org.el: New face `org-date-selected' for the selected calendar day.
[org-mode.git] / lisp / org.el
blobc600896e95c7625b061bfa25966a83aa3059fa07
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.8.09
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)
78 (require 'format-spec)
80 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
81 (when (fboundp 'defvaralias)
82 (unless (boundp 'calendar-view-holidays-initially-flag)
83 (defvaralias 'calendar-view-holidays-initially-flag
84 'view-calendar-holidays-initially))
85 (unless (boundp 'calendar-view-diary-initially-flag)
86 (defvaralias 'calendar-view-diary-initially-flag
87 'view-diary-entries-initially))
88 (unless (boundp 'diary-fancy-buffer)
89 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
91 (require 'outline) (require 'noutline)
92 ;; Other stuff we need.
93 (require 'time-date)
94 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
95 (require 'easymenu)
96 (require 'overlay)
98 (require 'org-macs)
99 (require 'org-entities)
100 (require 'org-compat)
101 (require 'org-faces)
102 (require 'org-list)
103 (require 'org-pcomplete)
104 (require 'org-src)
105 (require 'org-footnote)
107 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
108 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
109 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
111 (declare-function org-at-clock-log-p "org-clock" ())
112 (declare-function org-clock-timestamps-up "org-clock" ())
113 (declare-function org-clock-timestamps-down "org-clock" ())
115 ;; babel
116 (require 'ob)
117 (require 'ob-table)
118 (require 'ob-lob)
119 (require 'ob-ref)
120 (require 'ob-tangle)
121 (require 'ob-comint)
122 (require 'ob-keys)
124 ;; load languages based on value of `org-babel-load-languages'
125 (defvar org-babel-load-languages)
126 ;;;###autoload
127 (defun org-babel-do-load-languages (sym value)
128 "Load the languages defined in `org-babel-load-languages'."
129 (set-default sym value)
130 (mapc (lambda (pair)
131 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
132 (if active
133 (progn
134 (require (intern (concat "ob-" lang))))
135 (progn
136 (funcall 'fmakunbound
137 (intern (concat "org-babel-execute:" lang)))
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-expand-body:" lang)))))))
140 org-babel-load-languages))
142 (defcustom org-babel-load-languages '((emacs-lisp . t))
143 "Languages which can be evaluated in Org-mode buffers.
144 This list can be used to load support for any of the languages
145 below, note that each language will depend on a different set of
146 system executables and/or Emacs modes. When a language is
147 \"loaded\", then code blocks in that language can be evaluated
148 with `org-babel-execute-src-block' bound by default to C-c
149 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
150 be set to remove code block evaluation from the C-c C-c
151 keybinding. By default only Emacs Lisp (which has no
152 requirements) is loaded."
153 :group 'org-babel
154 :set 'org-babel-do-load-languages
155 :version "24.1"
156 :type '(alist :tag "Babel Languages"
157 :key-type
158 (choice
159 (const :tag "Awk" awk)
160 (const :tag "C" C)
161 (const :tag "R" R)
162 (const :tag "Asymptote" asymptote)
163 (const :tag "Calc" calc)
164 (const :tag "Clojure" clojure)
165 (const :tag "CSS" css)
166 (const :tag "Ditaa" ditaa)
167 (const :tag "Dot" dot)
168 (const :tag "Emacs Lisp" emacs-lisp)
169 (const :tag "Fortran" fortran)
170 (const :tag "Gnuplot" gnuplot)
171 (const :tag "Haskell" haskell)
172 (const :tag "Java" java)
173 (const :tag "Javascript" js)
174 (const :tag "Latex" latex)
175 (const :tag "Ledger" ledger)
176 (const :tag "Lilypond" lilypond)
177 (const :tag "Maxima" maxima)
178 (const :tag "Matlab" matlab)
179 (const :tag "Mscgen" mscgen)
180 (const :tag "Ocaml" ocaml)
181 (const :tag "Octave" octave)
182 (const :tag "Org" org)
183 (const :tag "Perl" perl)
184 (const :tag "Pico Lisp" picolisp)
185 (const :tag "PlantUML" plantuml)
186 (const :tag "Python" python)
187 (const :tag "Ruby" ruby)
188 (const :tag "Sass" sass)
189 (const :tag "Scheme" scheme)
190 (const :tag "Screen" screen)
191 (const :tag "Shell Script" sh)
192 (const :tag "Shen" shen)
193 (const :tag "Sql" sql)
194 (const :tag "Sqlite" sqlite))
195 :value-type (boolean :tag "Activate" :value t)))
197 ;;;; Customization variables
198 (defcustom org-clone-delete-id nil
199 "Remove ID property of clones of a subtree.
200 When non-nil, clones of a subtree don't inherit the ID property.
201 Otherwise they inherit the ID property with a new unique
202 identifier."
203 :type 'boolean
204 :version "24.1"
205 :group 'org-id)
207 ;;; Version
209 (defconst org-version "7.8.09"
210 "The version number of the file org.el.")
212 ;;;###autoload
213 (defun org-version (&optional here)
214 "Show the org-mode version in the echo area.
215 With prefix arg HERE, insert it at point."
216 (interactive "P")
217 (let* ((origin default-directory)
218 (version org-version)
219 (git-version)
220 (dir (concat (file-name-directory (locate-library "org")) "../" )))
221 (when (and (file-exists-p (expand-file-name ".git" dir))
222 (executable-find "git"))
223 (unwind-protect
224 (progn
225 (cd dir)
226 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
227 (with-current-buffer "*Shell Command Output*"
228 (goto-char (point-min))
229 (setq git-version (buffer-substring (point) (point-at-eol))))
230 (subst-char-in-string ?- ?. git-version t)
231 (when (string-match "\\S-"
232 (shell-command-to-string
233 "git diff-index --name-only HEAD --"))
234 (setq git-version (concat git-version ".dirty")))
235 (setq version (concat version " (" git-version ")"))))
236 (cd origin)))
237 (setq version (format "Org-mode version %s" version))
238 (if here (insert version))
239 (message version)))
241 ;;; Compatibility constants
243 ;;; The custom variables
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
290 (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)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
498 Not all export backends support this, but HTML does.
500 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-comment-string "COMMENT"
677 "Entries starting with this keyword will never be exported.
678 An entry can be toggled between COMMENT and normal with
679 \\[org-toggle-comment].
680 Changes become only effective after restarting Emacs."
681 :group 'org-keywords
682 :type 'string)
684 (defcustom org-quote-string "QUOTE"
685 "Entries starting with this keyword will be exported in fixed-width font.
686 Quoting applies only to the text in the entry following the headline, and does
687 not extend beyond the next headline, even if that is lower level.
688 An entry can be toggled between QUOTE and normal with
689 \\[org-toggle-fixed-width-section]."
690 :group 'org-keywords
691 :type 'string)
693 (defconst org-repeat-re
694 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
695 "Regular expression for specifying repeated events.
696 After a match, group 1 contains the repeat expression.")
698 (defgroup org-structure nil
699 "Options concerning the general structure of Org-mode files."
700 :tag "Org Structure"
701 :group 'org)
703 (defgroup org-reveal-location nil
704 "Options about how to make context of a location visible."
705 :tag "Org Reveal Location"
706 :group 'org-structure)
708 (defconst org-context-choice
709 '(choice
710 (const :tag "Always" t)
711 (const :tag "Never" nil)
712 (repeat :greedy t :tag "Individual contexts"
713 (cons
714 (choice :tag "Context"
715 (const agenda)
716 (const org-goto)
717 (const occur-tree)
718 (const tags-tree)
719 (const link-search)
720 (const mark-goto)
721 (const bookmark-jump)
722 (const isearch)
723 (const default))
724 (boolean))))
725 "Contexts for the reveal options.")
727 (defcustom org-show-hierarchy-above '((default . t))
728 "Non-nil means show full hierarchy when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the hierarchy of headings
731 above the exposed location is shown.
732 Turning this off for example for sparse trees makes them very compact.
733 Instead of t, this can also be an alist specifying this option for different
734 contexts. Valid contexts are
735 agenda when exposing an entry from the agenda
736 org-goto when using the command `org-goto' on key C-c C-j
737 occur-tree when using the command `org-occur' on key C-c /
738 tags-tree when constructing a sparse tree based on tags matches
739 link-search when exposing search matches associated with a link
740 mark-goto when exposing the jump goal of a mark
741 bookmark-jump when exposing a bookmark location
742 isearch when exiting from an incremental search
743 default default for all contexts not set explicitly"
744 :group 'org-reveal-location
745 :type org-context-choice)
747 (defcustom org-show-following-heading '((default . nil))
748 "Non-nil means show following heading when revealing a location.
749 Org-mode often shows locations in an org-mode file which might have
750 been invisible before. When this is set, the heading following the
751 match is shown.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-siblings '((default . nil) (isearch t))
761 "Non-nil means show all sibling heading when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the sibling of the current entry
764 heading are all made visible. If `org-show-hierarchy-above' is t,
765 the same happens on each level of the hierarchy above the current entry.
767 By default this is on for the isearch context, off for all other contexts.
768 Turning this off for example for sparse trees makes them very compact,
769 but makes it harder to edit the location of the match. In such a case,
770 use the command \\[org-reveal] to show more context.
771 Instead of t, this can also be an alist specifying this option for different
772 contexts. See `org-show-hierarchy-above' for valid contexts."
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-entry-below '((default . nil))
777 "Non-nil means show the entry below a headline when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the text below the headline that is
780 exposed is also shown.
782 By default this is off for all contexts.
783 Instead of t, this can also be an alist specifying this option for different
784 contexts. See `org-show-hierarchy-above' for valid contexts."
785 :group 'org-reveal-location
786 :type org-context-choice)
788 (defcustom org-indirect-buffer-display 'other-window
789 "How should indirect tree buffers be displayed?
790 This applies to indirect buffers created with the commands
791 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
792 Valid values are:
793 current-window Display in the current window
794 other-window Just display in another window.
795 dedicated-frame Create one new frame, and re-use it each time.
796 new-frame Make a new frame each time. Note that in this case
797 previously-made indirect buffers are kept, and you need to
798 kill these buffers yourself."
799 :group 'org-structure
800 :group 'org-agenda-windows
801 :type '(choice
802 (const :tag "In current window" current-window)
803 (const :tag "In current frame, other window" other-window)
804 (const :tag "Each time a new frame" new-frame)
805 (const :tag "One dedicated frame" dedicated-frame)))
807 (defcustom org-use-speed-commands nil
808 "Non-nil means activate single letter commands at beginning of a headline.
809 This may also be a function to test for appropriate locations where speed
810 commands should be active."
811 :group 'org-structure
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "At beginning of headline stars" t)
815 (function)))
817 (defcustom org-speed-commands-user nil
818 "Alist of additional speed commands.
819 This list will be checked before `org-speed-commands-default'
820 when the variable `org-use-speed-commands' is non-nil
821 and when the cursor is at the beginning of a headline.
822 The car if each entry is a string with a single letter, which must
823 be assigned to `self-insert-command' in the global map.
824 The cdr is either a command to be called interactively, a function
825 to be called, or a form to be evaluated.
826 An entry that is just a list with a single string will be interpreted
827 as a descriptive headline that will be added when listing the speed
828 commands in the Help buffer using the `?' speed command."
829 :group 'org-structure
830 :type '(repeat :value ("k" . ignore)
831 (choice :value ("k" . ignore)
832 (list :tag "Descriptive Headline" (string :tag "Headline"))
833 (cons :tag "Letter and Command"
834 (string :tag "Command letter")
835 (choice
836 (function)
837 (sexp))))))
839 (defgroup org-cycle nil
840 "Options concerning visibility cycling in Org-mode."
841 :tag "Org Cycle"
842 :group 'org-structure)
844 (defcustom org-cycle-skip-children-state-if-no-children t
845 "Non-nil means skip CHILDREN state in entries that don't have any."
846 :group 'org-cycle
847 :type 'boolean)
849 (defcustom org-cycle-max-level nil
850 "Maximum level which should still be subject to visibility cycling.
851 Levels higher than this will, for cycling, be treated as text, not a headline.
852 When `org-odd-levels-only' is set, a value of N in this variable actually
853 means 2N-1 stars as the limiting headline.
854 When nil, cycle all levels.
855 Note that the limiting level of cycling is also influenced by
856 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
857 `org-inlinetask-min-level' is, cycling will be limited to levels one less
858 than its value."
859 :group 'org-cycle
860 :type '(choice
861 (const :tag "No limit" nil)
862 (integer :tag "Maximum level")))
864 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
865 "Names of drawers. Drawers are not opened by cycling on the headline above.
866 Drawers only open with a TAB on the drawer line itself. A drawer looks like
867 this:
868 :DRAWERNAME:
869 .....
870 :END:
871 The drawer \"PROPERTIES\" is special for capturing properties through
872 the property API.
874 Drawers can be defined on the per-file basis with a line like:
876 #+DRAWERS: HIDDEN STATE PROPERTIES"
877 :group 'org-structure
878 :group 'org-cycle
879 :type '(repeat (string :tag "Drawer Name")))
881 (defcustom org-hide-block-startup nil
882 "Non-nil means entering Org-mode will fold all blocks.
883 This can also be set in on a per-file basis with
885 #+STARTUP: hideblocks
886 #+STARTUP: showblocks"
887 :group 'org-startup
888 :group 'org-cycle
889 :type 'boolean)
891 (defcustom org-cycle-global-at-bob nil
892 "Cycle globally if cursor is at beginning of buffer and not at a headline.
893 This makes it possible to do global cycling without having to use S-TAB or
894 \\[universal-argument] TAB. For this special case to work, the first line \
895 of the buffer
896 must not be a headline - it may be empty or some other text. When used in
897 this way, `org-cycle-hook' is disables temporarily, to make sure the
898 cursor stays at the beginning of the buffer.
899 When this option is nil, don't do anything special at the beginning
900 of the buffer."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-level-after-item/entry-creation t
905 "Non-nil means cycle entry level or item indentation in new empty entries.
907 When the cursor is at the end of an empty headline, i.e with only stars
908 and maybe a TODO keyword, TAB will then switch the entry to become a child,
909 and then all possible ancestor states, before returning to the original state.
910 This makes data entry extremely fast: M-RET to create a new headline,
911 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
913 When the cursor is at the end of an empty plain list item, one TAB will
914 make it a subitem, two or more tabs will back up to make this an item
915 higher up in the item hierarchy."
916 :group 'org-cycle
917 :type 'boolean)
919 (defcustom org-cycle-emulate-tab t
920 "Where should `org-cycle' emulate TAB.
921 nil Never
922 white Only in completely white lines
923 whitestart Only at the beginning of lines, before the first non-white char
924 t Everywhere except in headlines
925 exc-hl-bol Everywhere except at the start of a headline
926 If TAB is used in a place where it does not emulate TAB, the current subtree
927 visibility is cycled."
928 :group 'org-cycle
929 :type '(choice (const :tag "Never" nil)
930 (const :tag "Only in completely white lines" white)
931 (const :tag "Before first char in a line" whitestart)
932 (const :tag "Everywhere except in headlines" t)
933 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
936 (defcustom org-cycle-separator-lines 2
937 "Number of empty lines needed to keep an empty line between collapsed trees.
938 If you leave an empty line between the end of a subtree and the following
939 headline, this empty line is hidden when the subtree is folded.
940 Org-mode will leave (exactly) one empty line visible if the number of
941 empty lines is equal or larger to the number given in this variable.
942 So the default 2 means at least 2 empty lines after the end of a subtree
943 are needed to produce free space between a collapsed subtree and the
944 following headline.
946 If the number is negative, and the number of empty lines is at least -N,
947 all empty lines are shown.
949 Special case: when 0, never leave empty lines in collapsed view."
950 :group 'org-cycle
951 :type 'integer)
952 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
954 (defcustom org-pre-cycle-hook nil
955 "Hook that is run before visibility cycling is happening.
956 The function(s) in this hook must accept a single argument which indicates
957 the new state that will be set right after running this hook. The
958 argument is a symbol. Before a global state change, it can have the values
959 `overview', `content', or `all'. Before a local state change, it can have
960 the values `folded', `children', or `subtree'."
961 :group 'org-cycle
962 :type 'hook)
964 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
965 org-cycle-hide-drawers
966 org-cycle-show-empty-lines
967 org-optimize-window-after-visibility-change)
968 "Hook that is run after `org-cycle' has changed the buffer visibility.
969 The function(s) in this hook must accept a single argument which indicates
970 the new state that was set by the most recent `org-cycle' command. The
971 argument is a symbol. After a global state change, it can have the values
972 `overview', `content', or `all'. After a local state change, it can have
973 the values `folded', `children', or `subtree'."
974 :group 'org-cycle
975 :type 'hook)
977 (defgroup org-edit-structure nil
978 "Options concerning structure editing in Org-mode."
979 :tag "Org Edit Structure"
980 :group 'org-structure)
982 (defcustom org-odd-levels-only nil
983 "Non-nil means skip even levels and only use odd levels for the outline.
984 This has the effect that two stars are being added/taken away in
985 promotion/demotion commands. It also influences how levels are
986 handled by the exporters.
987 Changing it requires restart of `font-lock-mode' to become effective
988 for fontification also in regions already fontified.
989 You may also set this on a per-file basis by adding one of the following
990 lines to the buffer:
992 #+STARTUP: odd
993 #+STARTUP: oddeven"
994 :group 'org-edit-structure
995 :group 'org-appearance
996 :type 'boolean)
998 (defcustom org-adapt-indentation t
999 "Non-nil means adapt indentation to outline node level.
1001 When this variable is set, Org assumes that you write outlines by
1002 indenting text in each node to align with the headline (after the stars).
1003 The following issues are influenced by this variable:
1005 - When this is set and the *entire* text in an entry is indented, the
1006 indentation is increased by one space in a demotion command, and
1007 decreased by one in a promotion command. If any line in the entry
1008 body starts with text at column 0, indentation is not changed at all.
1010 - Property drawers and planning information is inserted indented when
1011 this variable s set. When nil, they will not be indented.
1013 - TAB indents a line relative to context. The lines below a headline
1014 will be indented when this variable is set.
1016 Note that this is all about true indentation, by adding and removing
1017 space characters. See also `org-indent.el' which does level-dependent
1018 indentation in a virtual way, i.e. at display time in Emacs."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1022 (defcustom org-special-ctrl-a/e nil
1023 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1025 When t, `C-a' will bring back the cursor to the beginning of the
1026 headline text, i.e. after the stars and after a possible TODO keyword.
1027 In an item, this will be the position after the bullet.
1028 When the cursor is already at that position, another `C-a' will bring
1029 it to the beginning of the line.
1031 `C-e' will jump to the end of the headline, ignoring the presence of tags
1032 in the headline. A second `C-e' will then jump to the true end of the
1033 line, after any tags. This also means that, when this variable is
1034 non-nil, `C-e' also will never jump beyond the end of the heading of a
1035 folded section, i.e. not after the ellipses.
1037 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1038 going to the true line boundary first. Only a directly following, identical
1039 keypress will bring the cursor to the special positions.
1041 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1042 set separately."
1043 :group 'org-edit-structure
1044 :type '(choice
1045 (const :tag "off" nil)
1046 (const :tag "on: after stars/bullet and before tags first" t)
1047 (const :tag "reversed: true line boundary first" reversed)
1048 (cons :tag "Set C-a and C-e separately"
1049 (choice :tag "Special C-a"
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet first" t)
1052 (const :tag "reversed: before stars/bullet first" reversed))
1053 (choice :tag "Special C-e"
1054 (const :tag "off" nil)
1055 (const :tag "on: before tags first" t)
1056 (const :tag "reversed: after tags first" reversed)))))
1057 (if (fboundp 'defvaralias)
1058 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1060 (defcustom org-special-ctrl-k nil
1061 "Non-nil means `C-k' will behave specially in headlines.
1062 When nil, `C-k' will call the default `kill-line' command.
1063 When t, the following will happen while the cursor is in the headline:
1065 - When the cursor is at the beginning of a headline, kill the entire
1066 line and possible the folded subtree below the line.
1067 - When in the middle of the headline text, kill the headline up to the tags.
1068 - When after the headline text, kill the tags."
1069 :group 'org-edit-structure
1070 :type 'boolean)
1072 (defcustom org-ctrl-k-protect-subtree nil
1073 "Non-nil means, do not delete a hidden subtree with C-k.
1074 When set to the symbol `error', simply throw an error when C-k is
1075 used to kill (part-of) a headline that has hidden text behind it.
1076 Any other non-nil value will result in a query to the user, if it is
1077 OK to kill that hidden subtree. When nil, kill without remorse."
1078 :group 'org-edit-structure
1079 :version "24.1"
1080 :type '(choice
1081 (const :tag "Do not protect hidden subtrees" nil)
1082 (const :tag "Protect hidden subtrees with a security query" t)
1083 (const :tag "Never kill a hidden subtree with C-k" error)))
1085 (defcustom org-catch-invisible-edits nil
1086 "Check if in invisible region before inserting or deleting a character.
1087 Valid values are:
1089 nil Do not check, so just do invisible edits.
1090 error Throw an error and do nothing.
1091 show Make point visible, and do the requested edit.
1092 show-and-error Make point visible, then throw an error and abort the edit.
1093 smart Make point visible, and do insertion/deletion if it is
1094 adjacent to visible text and the change feels predictable.
1095 Never delete a previously invisible character or add in the
1096 middle or right after an invisible region. Basically, this
1097 allows insertion and backward-delete right before ellipses.
1098 FIXME: maybe in this case we should not even show?"
1099 :group 'org-edit-structure
1100 :version "24.1"
1101 :type '(choice
1102 (const :tag "Do not check" nil)
1103 (const :tag "Throw error when trying to edit" error)
1104 (const :tag "Unhide, but do not do the edit" show-and-error)
1105 (const :tag "Show invisible part and do the edit" show)
1106 (const :tag "Be smart and do the right thing" smart)))
1108 (defcustom org-yank-folded-subtrees t
1109 "Non-nil means when yanking subtrees, fold them.
1110 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1111 it starts with a heading and all other headings in it are either children
1112 or siblings, then fold all the subtrees. However, do this only if no
1113 text after the yank would be swallowed into a folded tree by this action."
1114 :group 'org-edit-structure
1115 :type 'boolean)
1117 (defcustom org-yank-adjusted-subtrees nil
1118 "Non-nil means when yanking subtrees, adjust the level.
1119 With this setting, `org-paste-subtree' is used to insert the subtree, see
1120 this function for details."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-M-RET-may-split-line '((default . t))
1125 "Non-nil means M-RET will split the line at the cursor position.
1126 When nil, it will go to the end of the line before making a
1127 new line.
1128 You may also set this option in a different way for different
1129 contexts. Valid contexts are:
1131 headline when creating a new headline
1132 item when creating a new item
1133 table in a table field
1134 default the value to be used for all contexts not explicitly
1135 customized"
1136 :group 'org-structure
1137 :group 'org-table
1138 :type '(choice
1139 (const :tag "Always" t)
1140 (const :tag "Never" nil)
1141 (repeat :greedy t :tag "Individual contexts"
1142 (cons
1143 (choice :tag "Context"
1144 (const headline)
1145 (const item)
1146 (const table)
1147 (const default))
1148 (boolean)))))
1151 (defcustom org-insert-heading-respect-content nil
1152 "Non-nil means insert new headings after the current subtree.
1153 When nil, the new heading is created directly after the current line.
1154 The commands \\[org-insert-heading-respect-content] and
1155 \\[org-insert-todo-heading-respect-content] turn this variable on
1156 for the duration of the command."
1157 :group 'org-structure
1158 :type 'boolean)
1160 (defcustom org-blank-before-new-entry '((heading . auto)
1161 (plain-list-item . auto))
1162 "Should `org-insert-heading' leave a blank line before new heading/item?
1163 The value is an alist, with `heading' and `plain-list-item' as CAR,
1164 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1165 which case Org will look at the surrounding headings/items and try to
1166 make an intelligent decision whether to insert a blank line or not.
1168 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1169 set, the setting here is ignored and no empty line is inserted, to avoid
1170 breaking the list structure."
1171 :group 'org-edit-structure
1172 :type '(list
1173 (cons (const heading)
1174 (choice (const :tag "Never" nil)
1175 (const :tag "Always" t)
1176 (const :tag "Auto" auto)))
1177 (cons (const plain-list-item)
1178 (choice (const :tag "Never" nil)
1179 (const :tag "Always" t)
1180 (const :tag "Auto" auto)))))
1182 (defcustom org-insert-heading-hook nil
1183 "Hook being run after inserting a new heading."
1184 :group 'org-edit-structure
1185 :type 'hook)
1187 (defcustom org-enable-fixed-width-editor t
1188 "Non-nil means lines starting with \":\" are treated as fixed-width.
1189 This currently only means they are never auto-wrapped.
1190 When nil, such lines will be treated like ordinary lines.
1191 See also the QUOTE keyword."
1192 :group 'org-edit-structure
1193 :type 'boolean)
1195 (defcustom org-goto-auto-isearch t
1196 "Non-nil means typing characters in `org-goto' starts incremental search."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defgroup org-sparse-trees nil
1201 "Options concerning sparse trees in Org-mode."
1202 :tag "Org Sparse Trees"
1203 :group 'org-structure)
1205 (defcustom org-highlight-sparse-tree-matches t
1206 "Non-nil means highlight all matches that define a sparse tree.
1207 The highlights will automatically disappear the next time the buffer is
1208 changed by an edit command."
1209 :group 'org-sparse-trees
1210 :type 'boolean)
1212 (defcustom org-remove-highlights-with-change t
1213 "Non-nil means any change to the buffer will remove temporary highlights.
1214 Such highlights are created by `org-occur' and `org-clock-display'.
1215 When nil, `C-c C-c needs to be used to get rid of the highlights.
1216 The highlights created by `org-preview-latex-fragment' always need
1217 `C-c C-c' to be removed."
1218 :group 'org-sparse-trees
1219 :group 'org-time
1220 :type 'boolean)
1223 (defcustom org-occur-hook '(org-first-headline-recenter)
1224 "Hook that is run after `org-occur' has constructed a sparse tree.
1225 This can be used to recenter the window to show as much of the structure
1226 as possible."
1227 :group 'org-sparse-trees
1228 :type 'hook)
1230 (defgroup org-imenu-and-speedbar nil
1231 "Options concerning imenu and speedbar in Org-mode."
1232 :tag "Org Imenu and Speedbar"
1233 :group 'org-structure)
1235 (defcustom org-imenu-depth 2
1236 "The maximum level for Imenu access to Org-mode headlines.
1237 This also applied for speedbar access."
1238 :group 'org-imenu-and-speedbar
1239 :type 'integer)
1241 (defgroup org-table nil
1242 "Options concerning tables in Org-mode."
1243 :tag "Org Table"
1244 :group 'org)
1246 (defcustom org-enable-table-editor 'optimized
1247 "Non-nil means lines starting with \"|\" are handled by the table editor.
1248 When nil, such lines will be treated like ordinary lines.
1250 When equal to the symbol `optimized', the table editor will be optimized to
1251 do the following:
1252 - Automatic overwrite mode in front of whitespace in table fields.
1253 This makes the structure of the table stay in tact as long as the edited
1254 field does not exceed the column width.
1255 - Minimize the number of realigns. Normally, the table is aligned each time
1256 TAB or RET are pressed to move to another field. With optimization this
1257 happens only if changes to a field might have changed the column width.
1258 Optimization requires replacing the functions `self-insert-command',
1259 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1260 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1261 very good at guessing when a re-align will be necessary, but you can always
1262 force one with \\[org-ctrl-c-ctrl-c].
1264 If you would like to use the optimized version in Org-mode, but the
1265 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1267 This variable can be used to turn on and off the table editor during a session,
1268 but in order to toggle optimization, a restart is required.
1270 See also the variable `org-table-auto-blank-field'."
1271 :group 'org-table
1272 :type '(choice
1273 (const :tag "off" nil)
1274 (const :tag "on" t)
1275 (const :tag "on, optimized" optimized)))
1277 (defcustom org-self-insert-cluster-for-undo t
1278 "Non-nil means cluster self-insert commands for undo when possible.
1279 If this is set, then, like in the Emacs command loop, 20 consecutive
1280 characters will be undone together.
1281 This is configurable, because there is some impact on typing performance."
1282 :group 'org-table
1283 :type 'boolean)
1285 (defcustom org-table-tab-recognizes-table.el t
1286 "Non-nil means TAB will automatically notice a table.el table.
1287 When it sees such a table, it moves point into it and - if necessary -
1288 calls `table-recognize-table'."
1289 :group 'org-table-editing
1290 :type 'boolean)
1292 (defgroup org-link nil
1293 "Options concerning links in Org-mode."
1294 :tag "Org Link"
1295 :group 'org)
1297 (defvar org-link-abbrev-alist-local nil
1298 "Buffer-local version of `org-link-abbrev-alist', which see.
1299 The value of this is taken from the #+LINK lines.")
1300 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1302 (defcustom org-link-abbrev-alist nil
1303 "Alist of link abbreviations.
1304 The car of each element is a string, to be replaced at the start of a link.
1305 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1306 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1308 [[linkkey:tag][description]]
1310 The 'linkkey' must be a word word, starting with a letter, followed
1311 by letters, numbers, '-' or '_'.
1313 If REPLACE is a string, the tag will simply be appended to create the link.
1314 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1315 the placeholder \"%h\" will cause a url-encoded version of the tag to
1316 be inserted at that point (see the function `url-hexify-string').
1318 REPLACE may also be a function that will be called with the tag as the
1319 only argument to create the link, which should be returned as a string.
1321 See the manual for examples."
1322 :group 'org-link
1323 :type '(repeat
1324 (cons
1325 (string :tag "Protocol")
1326 (choice
1327 (string :tag "Format")
1328 (function)))))
1330 (defcustom org-descriptive-links t
1331 "Non-nil means Org will display descriptive links.
1332 E.g. [[http://orgmode.org][Org website]] will be displayed as
1333 \"Org Website\", hiding the link itself and just displaying its
1334 description. When set to `nil', Org will display the full links
1335 literally.
1337 You can interactively set the value of this variable by calling
1338 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1339 :group 'org-link
1340 :type 'boolean)
1342 (defcustom org-link-file-path-type 'adaptive
1343 "How the path name in file links should be stored.
1344 Valid values are:
1346 relative Relative to the current directory, i.e. the directory of the file
1347 into which the link is being inserted.
1348 absolute Absolute path, if possible with ~ for home directory.
1349 noabbrev Absolute path, no abbreviation of home directory.
1350 adaptive Use relative path for files in the current directory and sub-
1351 directories of it. For other files, use an absolute path."
1352 :group 'org-link
1353 :type '(choice
1354 (const relative)
1355 (const absolute)
1356 (const noabbrev)
1357 (const adaptive)))
1359 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1360 "Types of links that should be activated in Org-mode files.
1361 This is a list of symbols, each leading to the activation of a certain link
1362 type. In principle, it does not hurt to turn on most link types - there may
1363 be a small gain when turning off unused link types. The types are:
1365 bracket The recommended [[link][description]] or [[link]] links with hiding.
1366 angle Links in angular brackets that may contain whitespace like
1367 <bbdb:Carsten Dominik>.
1368 plain Plain links in normal text, no whitespace, like http://google.com.
1369 radio Text that is matched by a radio target, see manual for details.
1370 tag Tag settings in a headline (link to tag search).
1371 date Time stamps (link to calendar).
1372 footnote Footnote labels.
1374 Changing this variable requires a restart of Emacs to become effective."
1375 :group 'org-link
1376 :type '(set :greedy t
1377 (const :tag "Double bracket links" bracket)
1378 (const :tag "Angular bracket links" angle)
1379 (const :tag "Plain text links" plain)
1380 (const :tag "Radio target matches" radio)
1381 (const :tag "Tags" tag)
1382 (const :tag "Timestamps" date)
1383 (const :tag "Footnotes" footnote)))
1385 (defcustom org-make-link-description-function nil
1386 "Function to use to generate link descriptions from links.
1387 If nil the link location will be used. This function must take
1388 two parameters; the first is the link and the second the
1389 description `org-insert-link' has generated, and should return the
1390 description to use."
1391 :group 'org-link
1392 :type 'function)
1394 (defgroup org-link-store nil
1395 "Options concerning storing links in Org-mode."
1396 :tag "Org Store Link"
1397 :group 'org-link)
1399 (defcustom org-email-link-description-format "Email %c: %.30s"
1400 "Format of the description part of a link to an email or usenet message.
1401 The following %-escapes will be replaced by corresponding information:
1403 %F full \"From\" field
1404 %f name, taken from \"From\" field, address if no name
1405 %T full \"To\" field
1406 %t first name in \"To\" field, address if no name
1407 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1408 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1409 %s subject
1410 %d date
1411 %m message-id.
1413 You may use normal field width specification between the % and the letter.
1414 This is for example useful to limit the length of the subject.
1416 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1417 :group 'org-link-store
1418 :type 'string)
1420 (defcustom org-from-is-user-regexp
1421 (let (r1 r2)
1422 (when (and user-mail-address (not (string= user-mail-address "")))
1423 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1424 (when (and user-full-name (not (string= user-full-name "")))
1425 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1426 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1427 "Regexp matched against the \"From:\" header of an email or usenet message.
1428 It should match if the message is from the user him/herself."
1429 :group 'org-link-store
1430 :type 'regexp)
1432 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1433 "Non-nil means storing a link to an Org file will use entry IDs.
1435 Note that before this variable is even considered, org-id must be loaded,
1436 so please customize `org-modules' and turn it on.
1438 The variable can have the following values:
1440 t Create an ID if needed to make a link to the current entry.
1442 create-if-interactive
1443 If `org-store-link' is called directly (interactively, as a user
1444 command), do create an ID to support the link. But when doing the
1445 job for remember, only use the ID if it already exists. The
1446 purpose of this setting is to avoid proliferation of unwanted
1447 IDs, just because you happen to be in an Org file when you
1448 call `org-remember' that automatically and preemptively
1449 creates a link. If you do want to get an ID link in a remember
1450 template to an entry not having an ID, create it first by
1451 explicitly creating a link to it, using `C-c C-l' first.
1453 create-if-interactive-and-no-custom-id
1454 Like create-if-interactive, but do not create an ID if there is
1455 a CUSTOM_ID property defined in the entry. This is the default.
1457 use-existing
1458 Use existing ID, do not create one.
1460 nil Never use an ID to make a link, instead link using a text search for
1461 the headline text."
1462 :group 'org-link-store
1463 :type '(choice
1464 (const :tag "Create ID to make link" t)
1465 (const :tag "Create if storing link interactively"
1466 create-if-interactive)
1467 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1468 create-if-interactive-and-no-custom-id)
1469 (const :tag "Only use existing" use-existing)
1470 (const :tag "Do not use ID to create link" nil)))
1472 (defcustom org-context-in-file-links t
1473 "Non-nil means file links from `org-store-link' contain context.
1474 A search string will be added to the file name with :: as separator and
1475 used to find the context when the link is activated by the command
1476 `org-open-at-point'. When this option is t, the entire active region
1477 will be placed in the search string of the file link. If set to a
1478 positive integer, only the first n lines of context will be stored.
1480 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1481 negates this setting for the duration of the command."
1482 :group 'org-link-store
1483 :type '(choice boolean integer))
1485 (defcustom org-keep-stored-link-after-insertion nil
1486 "Non-nil means keep link in list for entire session.
1488 The command `org-store-link' adds a link pointing to the current
1489 location to an internal list. These links accumulate during a session.
1490 The command `org-insert-link' can be used to insert links into any
1491 Org-mode file (offering completion for all stored links). When this
1492 option is nil, every link which has been inserted once using \\[org-insert-link]
1493 will be removed from the list, to make completing the unused links
1494 more efficient."
1495 :group 'org-link-store
1496 :type 'boolean)
1498 (defgroup org-link-follow nil
1499 "Options concerning following links in Org-mode."
1500 :tag "Org Follow Link"
1501 :group 'org-link)
1503 (defcustom org-link-translation-function nil
1504 "Function to translate links with different syntax to Org syntax.
1505 This can be used to translate links created for example by the Planner
1506 or emacs-wiki packages to Org syntax.
1507 The function must accept two parameters, a TYPE containing the link
1508 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1509 which is everything after the link protocol. It should return a cons
1510 with possibly modified values of type and path.
1511 Org contains a function for this, so if you set this variable to
1512 `org-translate-link-from-planner', you should be able follow many
1513 links created by planner."
1514 :group 'org-link-follow
1515 :type 'function)
1517 (defcustom org-follow-link-hook nil
1518 "Hook that is run after a link has been followed."
1519 :group 'org-link-follow
1520 :type 'hook)
1522 (defcustom org-tab-follows-link nil
1523 "Non-nil means on links TAB will follow the link.
1524 Needs to be set before org.el is loaded.
1525 This really should not be used, it does not make sense, and the
1526 implementation is bad."
1527 :group 'org-link-follow
1528 :type 'boolean)
1530 (defcustom org-return-follows-link nil
1531 "Non-nil means on links RET will follow the link."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-mouse-1-follows-link
1536 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1537 "Non-nil means mouse-1 on a link will follow the link.
1538 A longer mouse click will still set point. Does not work on XEmacs.
1539 Needs to be set before org.el is loaded."
1540 :group 'org-link-follow
1541 :type 'boolean)
1543 (defcustom org-mark-ring-length 4
1544 "Number of different positions to be recorded in the ring.
1545 Changing this requires a restart of Emacs to work correctly."
1546 :group 'org-link-follow
1547 :type 'integer)
1549 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1550 "Non-nil means internal links in Org files must exactly match a headline.
1551 When nil, the link search tries to match a phrase with all words
1552 in the search text."
1553 :group 'org-link-follow
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Use fuzzy text search" nil)
1557 (const :tag "Match only exact headline" t)
1558 (const :tag "Match exact headline or query to create it"
1559 query-to-create)))
1561 (defcustom org-link-frame-setup
1562 '((vm . vm-visit-folder-other-frame)
1563 (gnus . org-gnus-no-new-news)
1564 (file . find-file-other-window)
1565 (wl . wl-other-frame))
1566 "Setup the frame configuration for following links.
1567 When following a link with Emacs, it may often be useful to display
1568 this link in another window or frame. This variable can be used to
1569 set this up for the different types of links.
1570 For VM, use any of
1571 `vm-visit-folder'
1572 `vm-visit-folder-other-window'
1573 `vm-visit-folder-other-frame'
1574 For Gnus, use any of
1575 `gnus'
1576 `gnus-other-frame'
1577 `org-gnus-no-new-news'
1578 For FILE, use any of
1579 `find-file'
1580 `find-file-other-window'
1581 `find-file-other-frame'
1582 For Wanderlust use any of
1583 `wl'
1584 `wl-other-frame'
1585 For the calendar, use the variable `calendar-setup'.
1586 For BBDB, it is currently only possible to display the matches in
1587 another window."
1588 :group 'org-link-follow
1589 :type '(list
1590 (cons (const vm)
1591 (choice
1592 (const vm-visit-folder)
1593 (const vm-visit-folder-other-window)
1594 (const vm-visit-folder-other-frame)))
1595 (cons (const gnus)
1596 (choice
1597 (const gnus)
1598 (const gnus-other-frame)
1599 (const org-gnus-no-new-news)))
1600 (cons (const file)
1601 (choice
1602 (const find-file)
1603 (const find-file-other-window)
1604 (const find-file-other-frame)))
1605 (cons (const wl)
1606 (choice
1607 (const wl)
1608 (const wl-other-frame)))))
1610 (defcustom org-display-internal-link-with-indirect-buffer nil
1611 "Non-nil means use indirect buffer to display infile links.
1612 Activating internal links (from one location in a file to another location
1613 in the same file) normally just jumps to the location. When the link is
1614 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1615 is displayed in
1616 another window. When this option is set, the other window actually displays
1617 an indirect buffer clone of the current buffer, to avoid any visibility
1618 changes to the current buffer."
1619 :group 'org-link-follow
1620 :type 'boolean)
1622 (defcustom org-open-non-existing-files nil
1623 "Non-nil means `org-open-file' will open non-existing files.
1624 When nil, an error will be generated.
1625 This variable applies only to external applications because they
1626 might choke on non-existing files. If the link is to a file that
1627 will be opened in Emacs, the variable is ignored."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-open-directory-means-index-dot-org nil
1632 "Non-nil means a link to a directory really means to index.org.
1633 When nil, following a directory link will run dired or open a finder/explorer
1634 window on that directory."
1635 :group 'org-link-follow
1636 :type 'boolean)
1638 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1639 "Function and arguments to call for following mailto links.
1640 This is a list with the first element being a Lisp function, and the
1641 remaining elements being arguments to the function. In string arguments,
1642 %a will be replaced by the address, and %s will be replaced by the subject
1643 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1644 :group 'org-link-follow
1645 :type '(choice
1646 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1647 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1648 (const :tag "message-mail" (message-mail "%a" "%s"))
1649 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1651 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1652 "Non-nil means ask for confirmation before executing shell links.
1653 Shell links can be dangerous: just think about a link
1655 [[shell:rm -rf ~/*][Google Search]]
1657 This link would show up in your Org-mode document as \"Google Search\",
1658 but really it would remove your entire home directory.
1659 Therefore we advise against setting this variable to nil.
1660 Just change it to `y-or-n-p' if you want to confirm with a
1661 single keystroke rather than having to type \"yes\"."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1665 (const :tag "with y-or-n (faster)" y-or-n-p)
1666 (const :tag "no confirmation (dangerous)" nil)))
1667 (put 'org-confirm-shell-link-function
1668 'safe-local-variable
1669 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1671 (defcustom org-confirm-shell-link-not-regexp ""
1672 "A regexp to skip confirmation for shell links."
1673 :group 'org-link-follow
1674 :version "24.1"
1675 :type 'regexp)
1677 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1678 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1679 Elisp links can be dangerous: just think about a link
1681 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1683 This link would show up in your Org-mode document as \"Google Search\",
1684 but really it would remove your entire home directory.
1685 Therefore we advise against setting this variable to nil.
1686 Just change it to `y-or-n-p' if you want to confirm with a
1687 single keystroke rather than having to type \"yes\"."
1688 :group 'org-link-follow
1689 :type '(choice
1690 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1691 (const :tag "with y-or-n (faster)" y-or-n-p)
1692 (const :tag "no confirmation (dangerous)" nil)))
1693 (put 'org-confirm-shell-link-function
1694 'safe-local-variable
1695 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1697 (defcustom org-confirm-elisp-link-not-regexp ""
1698 "A regexp to skip confirmation for Elisp links."
1699 :group 'org-link-follow
1700 :version "24.1"
1701 :type 'regexp)
1703 (defconst org-file-apps-defaults-gnu
1704 '((remote . emacs)
1705 (system . mailcap)
1706 (t . mailcap))
1707 "Default file applications on a UNIX or GNU/Linux system.
1708 See `org-file-apps'.")
1710 (defconst org-file-apps-defaults-macosx
1711 '((remote . emacs)
1712 (t . "open %s")
1713 (system . "open %s")
1714 ("ps.gz" . "gv %s")
1715 ("eps.gz" . "gv %s")
1716 ("dvi" . "xdvi %s")
1717 ("fig" . "xfig %s"))
1718 "Default file applications on a MacOS X system.
1719 The system \"open\" is known as a default, but we use X11 applications
1720 for some files for which the OS does not have a good default.
1721 See `org-file-apps'.")
1723 (defconst org-file-apps-defaults-windowsnt
1724 (list
1725 '(remote . emacs)
1726 (cons t
1727 (list (if (featurep 'xemacs)
1728 'mswindows-shell-execute
1729 'w32-shell-execute)
1730 "open" 'file))
1731 (cons 'system
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file)))
1736 "Default file applications on a Windows NT system.
1737 The system \"open\" is used for most files.
1738 See `org-file-apps'.")
1740 (defcustom org-file-apps
1742 (auto-mode . emacs)
1743 ("\\.mm\\'" . default)
1744 ("\\.x?html?\\'" . default)
1745 ("\\.pdf\\'" . default)
1747 "External applications for opening `file:path' items in a document.
1748 Org-mode uses system defaults for different file types, but
1749 you can use this variable to set the application for a given file
1750 extension. The entries in this list are cons cells where the car identifies
1751 files and the cdr the corresponding command. Possible values for the
1752 file identifier are
1753 \"string\" A string as a file identifier can be interpreted in different
1754 ways, depending on its contents:
1756 - Alphanumeric characters only:
1757 Match links with this file extension.
1758 Example: (\"pdf\" . \"evince %s\")
1759 to open PDFs with evince.
1761 - Regular expression: Match links where the
1762 filename matches the regexp. If you want to
1763 use groups here, use shy groups.
1765 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1766 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1767 to open *.html and *.xhtml with firefox.
1769 - Regular expression which contains (non-shy) groups:
1770 Match links where the whole link, including \"::\", and
1771 anything after that, matches the regexp.
1772 In a custom command string, %1, %2, etc. are replaced with
1773 the parts of the link that were matched by the groups.
1774 For backwards compatibility, if a command string is given
1775 that does not use any of the group matches, this case is
1776 handled identically to the second one (i.e. match against
1777 file name only).
1778 In a custom lisp form, you can access the group matches with
1779 (match-string n link).
1781 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1782 to open [[file:document.pdf::5]] with evince at page 5.
1784 `directory' Matches a directory
1785 `remote' Matches a remote file, accessible through tramp or efs.
1786 Remote files most likely should be visited through Emacs
1787 because external applications cannot handle such paths.
1788 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1789 so all files Emacs knows how to handle. Using this with
1790 command `emacs' will open most files in Emacs. Beware that this
1791 will also open html files inside Emacs, unless you add
1792 (\"html\" . default) to the list as well.
1793 t Default for files not matched by any of the other options.
1794 `system' The system command to open files, like `open' on Windows
1795 and Mac OS X, and mailcap under GNU/Linux. This is the command
1796 that will be selected if you call `C-c C-o' with a double
1797 \\[universal-argument] \\[universal-argument] prefix.
1799 Possible values for the command are:
1800 `emacs' The file will be visited by the current Emacs process.
1801 `default' Use the default application for this file type, which is the
1802 association for t in the list, most likely in the system-specific
1803 part.
1804 This can be used to overrule an unwanted setting in the
1805 system-specific variable.
1806 `system' Use the system command for opening files, like \"open\".
1807 This command is specified by the entry whose car is `system'.
1808 Most likely, the system-specific version of this variable
1809 does define this command, but you can overrule/replace it
1810 here.
1811 string A command to be executed by a shell; %s will be replaced
1812 by the path to the file.
1813 sexp A Lisp form which will be evaluated. The file path will
1814 be available in the Lisp variable `file'.
1815 For more examples, see the system specific constants
1816 `org-file-apps-defaults-macosx'
1817 `org-file-apps-defaults-windowsnt'
1818 `org-file-apps-defaults-gnu'."
1819 :group 'org-link-follow
1820 :type '(repeat
1821 (cons (choice :value ""
1822 (string :tag "Extension")
1823 (const :tag "System command to open files" system)
1824 (const :tag "Default for unrecognized files" t)
1825 (const :tag "Remote file" remote)
1826 (const :tag "Links to a directory" directory)
1827 (const :tag "Any files that have Emacs modes"
1828 auto-mode))
1829 (choice :value ""
1830 (const :tag "Visit with Emacs" emacs)
1831 (const :tag "Use default" default)
1832 (const :tag "Use the system command" system)
1833 (string :tag "Command")
1834 (sexp :tag "Lisp form")))))
1838 (defgroup org-refile nil
1839 "Options concerning refiling entries in Org-mode."
1840 :tag "Org Refile"
1841 :group 'org)
1843 (defcustom org-directory "~/org"
1844 "Directory with org files.
1845 This is just a default location to look for Org files. There is no need
1846 at all to put your files into this directory. It is only used in the
1847 following situations:
1849 1. When a remember template specifies a target file that is not an
1850 absolute path. The path will then be interpreted relative to
1851 `org-directory'
1852 2. When a remember note is filed away in an interactive way (when exiting the
1853 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1854 with `org-directory' as the default path."
1855 :group 'org-refile
1856 :group 'org-remember
1857 :type 'directory)
1859 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1860 "Default target for storing notes.
1861 Used as a fall back file for org-remember.el and org-capture.el, for
1862 templates that do not specify a target file."
1863 :group 'org-refile
1864 :group 'org-remember
1865 :type '(choice
1866 (const :tag "Default from remember-data-file" nil)
1867 file))
1869 (defcustom org-goto-interface 'outline
1870 "The default interface to be used for `org-goto'.
1871 Allowed values are:
1872 outline The interface shows an outline of the relevant file
1873 and the correct heading is found by moving through
1874 the outline or by searching with incremental search.
1875 outline-path-completion Headlines in the current buffer are offered via
1876 completion. This is the interface also used by
1877 the refile command."
1878 :group 'org-refile
1879 :type '(choice
1880 (const :tag "Outline" outline)
1881 (const :tag "Outline-path-completion" outline-path-completion)))
1883 (defcustom org-goto-max-level 5
1884 "Maximum target level when running `org-goto' with refile interface."
1885 :group 'org-refile
1886 :type 'integer)
1888 (defcustom org-reverse-note-order nil
1889 "Non-nil means store new notes at the beginning of a file or entry.
1890 When nil, new notes will be filed to the end of a file or entry.
1891 This can also be a list with cons cells of regular expressions that
1892 are matched against file names, and values."
1893 :group 'org-remember
1894 :group 'org-refile
1895 :type '(choice
1896 (const :tag "Reverse always" t)
1897 (const :tag "Reverse never" nil)
1898 (repeat :tag "By file name regexp"
1899 (cons regexp boolean))))
1901 (defcustom org-log-refile nil
1902 "Information to record when a task is refiled.
1904 Possible values are:
1906 nil Don't add anything
1907 time Add a time stamp to the task
1908 note Prompt for a note and add it with template `org-log-note-headings'
1910 This option can also be set with on a per-file-basis with
1912 #+STARTUP: nologrefile
1913 #+STARTUP: logrefile
1914 #+STARTUP: lognoterefile
1916 You can have local logging settings for a subtree by setting the LOGGING
1917 property to one or more of these keywords.
1919 When bulk-refiling from the agenda, the value `note' is forbidden and
1920 will temporarily be changed to `time'."
1921 :group 'org-refile
1922 :group 'org-progress
1923 :version "24.1"
1924 :type '(choice
1925 (const :tag "No logging" nil)
1926 (const :tag "Record timestamp" time)
1927 (const :tag "Record timestamp with note." note)))
1929 (defcustom org-refile-targets nil
1930 "Targets for refiling entries with \\[org-refile].
1931 This is a list of cons cells. Each cell contains:
1932 - a specification of the files to be considered, either a list of files,
1933 or a symbol whose function or variable value will be used to retrieve
1934 a file name or a list of file names. If you use `org-agenda-files' for
1935 that, all agenda files will be scanned for targets. Nil means consider
1936 headings in the current buffer.
1937 - A specification of how to find candidate refile targets. This may be
1938 any of:
1939 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1940 This tag has to be present in all target headlines, inheritance will
1941 not be considered.
1942 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1943 todo keyword.
1944 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1945 headlines that are refiling targets.
1946 - a cons cell (:level . N). Any headline of level N is considered a target.
1947 Note that, when `org-odd-levels-only' is set, level corresponds to
1948 order in hierarchy, not to the number of stars.
1949 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1950 Note that, when `org-odd-levels-only' is set, level corresponds to
1951 order in hierarchy, not to the number of stars.
1953 Each element of this list generates a set of possible targets.
1954 The union of these sets is presented (with completion) to
1955 the user by `org-refile'.
1957 You can set the variable `org-refile-target-verify-function' to a function
1958 to verify each headline found by the simple criteria above.
1960 When this variable is nil, all top-level headlines in the current buffer
1961 are used, equivalent to the value `((nil . (:level . 1))'."
1962 :group 'org-refile
1963 :type '(repeat
1964 (cons
1965 (choice :value org-agenda-files
1966 (const :tag "All agenda files" org-agenda-files)
1967 (const :tag "Current buffer" nil)
1968 (function) (variable) (file))
1969 (choice :tag "Identify target headline by"
1970 (cons :tag "Specific tag" (const :value :tag) (string))
1971 (cons :tag "TODO keyword" (const :value :todo) (string))
1972 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1973 (cons :tag "Level number" (const :value :level) (integer))
1974 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1976 (defcustom org-refile-target-verify-function nil
1977 "Function to verify if the headline at point should be a refile target.
1978 The function will be called without arguments, with point at the
1979 beginning of the headline. It should return t and leave point
1980 where it is if the headline is a valid target for refiling.
1982 If the target should not be selected, the function must return nil.
1983 In addition to this, it may move point to a place from where the search
1984 should be continued. For example, the function may decide that the entire
1985 subtree of the current entry should be excluded and move point to the end
1986 of the subtree."
1987 :group 'org-refile
1988 :type 'function)
1990 (defcustom org-refile-use-cache nil
1991 "Non-nil means cache refile targets to speed up the process.
1992 The cache for a particular file will be updated automatically when
1993 the buffer has been killed, or when any of the marker used for flagging
1994 refile targets no longer points at a live buffer.
1995 If you have added new entries to a buffer that might themselves be targets,
1996 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1997 find that easier, `C-u C-u C-u C-c C-w'."
1998 :group 'org-refile
1999 :version "24.1"
2000 :type 'boolean)
2002 (defcustom org-refile-use-outline-path nil
2003 "Non-nil means provide refile targets as paths.
2004 So a level 3 headline will be available as level1/level2/level3.
2006 When the value is `file', also include the file name (without directory)
2007 into the path. In this case, you can also stop the completion after
2008 the file name, to get entries inserted as top level in the file.
2010 When `full-file-path', include the full file path."
2011 :group 'org-refile
2012 :type '(choice
2013 (const :tag "Not" nil)
2014 (const :tag "Yes" t)
2015 (const :tag "Start with file name" file)
2016 (const :tag "Start with full file path" full-file-path)))
2018 (defcustom org-outline-path-complete-in-steps t
2019 "Non-nil means complete the outline path in hierarchical steps.
2020 When Org-mode uses the refile interface to select an outline path
2021 \(see variable `org-refile-use-outline-path'), the completion of
2022 the path can be done is a single go, or if can be done in steps down
2023 the headline hierarchy. Going in steps is probably the best if you
2024 do not use a special completion package like `ido' or `icicles'.
2025 However, when using these packages, going in one step can be very
2026 fast, while still showing the whole path to the entry."
2027 :group 'org-refile
2028 :type 'boolean)
2030 (defcustom org-refile-allow-creating-parent-nodes nil
2031 "Non-nil means allow to create new nodes as refile targets.
2032 New nodes are then created by adding \"/new node name\" to the completion
2033 of an existing node. When the value of this variable is `confirm',
2034 new node creation must be confirmed by the user (recommended)
2035 When nil, the completion must match an existing entry.
2037 Note that, if the new heading is not seen by the criteria
2038 listed in `org-refile-targets', multiple instances of the same
2039 heading would be created by trying again to file under the new
2040 heading."
2041 :group 'org-refile
2042 :type '(choice
2043 (const :tag "Never" nil)
2044 (const :tag "Always" t)
2045 (const :tag "Prompt for confirmation" confirm)))
2047 (defcustom org-refile-active-region-within-subtree nil
2048 "Non-nil means also refile active region within a subtree.
2050 By default `org-refile' doesn't allow refiling regions if they
2051 don't contain a set of subtrees, but it might be convenient to
2052 do so sometimes: in that case, the first line of the region is
2053 converted to a headline before refiling."
2054 :group 'org-refile
2055 :version "24.1"
2056 :type 'boolean)
2058 (defgroup org-todo nil
2059 "Options concerning TODO items in Org-mode."
2060 :tag "Org TODO"
2061 :group 'org)
2063 (defgroup org-progress nil
2064 "Options concerning Progress logging in Org-mode."
2065 :tag "Org Progress"
2066 :group 'org-time)
2068 (defvar org-todo-interpretation-widgets
2069 '((:tag "Sequence (cycling hits every state)" sequence)
2070 (:tag "Type (cycling directly to DONE)" type))
2071 "The available interpretation symbols for customizing `org-todo-keywords'.
2072 Interested libraries should add to this list.")
2074 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2075 "List of TODO entry keyword sequences and their interpretation.
2076 \\<org-mode-map>This is a list of sequences.
2078 Each sequence starts with a symbol, either `sequence' or `type',
2079 indicating if the keywords should be interpreted as a sequence of
2080 action steps, or as different types of TODO items. The first
2081 keywords are states requiring action - these states will select a headline
2082 for inclusion into the global TODO list Org-mode produces. If one of
2083 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2084 signify that no further action is necessary. If \"|\" is not found,
2085 the last keyword is treated as the only DONE state of the sequence.
2087 The command \\[org-todo] cycles an entry through these states, and one
2088 additional state where no keyword is present. For details about this
2089 cycling, see the manual.
2091 TODO keywords and interpretation can also be set on a per-file basis with
2092 the special #+SEQ_TODO and #+TYP_TODO lines.
2094 Each keyword can optionally specify a character for fast state selection
2095 \(in combination with the variable `org-use-fast-todo-selection')
2096 and specifiers for state change logging, using the same syntax
2097 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2098 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2099 indicates to record a time stamp each time this state is selected.
2101 Each keyword may also specify if a timestamp or a note should be
2102 recorded when entering or leaving the state, by adding additional
2103 characters in the parenthesis after the keyword. This looks like this:
2104 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2105 record only the time of the state change. With X and Y being either
2106 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2107 Y when leaving the state if and only if the *target* state does not
2108 define X. You may omit any of the fast-selection key or X or /Y,
2109 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2111 For backward compatibility, this variable may also be just a list
2112 of keywords - in this case the interpretation (sequence or type) will be
2113 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2114 :group 'org-todo
2115 :group 'org-keywords
2116 :type '(choice
2117 (repeat :tag "Old syntax, just keywords"
2118 (string :tag "Keyword"))
2119 (repeat :tag "New syntax"
2120 (cons
2121 (choice
2122 :tag "Interpretation"
2123 ;;Quick and dirty way to see
2124 ;;`org-todo-interpretations'. This takes the
2125 ;;place of item arguments
2126 :convert-widget
2127 (lambda (widget)
2128 (widget-put widget
2129 :args (mapcar
2130 #'(lambda (x)
2131 (widget-convert
2132 (cons 'const x)))
2133 org-todo-interpretation-widgets))
2134 widget))
2135 (repeat
2136 (string :tag "Keyword"))))))
2138 (defvar org-todo-keywords-1 nil
2139 "All TODO and DONE keywords active in a buffer.")
2140 (make-variable-buffer-local 'org-todo-keywords-1)
2141 (defvar org-todo-keywords-for-agenda nil)
2142 (defvar org-done-keywords-for-agenda nil)
2143 (defvar org-drawers-for-agenda nil)
2144 (defvar org-todo-keyword-alist-for-agenda nil)
2145 (defvar org-tag-alist-for-agenda nil)
2146 (defvar org-agenda-contributing-files nil)
2147 (defvar org-not-done-keywords nil)
2148 (make-variable-buffer-local 'org-not-done-keywords)
2149 (defvar org-done-keywords nil)
2150 (make-variable-buffer-local 'org-done-keywords)
2151 (defvar org-todo-heads nil)
2152 (make-variable-buffer-local 'org-todo-heads)
2153 (defvar org-todo-sets nil)
2154 (make-variable-buffer-local 'org-todo-sets)
2155 (defvar org-todo-log-states nil)
2156 (make-variable-buffer-local 'org-todo-log-states)
2157 (defvar org-todo-kwd-alist nil)
2158 (make-variable-buffer-local 'org-todo-kwd-alist)
2159 (defvar org-todo-key-alist nil)
2160 (make-variable-buffer-local 'org-todo-key-alist)
2161 (defvar org-todo-key-trigger nil)
2162 (make-variable-buffer-local 'org-todo-key-trigger)
2164 (defcustom org-todo-interpretation 'sequence
2165 "Controls how TODO keywords are interpreted.
2166 This variable is in principle obsolete and is only used for
2167 backward compatibility, if the interpretation of todo keywords is
2168 not given already in `org-todo-keywords'. See that variable for
2169 more information."
2170 :group 'org-todo
2171 :group 'org-keywords
2172 :type '(choice (const sequence)
2173 (const type)))
2175 (defcustom org-use-fast-todo-selection t
2176 "Non-nil means use the fast todo selection scheme with C-c C-t.
2177 This variable describes if and under what circumstances the cycling
2178 mechanism for TODO keywords will be replaced by a single-key, direct
2179 selection scheme.
2181 When nil, fast selection is never used.
2183 When the symbol `prefix', it will be used when `org-todo' is called with
2184 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2185 in an agenda buffer.
2187 When t, fast selection is used by default. In this case, the prefix
2188 argument forces cycling instead.
2190 In all cases, the special interface is only used if access keys have actually
2191 been assigned by the user, i.e. if keywords in the configuration are followed
2192 by a letter in parenthesis, like TODO(t)."
2193 :group 'org-todo
2194 :type '(choice
2195 (const :tag "Never" nil)
2196 (const :tag "By default" t)
2197 (const :tag "Only with C-u C-c C-t" prefix)))
2199 (defcustom org-provide-todo-statistics t
2200 "Non-nil means update todo statistics after insert and toggle.
2201 ALL-HEADLINES means update todo statistics by including headlines
2202 with no TODO keyword as well, counting them as not done.
2203 A list of TODO keywords means the same, but skip keywords that are
2204 not in this list.
2206 When this is set, todo statistics is updated in the parent of the
2207 current entry each time a todo state is changed."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Yes, only for TODO entries" t)
2211 (const :tag "Yes, including all entries" 'all-headlines)
2212 (repeat :tag "Yes, for TODOs in this list"
2213 (string :tag "TODO keyword"))
2214 (other :tag "No TODO statistics" nil)))
2216 (defcustom org-hierarchical-todo-statistics t
2217 "Non-nil means TODO statistics covers just direct children.
2218 When nil, all entries in the subtree are considered.
2219 This has only an effect if `org-provide-todo-statistics' is set.
2220 To set this to nil for only a single subtree, use a COOKIE_DATA
2221 property and include the word \"recursive\" into the value."
2222 :group 'org-todo
2223 :type 'boolean)
2225 (defcustom org-after-todo-state-change-hook nil
2226 "Hook which is run after the state of a TODO item was changed.
2227 The new state (a string with a TODO keyword, or nil) is available in the
2228 Lisp variable `org-state'."
2229 :group 'org-todo
2230 :type 'hook)
2232 (defvar org-blocker-hook nil
2233 "Hook for functions that are allowed to block a state change.
2235 Each function gets as its single argument a property list, see
2236 `org-trigger-hook' for more information about this list.
2238 If any of the functions in this hook returns nil, the state change
2239 is blocked.")
2241 (defvar org-trigger-hook nil
2242 "Hook for functions that are triggered by a state change.
2244 Each function gets as its single argument a property list with at least
2245 the following elements:
2247 (:type type-of-change :position pos-at-entry-start
2248 :from old-state :to new-state)
2250 Depending on the type, more properties may be present.
2252 This mechanism is currently implemented for:
2254 TODO state changes
2255 ------------------
2256 :type todo-state-change
2257 :from previous state (keyword as a string), or nil, or a symbol
2258 'todo' or 'done', to indicate the general type of state.
2259 :to new state, like in :from")
2261 (defcustom org-enforce-todo-dependencies nil
2262 "Non-nil means undone TODO entries will block switching the parent to DONE.
2263 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2264 be blocked if any prior sibling is not yet done.
2265 Finally, if the parent is blocked because of ordered siblings of its own,
2266 the child will also be blocked."
2267 :set (lambda (var val)
2268 (set var val)
2269 (if val
2270 (add-hook 'org-blocker-hook
2271 'org-block-todo-from-children-or-siblings-or-parent)
2272 (remove-hook 'org-blocker-hook
2273 'org-block-todo-from-children-or-siblings-or-parent)))
2274 :group 'org-todo
2275 :type 'boolean)
2277 (defcustom org-enforce-todo-checkbox-dependencies nil
2278 "Non-nil means unchecked boxes will block switching the parent to DONE.
2279 When this is nil, checkboxes have no influence on switching TODO states.
2280 When non-nil, you first need to check off all check boxes before the TODO
2281 entry can be switched to DONE.
2282 This variable needs to be set before org.el is loaded, and you need to
2283 restart Emacs after a change to make the change effective. The only way
2284 to change is while Emacs is running is through the customize interface."
2285 :set (lambda (var val)
2286 (set var val)
2287 (if val
2288 (add-hook 'org-blocker-hook
2289 'org-block-todo-from-checkboxes)
2290 (remove-hook 'org-blocker-hook
2291 'org-block-todo-from-checkboxes)))
2292 :group 'org-todo
2293 :type 'boolean)
2295 (defcustom org-treat-insert-todo-heading-as-state-change nil
2296 "Non-nil means inserting a TODO heading is treated as state change.
2297 So when the command \\[org-insert-todo-heading] is used, state change
2298 logging will apply if appropriate. When nil, the new TODO item will
2299 be inserted directly, and no logging will take place."
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2304 "Non-nil means switching TODO states with S-cursor counts as state change.
2305 This is the default behavior. However, setting this to nil allows a
2306 convenient way to select a TODO state and bypass any logging associated
2307 with that."
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-todo-state-tags-triggers nil
2312 "Tag changes that should be triggered by TODO state changes.
2313 This is a list. Each entry is
2315 (state-change (tag . flag) .......)
2317 State-change can be a string with a state, and empty string to indicate the
2318 state that has no TODO keyword, or it can be one of the symbols `todo'
2319 or `done', meaning any not-done or done state, respectively."
2320 :group 'org-todo
2321 :group 'org-tags
2322 :type '(repeat
2323 (cons (choice :tag "When changing to"
2324 (const :tag "Not-done state" todo)
2325 (const :tag "Done state" done)
2326 (string :tag "State"))
2327 (repeat
2328 (cons :tag "Tag action"
2329 (string :tag "Tag")
2330 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2332 (defcustom org-log-done nil
2333 "Information to record when a task moves to the DONE state.
2335 Possible values are:
2337 nil Don't add anything, just change the keyword
2338 time Add a time stamp to the task
2339 note Prompt for a note and add it with template `org-log-note-headings'
2341 This option can also be set with on a per-file-basis with
2343 #+STARTUP: nologdone
2344 #+STARTUP: logdone
2345 #+STARTUP: lognotedone
2347 You can have local logging settings for a subtree by setting the LOGGING
2348 property to one or more of these keywords."
2349 :group 'org-todo
2350 :group 'org-progress
2351 :type '(choice
2352 (const :tag "No logging" nil)
2353 (const :tag "Record CLOSED timestamp" time)
2354 (const :tag "Record CLOSED timestamp with note." note)))
2356 ;; Normalize old uses of org-log-done.
2357 (cond
2358 ((eq org-log-done t) (setq org-log-done 'time))
2359 ((and (listp org-log-done) (memq 'done org-log-done))
2360 (setq org-log-done 'note)))
2362 (defcustom org-log-reschedule nil
2363 "Information to record when the scheduling date of a tasks is modified.
2365 Possible values are:
2367 nil Don't add anything, just change the date
2368 time Add a time stamp to the task
2369 note Prompt for a note and add it with template `org-log-note-headings'
2371 This option can also be set with on a per-file-basis with
2373 #+STARTUP: nologreschedule
2374 #+STARTUP: logreschedule
2375 #+STARTUP: lognotereschedule"
2376 :group 'org-todo
2377 :group 'org-progress
2378 :type '(choice
2379 (const :tag "No logging" nil)
2380 (const :tag "Record timestamp" time)
2381 (const :tag "Record timestamp with note." note)))
2383 (defcustom org-log-redeadline nil
2384 "Information to record when the deadline date of a tasks is modified.
2386 Possible values are:
2388 nil Don't add anything, just change the date
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2392 This option can also be set with on a per-file-basis with
2394 #+STARTUP: nologredeadline
2395 #+STARTUP: logredeadline
2396 #+STARTUP: lognoteredeadline
2398 You can have local logging settings for a subtree by setting the LOGGING
2399 property to one or more of these keywords."
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2407 (defcustom org-log-note-clock-out nil
2408 "Non-nil means record a note when clocking out of an item.
2409 This can also be configured on a per-file basis by adding one of
2410 the following lines anywhere in the buffer:
2412 #+STARTUP: lognoteclock-out
2413 #+STARTUP: nolognoteclock-out"
2414 :group 'org-todo
2415 :group 'org-progress
2416 :type 'boolean)
2418 (defcustom org-log-done-with-time t
2419 "Non-nil means the CLOSED time stamp will contain date and time.
2420 When nil, only the date will be recorded."
2421 :group 'org-progress
2422 :type 'boolean)
2424 (defcustom org-log-note-headings
2425 '((done . "CLOSING NOTE %t")
2426 (state . "State %-12s from %-12S %t")
2427 (note . "Note taken on %t")
2428 (reschedule . "Rescheduled from %S on %t")
2429 (delschedule . "Not scheduled, was %S on %t")
2430 (redeadline . "New deadline from %S on %t")
2431 (deldeadline . "Removed deadline, was %S on %t")
2432 (refile . "Refiled on %t")
2433 (clock-out . ""))
2434 "Headings for notes added to entries.
2435 The value is an alist, with the car being a symbol indicating the note
2436 context, and the cdr is the heading to be used. The heading may also be the
2437 empty string.
2438 %t in the heading will be replaced by a time stamp.
2439 %T will be an active time stamp instead the default inactive one
2440 %d will be replaced by a short-format time stamp.
2441 %D will be replaced by an active short-format time stamp.
2442 %s will be replaced by the new TODO state, in double quotes.
2443 %S will be replaced by the old TODO state, in double quotes.
2444 %u will be replaced by the user name.
2445 %U will be replaced by the full user name.
2447 In fact, it is not a good idea to change the `state' entry, because
2448 agenda log mode depends on the format of these entries."
2449 :group 'org-todo
2450 :group 'org-progress
2451 :type '(list :greedy t
2452 (cons (const :tag "Heading when closing an item" done) string)
2453 (cons (const :tag
2454 "Heading when changing todo state (todo sequence only)"
2455 state) string)
2456 (cons (const :tag "Heading when just taking a note" note) string)
2457 (cons (const :tag "Heading when clocking out" clock-out) string)
2458 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2459 (cons (const :tag "Heading when rescheduling" reschedule) string)
2460 (cons (const :tag "Heading when changing deadline" redeadline) string)
2461 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2462 (cons (const :tag "Heading when refiling" refile) string)))
2464 (unless (assq 'note org-log-note-headings)
2465 (push '(note . "%t") org-log-note-headings))
2467 (defcustom org-log-into-drawer nil
2468 "Non-nil means insert state change notes and time stamps into a drawer.
2469 When nil, state changes notes will be inserted after the headline and
2470 any scheduling and clock lines, but not inside a drawer.
2472 The value of this variable should be the name of the drawer to use.
2473 LOGBOOK is proposed as the default drawer for this purpose, you can
2474 also set this to a string to define the drawer of your choice.
2476 A value of t is also allowed, representing \"LOGBOOK\".
2478 If this variable is set, `org-log-state-notes-insert-after-drawers'
2479 will be ignored.
2481 You can set the property LOG_INTO_DRAWER to overrule this setting for
2482 a subtree."
2483 :group 'org-todo
2484 :group 'org-progress
2485 :type '(choice
2486 (const :tag "Not into a drawer" nil)
2487 (const :tag "LOGBOOK" t)
2488 (string :tag "Other")))
2490 (if (fboundp 'defvaralias)
2491 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2493 (defun org-log-into-drawer ()
2494 "Return the value of `org-log-into-drawer', but let properties overrule.
2495 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2496 used instead of the default value."
2497 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2498 (cond
2499 ((or (not p) (equal p "nil")) org-log-into-drawer)
2500 ((equal p "t") "LOGBOOK")
2501 (t p))))
2503 (defcustom org-log-state-notes-insert-after-drawers nil
2504 "Non-nil means insert state change notes after any drawers in entry.
2505 Only the drawers that *immediately* follow the headline and the
2506 deadline/scheduled line are skipped.
2507 When nil, insert notes right after the heading and perhaps the line
2508 with deadline/scheduling if present.
2510 This variable will have no effect if `org-log-into-drawer' is
2511 set."
2512 :group 'org-todo
2513 :group 'org-progress
2514 :type 'boolean)
2516 (defcustom org-log-states-order-reversed t
2517 "Non-nil means the latest state note will be directly after heading.
2518 When nil, the state change notes will be ordered according to time."
2519 :group 'org-todo
2520 :group 'org-progress
2521 :type 'boolean)
2523 (defcustom org-todo-repeat-to-state nil
2524 "The TODO state to which a repeater should return the repeating task.
2525 By default this is the first task in a TODO sequence, or the previous state
2526 in a TODO_TYP set. But you can specify another task here.
2527 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2528 :group 'org-todo
2529 :version "24.1"
2530 :type '(choice (const :tag "Head of sequence" nil)
2531 (string :tag "Specific state")))
2533 (defcustom org-log-repeat 'time
2534 "Non-nil means record moving through the DONE state when triggering repeat.
2535 An auto-repeating task is immediately switched back to TODO when
2536 marked DONE. If you are not logging state changes (by adding \"@\"
2537 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2538 record a closing note, there will be no record of the task moving
2539 through DONE. This variable forces taking a note anyway.
2541 nil Don't force a record
2542 time Record a time stamp
2543 note Record a note
2545 This option can also be set with on a per-file-basis with
2547 #+STARTUP: logrepeat
2548 #+STARTUP: lognoterepeat
2549 #+STARTUP: nologrepeat
2551 You can have local logging settings for a subtree by setting the LOGGING
2552 property to one or more of these keywords."
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type '(choice
2556 (const :tag "Don't force a record" nil)
2557 (const :tag "Force recording the DONE state" time)
2558 (const :tag "Force recording a note with the DONE state" note)))
2561 (defgroup org-priorities nil
2562 "Priorities in Org-mode."
2563 :tag "Org Priorities"
2564 :group 'org-todo)
2566 (defcustom org-enable-priority-commands t
2567 "Non-nil means priority commands are active.
2568 When nil, these commands will be disabled, so that you never accidentally
2569 set a priority."
2570 :group 'org-priorities
2571 :type 'boolean)
2573 (defcustom org-highest-priority ?A
2574 "The highest priority of TODO items. A character like ?A, ?B etc.
2575 Must have a smaller ASCII number than `org-lowest-priority'."
2576 :group 'org-priorities
2577 :type 'character)
2579 (defcustom org-lowest-priority ?C
2580 "The lowest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a larger ASCII number than `org-highest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-default-priority ?B
2586 "The default priority of TODO items.
2587 This is the priority an item gets if no explicit priority is given.
2588 When starting to cycle on an empty priority the first step in the cycle
2589 depends on `org-priority-start-cycle-with-default'. The resulting first
2590 step priority must not exceed the range from `org-highest-priority' to
2591 `org-lowest-priority' which means that `org-default-priority' has to be
2592 in this range exclusive or inclusive the range boundaries. Else the
2593 first step refuses to set the default and the second will fall back
2594 to (depending on the command used) the highest or lowest priority."
2595 :group 'org-priorities
2596 :type 'character)
2598 (defcustom org-priority-start-cycle-with-default t
2599 "Non-nil means start with default priority when starting to cycle.
2600 When this is nil, the first step in the cycle will be (depending on the
2601 command used) one higher or lower than the default priority.
2602 See also `org-default-priority'."
2603 :group 'org-priorities
2604 :type 'boolean)
2606 (defcustom org-get-priority-function nil
2607 "Function to extract the priority from a string.
2608 The string is normally the headline. If this is nil Org computes the
2609 priority from the priority cookie like [#A] in the headline. It returns
2610 an integer, increasing by 1000 for each priority level.
2611 The user can set a different function here, which should take a string
2612 as an argument and return the numeric priority."
2613 :group 'org-priorities
2614 :version "24.1"
2615 :type 'function)
2617 (defgroup org-time nil
2618 "Options concerning time stamps and deadlines in Org-mode."
2619 :tag "Org Time"
2620 :group 'org)
2622 (defcustom org-insert-labeled-timestamps-at-point nil
2623 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2624 When nil, these labeled time stamps are forces into the second line of an
2625 entry, just after the headline. When scheduling from the global TODO list,
2626 the time stamp will always be forced into the second line."
2627 :group 'org-time
2628 :type 'boolean)
2630 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2631 "Formats for `format-time-string' which are used for time stamps.
2632 It is not recommended to change this constant.")
2634 (defcustom org-time-stamp-rounding-minutes '(0 5)
2635 "Number of minutes to round time stamps to.
2636 These are two values, the first applies when first creating a time stamp.
2637 The second applies when changing it with the commands `S-up' and `S-down'.
2638 When changing the time stamp, this means that it will change in steps
2639 of N minutes, as given by the second value.
2641 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2642 numbers should be factors of 60, so for example 5, 10, 15.
2644 When this is larger than 1, you can still force an exact time stamp by using
2645 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2646 and by using a prefix arg to `S-up/down' to specify the exact number
2647 of minutes to shift."
2648 :group 'org-time
2649 :get #'(lambda (var) ; Make sure both elements are there
2650 (if (integerp (default-value var))
2651 (list (default-value var) 5)
2652 (default-value var)))
2653 :type '(list
2654 (integer :tag "when inserting times")
2655 (integer :tag "when modifying times")))
2657 ;; Normalize old customizations of this variable.
2658 (when (integerp org-time-stamp-rounding-minutes)
2659 (setq org-time-stamp-rounding-minutes
2660 (list org-time-stamp-rounding-minutes
2661 org-time-stamp-rounding-minutes)))
2663 (defcustom org-display-custom-times nil
2664 "Non-nil means overlay custom formats over all time stamps.
2665 The formats are defined through the variable `org-time-stamp-custom-formats'.
2666 To turn this on on a per-file basis, insert anywhere in the file:
2667 #+STARTUP: customtime"
2668 :group 'org-time
2669 :set 'set-default
2670 :type 'sexp)
2671 (make-variable-buffer-local 'org-display-custom-times)
2673 (defcustom org-time-stamp-custom-formats
2674 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2675 "Custom formats for time stamps. See `format-time-string' for the syntax.
2676 These are overlaid over the default ISO format if the variable
2677 `org-display-custom-times' is set. Time like %H:%M should be at the
2678 end of the second format. The custom formats are also honored by export
2679 commands, if custom time display is turned on at the time of export."
2680 :group 'org-time
2681 :type 'sexp)
2683 (defun org-time-stamp-format (&optional long inactive)
2684 "Get the right format for a time string."
2685 (let ((f (if long (cdr org-time-stamp-formats)
2686 (car org-time-stamp-formats))))
2687 (if inactive
2688 (concat "[" (substring f 1 -1) "]")
2689 f)))
2691 (defcustom org-time-clocksum-format "%d:%02d"
2692 "The format string used when creating CLOCKSUM lines.
2693 This is also used when org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2697 (defcustom org-time-clocksum-use-fractional nil
2698 "If non-nil, \\[org-clock-display] uses fractional times.
2699 org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'boolean)
2703 (defcustom org-time-clocksum-fractional-format "%.2f"
2704 "The format string used when creating CLOCKSUM lines, or when
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'string)
2709 (defcustom org-deadline-warning-days 14
2710 "No. of days before expiration during which a deadline becomes active.
2711 This variable governs the display in sparse trees and in the agenda.
2712 When 0 or negative, it means use this number (the absolute value of it)
2713 even if a deadline has a different individual lead time specified.
2715 Custom commands can set this variable in the options section."
2716 :group 'org-time
2717 :group 'org-agenda-daily/weekly
2718 :type 'integer)
2720 (defcustom org-read-date-prefer-future t
2721 "Non-nil means assume future for incomplete date input from user.
2722 This affects the following situations:
2723 1. The user gives a month but not a year.
2724 For example, if it is April and you enter \"feb 2\", this will be read
2725 as Feb 2, *next* year. \"May 5\", however, will be this year.
2726 2. The user gives a day, but no month.
2727 For example, if today is the 15th, and you enter \"3\", Org-mode will
2728 read this as the third of *next* month. However, if you enter \"17\",
2729 it will be considered as *this* month.
2731 If you set this variable to the symbol `time', then also the following
2732 will work:
2734 3. If the user gives a time, but no day. If the time is before now,
2735 to will be interpreted as tomorrow.
2737 Currently none of this works for ISO week specifications.
2739 When this option is nil, the current day, month and year will always be
2740 used as defaults.
2742 See also `org-agenda-jump-prefer-future'."
2743 :group 'org-time
2744 :type '(choice
2745 (const :tag "Never" nil)
2746 (const :tag "Check month and day" t)
2747 (const :tag "Check month, day, and time" time)))
2749 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2750 "Should the agenda jump command prefer the future for incomplete dates?
2751 The default is to do the same as configured in `org-read-date-prefer-future'.
2752 But you can also set a deviating value here.
2753 This may t or nil, or the symbol `org-read-date-prefer-future'."
2754 :group 'org-agenda
2755 :group 'org-time
2756 :version "24.1"
2757 :type '(choice
2758 (const :tag "Use org-read-date-prefer-future"
2759 org-read-date-prefer-future)
2760 (const :tag "Never" nil)
2761 (const :tag "Always" t)))
2763 (defcustom org-read-date-force-compatible-dates t
2764 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2766 Depending on the system Emacs is running on, certain dates cannot
2767 be represented with the type used internally to represent time.
2768 Dates between 1970-1-1 and 2038-1-1 can always be represented
2769 correctly. Some systems allow for earlier dates, some for later,
2770 some for both. One way to find out it to insert any date into an
2771 Org buffer, putting the cursor on the year and hitting S-up and
2772 S-down to test the range.
2774 When this variable is set to t, the date/time prompt will not let
2775 you specify dates outside the 1970-2037 range, so it is certain that
2776 these dates will work in whatever version of Emacs you are
2777 running, and also that you can move a file from one Emacs implementation
2778 to another. WHenever Org is forcing the year for you, it will display
2779 a message and beep.
2781 When this variable is nil, Org will check if the date is
2782 representable in the specific Emacs implementation you are using.
2783 If not, it will force a year, usually the current year, and beep
2784 to remind you. Currently this setting is not recommended because
2785 the likelihood that you will open your Org files in an Emacs that
2786 has limited date range is not negligible.
2788 A workaround for this problem is to use diary sexp dates for time
2789 stamps outside of this range."
2790 :group 'org-time
2791 :version "24.1"
2792 :type 'boolean)
2794 (defcustom org-read-date-display-live t
2795 "Non-nil means display current interpretation of date prompt live.
2796 This display will be in an overlay, in the minibuffer."
2797 :group 'org-time
2798 :type 'boolean)
2800 (defcustom org-read-date-popup-calendar t
2801 "Non-nil means pop up a calendar when prompting for a date.
2802 In the calendar, the date can be selected with mouse-1. However, the
2803 minibuffer will also be active, and you can simply enter the date as well.
2804 When nil, only the minibuffer will be available."
2805 :group 'org-time
2806 :type 'boolean)
2807 (if (fboundp 'defvaralias)
2808 (defvaralias 'org-popup-calendar-for-date-prompt
2809 'org-read-date-popup-calendar))
2811 (defcustom org-read-date-minibuffer-setup-hook nil
2812 "Hook to be used to set up keys for the date/time interface.
2813 Add key definitions to `minibuffer-local-map', which will be a temporary
2814 copy."
2815 :group 'org-time
2816 :type 'hook)
2818 (defcustom org-extend-today-until 0
2819 "The hour when your day really ends. Must be an integer.
2820 This has influence for the following applications:
2821 - When switching the agenda to \"today\". It it is still earlier than
2822 the time given here, the day recognized as TODAY is actually yesterday.
2823 - When a date is read from the user and it is still before the time given
2824 here, the current date and time will be assumed to be yesterday, 23:59.
2825 Also, timestamps inserted in remember templates follow this rule.
2827 IMPORTANT: This is a feature whose implementation is and likely will
2828 remain incomplete. Really, it is only here because past midnight seems to
2829 be the favorite working time of John Wiegley :-)"
2830 :group 'org-time
2831 :type 'integer)
2833 (defcustom org-use-effective-time nil
2834 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2835 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2836 \"effective time\" of any timestamps between midnight and 8am will be
2837 23:59 of the previous day."
2838 :group 'org-time
2839 :version "24.1"
2840 :type 'boolean)
2842 (defcustom org-edit-timestamp-down-means-later nil
2843 "Non-nil means S-down will increase the time in a time stamp.
2844 When nil, S-up will increase."
2845 :group 'org-time
2846 :type 'boolean)
2848 (defcustom org-calendar-follow-timestamp-change t
2849 "Non-nil means make the calendar window follow timestamp changes.
2850 When a timestamp is modified and the calendar window is visible, it will be
2851 moved to the new date."
2852 :group 'org-time
2853 :type 'boolean)
2855 (defgroup org-tags nil
2856 "Options concerning tags in Org-mode."
2857 :tag "Org Tags"
2858 :group 'org)
2860 (defcustom org-tag-alist nil
2861 "List of tags allowed in Org-mode files.
2862 When this list is nil, Org-mode will base TAG input on what is already in the
2863 buffer.
2864 The value of this variable is an alist, the car of each entry must be a
2865 keyword as a string, the cdr may be a character that is used to select
2866 that tag through the fast-tag-selection interface.
2867 See the manual for details."
2868 :group 'org-tags
2869 :type '(repeat
2870 (choice
2871 (cons (string :tag "Tag name")
2872 (character :tag "Access char"))
2873 (list :tag "Start radio group"
2874 (const :startgroup)
2875 (option (string :tag "Group description")))
2876 (list :tag "End radio group"
2877 (const :endgroup)
2878 (option (string :tag "Group description")))
2879 (const :tag "New line" (:newline)))))
2881 (defcustom org-tag-persistent-alist nil
2882 "List of tags that will always appear in all Org-mode files.
2883 This is in addition to any in buffer settings or customizations
2884 of `org-tag-alist'.
2885 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2886 The value of this variable is an alist, the car of each entry must be a
2887 keyword as a string, the cdr may be a character that is used to select
2888 that tag through the fast-tag-selection interface.
2889 See the manual for details.
2890 To disable these tags on a per-file basis, insert anywhere in the file:
2891 #+STARTUP: noptag"
2892 :group 'org-tags
2893 :type '(repeat
2894 (choice
2895 (cons (string :tag "Tag name")
2896 (character :tag "Access char"))
2897 (const :tag "Start radio group" (:startgroup))
2898 (const :tag "End radio group" (:endgroup))
2899 (const :tag "New line" (:newline)))))
2901 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2902 "If non-nil, always offer completion for all tags of all agenda files.
2903 Instead of customizing this variable directly, you might want to
2904 set it locally for capture buffers, because there no list of
2905 tags in that file can be created dynamically (there are none).
2907 (add-hook 'org-capture-mode-hook
2908 (lambda ()
2909 (set (make-local-variable
2910 'org-complete-tags-always-offer-all-agenda-tags)
2911 t)))"
2912 :group 'org-tags
2913 :version "24.1"
2914 :type 'boolean)
2916 (defvar org-file-tags nil
2917 "List of tags that can be inherited by all entries in the file.
2918 The tags will be inherited if the variable `org-use-tag-inheritance'
2919 says they should be.
2920 This variable is populated from #+FILETAGS lines.")
2922 (defcustom org-use-fast-tag-selection 'auto
2923 "Non-nil means use fast tag selection scheme.
2924 This is a special interface to select and deselect tags with single keys.
2925 When nil, fast selection is never used.
2926 When the symbol `auto', fast selection is used if and only if selection
2927 characters for tags have been configured, either through the variable
2928 `org-tag-alist' or through a #+TAGS line in the buffer.
2929 When t, fast selection is always used and selection keys are assigned
2930 automatically if necessary."
2931 :group 'org-tags
2932 :type '(choice
2933 (const :tag "Always" t)
2934 (const :tag "Never" nil)
2935 (const :tag "When selection characters are configured" 'auto)))
2937 (defcustom org-fast-tag-selection-single-key nil
2938 "Non-nil means fast tag selection exits after first change.
2939 When nil, you have to press RET to exit it.
2940 During fast tag selection, you can toggle this flag with `C-c'.
2941 This variable can also have the value `expert'. In this case, the window
2942 displaying the tags menu is not even shown, until you press C-c again."
2943 :group 'org-tags
2944 :type '(choice
2945 (const :tag "No" nil)
2946 (const :tag "Yes" t)
2947 (const :tag "Expert" expert)))
2949 (defvar org-fast-tag-selection-include-todo nil
2950 "Non-nil means fast tags selection interface will also offer TODO states.
2951 This is an undocumented feature, you should not rely on it.")
2953 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2954 "The column to which tags should be indented in a headline.
2955 If this number is positive, it specifies the column. If it is negative,
2956 it means that the tags should be flushright to that column. For example,
2957 -80 works well for a normal 80 character screen.
2958 When 0, place tags directly after headline text, with only one space in
2959 between."
2960 :group 'org-tags
2961 :type 'integer)
2963 (defcustom org-auto-align-tags t
2964 "Non-nil keeps tags aligned when modifying headlines.
2965 Some operations (i.e. demoting) change the length of a headline and
2966 therefore shift the tags around. With this option turned on, after
2967 each such operation the tags are again aligned to `org-tags-column'."
2968 :group 'org-tags
2969 :type 'boolean)
2971 (defcustom org-use-tag-inheritance t
2972 "Non-nil means tags in levels apply also for sublevels.
2973 When nil, only the tags directly given in a specific line apply there.
2974 This may also be a list of tags that should be inherited, or a regexp that
2975 matches tags that should be inherited. Additional control is possible
2976 with the variable `org-tags-exclude-from-inheritance' which gives an
2977 explicit list of tags to be excluded from inheritance., even if the value of
2978 `org-use-tag-inheritance' would select it for inheritance.
2980 If this option is t, a match early-on in a tree can lead to a large
2981 number of matches in the subtree when constructing the agenda or creating
2982 a sparse tree. If you only want to see the first match in a tree during
2983 a search, check out the variable `org-tags-match-list-sublevels'."
2984 :group 'org-tags
2985 :type '(choice
2986 (const :tag "Not" nil)
2987 (const :tag "Always" t)
2988 (repeat :tag "Specific tags" (string :tag "Tag"))
2989 (regexp :tag "Tags matched by regexp")))
2991 (defcustom org-tags-exclude-from-inheritance nil
2992 "List of tags that should never be inherited.
2993 This is a way to exclude a few tags from inheritance. For way to do
2994 the opposite, to actively allow inheritance for selected tags,
2995 see the variable `org-use-tag-inheritance'."
2996 :group 'org-tags
2997 :type '(repeat (string :tag "Tag")))
2999 (defun org-tag-inherit-p (tag)
3000 "Check if TAG is one that should be inherited."
3001 (cond
3002 ((member tag org-tags-exclude-from-inheritance) nil)
3003 ((eq org-use-tag-inheritance t) t)
3004 ((not org-use-tag-inheritance) nil)
3005 ((stringp org-use-tag-inheritance)
3006 (string-match org-use-tag-inheritance tag))
3007 ((listp org-use-tag-inheritance)
3008 (member tag org-use-tag-inheritance))
3009 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3011 (defcustom org-tags-match-list-sublevels t
3012 "Non-nil means list also sublevels of headlines matching a search.
3013 This variable applies to tags/property searches, and also to stuck
3014 projects because this search is based on a tags match as well.
3016 When set to the symbol `indented', sublevels are indented with
3017 leading dots.
3019 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3020 the sublevels of a headline matching a tag search often also match
3021 the same search. Listing all of them can create very long lists.
3022 Setting this variable to nil causes subtrees of a match to be skipped.
3024 This variable is semi-obsolete and probably should always be true. It
3025 is better to limit inheritance to certain tags using the variables
3026 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3027 :group 'org-tags
3028 :type '(choice
3029 (const :tag "No, don't list them" nil)
3030 (const :tag "Yes, do list them" t)
3031 (const :tag "List them, indented with leading dots" indented)))
3033 (defcustom org-tags-sort-function nil
3034 "When set, tags are sorted using this function as a comparator."
3035 :group 'org-tags
3036 :type '(choice
3037 (const :tag "No sorting" nil)
3038 (const :tag "Alphabetical" string<)
3039 (const :tag "Reverse alphabetical" string>)
3040 (function :tag "Custom function" nil)))
3042 (defvar org-tags-history nil
3043 "History of minibuffer reads for tags.")
3044 (defvar org-last-tags-completion-table nil
3045 "The last used completion table for tags.")
3046 (defvar org-after-tags-change-hook nil
3047 "Hook that is run after the tags in a line have changed.")
3049 (defgroup org-properties nil
3050 "Options concerning properties in Org-mode."
3051 :tag "Org Properties"
3052 :group 'org)
3054 (defcustom org-property-format "%-10s %s"
3055 "How property key/value pairs should be formatted by `indent-line'.
3056 When `indent-line' hits a property definition, it will format the line
3057 according to this format, mainly to make sure that the values are
3058 lined-up with respect to each other."
3059 :group 'org-properties
3060 :type 'string)
3062 (defcustom org-properties-postprocess-alist nil
3063 "Alist of properties and functions to adjust inserted values.
3064 Elements of this alist must be of the form
3066 ([string] [function])
3068 where [string] must be a property name and [function] must be a
3069 lambda expression: this lambda expression must take one argument,
3070 the value to adjust, and return the new value as a string.
3072 For example, this element will allow the property \"Remaining\"
3073 to be updated wrt the relation between the \"Effort\" property
3074 and the clock summary:
3076 ((\"Remaining\" (lambda(value)
3077 (let ((clocksum (org-clock-sum-current-item))
3078 (effort (org-duration-string-to-minutes
3079 (org-entry-get (point) \"Effort\"))))
3080 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3081 :group 'org-properties
3082 :version "24.1"
3083 :type 'alist)
3085 (defcustom org-use-property-inheritance nil
3086 "Non-nil means properties apply also for sublevels.
3088 This setting is chiefly used during property searches. Turning it on can
3089 cause significant overhead when doing a search, which is why it is not
3090 on by default.
3092 When nil, only the properties directly given in the current entry count.
3093 When t, every property is inherited. The value may also be a list of
3094 properties that should have inheritance, or a regular expression matching
3095 properties that should be inherited.
3097 However, note that some special properties use inheritance under special
3098 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3099 and the properties ending in \"_ALL\" when they are used as descriptor
3100 for valid values of a property.
3102 Note for programmers:
3103 When querying an entry with `org-entry-get', you can control if inheritance
3104 should be used. By default, `org-entry-get' looks only at the local
3105 properties. You can request inheritance by setting the inherit argument
3106 to t (to force inheritance) or to `selective' (to respect the setting
3107 in this variable)."
3108 :group 'org-properties
3109 :type '(choice
3110 (const :tag "Not" nil)
3111 (const :tag "Always" t)
3112 (repeat :tag "Specific properties" (string :tag "Property"))
3113 (regexp :tag "Properties matched by regexp")))
3115 (defun org-property-inherit-p (property)
3116 "Check if PROPERTY is one that should be inherited."
3117 (cond
3118 ((eq org-use-property-inheritance t) t)
3119 ((not org-use-property-inheritance) nil)
3120 ((stringp org-use-property-inheritance)
3121 (string-match org-use-property-inheritance property))
3122 ((listp org-use-property-inheritance)
3123 (member property org-use-property-inheritance))
3124 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3126 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3127 "The default column format, if no other format has been defined.
3128 This variable can be set on the per-file basis by inserting a line
3130 #+COLUMNS: %25ITEM ....."
3131 :group 'org-properties
3132 :type 'string)
3134 (defcustom org-columns-ellipses ".."
3135 "The ellipses to be used when a field in column view is truncated.
3136 When this is the empty string, as many characters as possible are shown,
3137 but then there will be no visual indication that the field has been truncated.
3138 When this is a string of length N, the last N characters of a truncated
3139 field are replaced by this string. If the column is narrower than the
3140 ellipses string, only part of the ellipses string will be shown."
3141 :group 'org-properties
3142 :type 'string)
3144 (defcustom org-columns-modify-value-for-display-function nil
3145 "Function that modifies values for display in column view.
3146 For example, it can be used to cut out a certain part from a time stamp.
3147 The function must take 2 arguments:
3149 column-title The title of the column (*not* the property name)
3150 value The value that should be modified.
3152 The function should return the value that should be displayed,
3153 or nil if the normal value should be used."
3154 :group 'org-properties
3155 :type 'function)
3157 (defcustom org-effort-property "Effort"
3158 "The property that is being used to keep track of effort estimates.
3159 Effort estimates given in this property need to have the format H:MM."
3160 :group 'org-properties
3161 :group 'org-progress
3162 :type '(string :tag "Property"))
3164 (defconst org-global-properties-fixed
3165 '(("VISIBILITY_ALL" . "folded children content all")
3166 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3167 "List of property/value pairs that can be inherited by any entry.
3169 These are fixed values, for the preset properties. The user variable
3170 that can be used to add to this list is `org-global-properties'.
3172 The entries in this list are cons cells where the car is a property
3173 name and cdr is a string with the value. If the value represents
3174 multiple items like an \"_ALL\" property, separate the items by
3175 spaces.")
3177 (defcustom org-global-properties nil
3178 "List of property/value pairs that can be inherited by any entry.
3180 This list will be combined with the constant `org-global-properties-fixed'.
3182 The entries in this list are cons cells where the car is a property
3183 name and cdr is a string with the value.
3185 You can set buffer-local values for the same purpose in the variable
3186 `org-file-properties' this by adding lines like
3188 #+PROPERTY: NAME VALUE"
3189 :group 'org-properties
3190 :type '(repeat
3191 (cons (string :tag "Property")
3192 (string :tag "Value"))))
3194 (defvar org-file-properties nil
3195 "List of property/value pairs that can be inherited by any entry.
3196 Valid for the current buffer.
3197 This variable is populated from #+PROPERTY lines.")
3198 (make-variable-buffer-local 'org-file-properties)
3200 (defgroup org-agenda nil
3201 "Options concerning agenda views in Org-mode."
3202 :tag "Org Agenda"
3203 :group 'org)
3205 (defvar org-category nil
3206 "Variable used by org files to set a category for agenda display.
3207 Such files should use a file variable to set it, for example
3209 # -*- mode: org; org-category: \"ELisp\"
3211 or contain a special line
3213 #+CATEGORY: ELisp
3215 If the file does not specify a category, then file's base name
3216 is used instead.")
3217 (make-variable-buffer-local 'org-category)
3218 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3220 (defcustom org-agenda-files nil
3221 "The files to be used for agenda display.
3222 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3223 \\[org-remove-file]. You can also use customize to edit the list.
3225 If an entry is a directory, all files in that directory that are matched by
3226 `org-agenda-file-regexp' will be part of the file list.
3228 If the value of the variable is not a list but a single file name, then
3229 the list of agenda files is actually stored and maintained in that file, one
3230 agenda file per line. In this file paths can be given relative to
3231 `org-directory'. Tilde expansion and environment variable substitution
3232 are also made."
3233 :group 'org-agenda
3234 :type '(choice
3235 (repeat :tag "List of files and directories" file)
3236 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3238 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3239 "Regular expression to match files for `org-agenda-files'.
3240 If any element in the list in that variable contains a directory instead
3241 of a normal file, all files in that directory that are matched by this
3242 regular expression will be included."
3243 :group 'org-agenda
3244 :type 'regexp)
3246 (defcustom org-agenda-text-search-extra-files nil
3247 "List of extra files to be searched by text search commands.
3248 These files will be search in addition to the agenda files by the
3249 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3250 Note that these files will only be searched for text search commands,
3251 not for the other agenda views like todo lists, tag searches or the weekly
3252 agenda. This variable is intended to list notes and possibly archive files
3253 that should also be searched by these two commands.
3254 In fact, if the first element in the list is the symbol `agenda-archives',
3255 than all archive files of all agenda files will be added to the search
3256 scope."
3257 :group 'org-agenda
3258 :type '(set :greedy t
3259 (const :tag "Agenda Archives" agenda-archives)
3260 (repeat :inline t (file))))
3262 (if (fboundp 'defvaralias)
3263 (defvaralias 'org-agenda-multi-occur-extra-files
3264 'org-agenda-text-search-extra-files))
3266 (defcustom org-agenda-skip-unavailable-files nil
3267 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3268 A nil value means to remove them, after a query, from the list."
3269 :group 'org-agenda
3270 :type 'boolean)
3272 (defcustom org-calendar-to-agenda-key [?c]
3273 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3274 The command `org-calendar-goto-agenda' will be bound to this key. The
3275 default is the character `c' because then `c' can be used to switch back and
3276 forth between agenda and calendar."
3277 :group 'org-agenda
3278 :type 'sexp)
3280 (defcustom org-calendar-agenda-action-key [?k]
3281 "The key to be installed in `calendar-mode-map' for agenda-action.
3282 The command `org-agenda-action' will be bound to this key. The
3283 default is the character `k' because we use the same key in the agenda."
3284 :group 'org-agenda
3285 :type 'sexp)
3287 (defcustom org-calendar-insert-diary-entry-key [?i]
3288 "The key to be installed in `calendar-mode-map' for adding diary entries.
3289 This option is irrelevant until `org-agenda-diary-file' has been configured
3290 to point to an Org-mode file. When that is the case, the command
3291 `org-agenda-diary-entry' will be bound to the key given here, by default
3292 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3293 if you want to continue doing this, you need to change this to a different
3294 key."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-agenda-diary-file 'diary-file
3299 "File to which to add new entries with the `i' key in agenda and calendar.
3300 When this is the symbol `diary-file', the functionality in the Emacs
3301 calendar will be used to add entries to the `diary-file'. But when this
3302 points to a file, `org-agenda-diary-entry' will be used instead."
3303 :group 'org-agenda
3304 :type '(choice
3305 (const :tag "The standard Emacs diary file" diary-file)
3306 (file :tag "Special Org file diary entries")))
3308 (eval-after-load "calendar"
3309 '(progn
3310 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3311 'org-calendar-goto-agenda)
3312 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3313 'org-agenda-action)
3314 (add-hook 'calendar-mode-hook
3315 (lambda ()
3316 (unless (eq org-agenda-diary-file 'diary-file)
3317 (define-key calendar-mode-map
3318 org-calendar-insert-diary-entry-key
3319 'org-agenda-diary-entry))))))
3321 (defgroup org-latex nil
3322 "Options for embedding LaTeX code into Org-mode."
3323 :tag "Org LaTeX"
3324 :group 'org)
3326 (defcustom org-format-latex-options
3327 '(:foreground default :background default :scale 1.0
3328 :html-foreground "Black" :html-background "Transparent"
3329 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3330 "Options for creating images from LaTeX fragments.
3331 This is a property list with the following properties:
3332 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3333 `default' means use the foreground of the default face.
3334 :background the background color, or \"Transparent\".
3335 `default' means use the background of the default face.
3336 :scale a scaling factor for the size of the images, to get more pixels
3337 :html-foreground, :html-background, :html-scale
3338 the same numbers for HTML export.
3339 :matchers a list indicating which matchers should be used to
3340 find LaTeX fragments. Valid members of this list are:
3341 \"begin\" find environments
3342 \"$1\" find single characters surrounded by $.$
3343 \"$\" find math expressions surrounded by $...$
3344 \"$$\" find math expressions surrounded by $$....$$
3345 \"\\(\" find math expressions surrounded by \\(...\\)
3346 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3347 :group 'org-latex
3348 :type 'plist)
3350 (defcustom org-format-latex-signal-error t
3351 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3352 When nil, just push out a message."
3353 :group 'org-latex
3354 :version "24.1"
3355 :type 'boolean)
3356 (defcustom org-latex-to-mathml-jar-file nil
3357 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3358 Use this to specify additional executable file say a jar file.
3360 When using MathToWeb as the converter, specify the full-path to
3361 your mathtoweb.jar file."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type '(choice
3365 (const :tag "None" nil)
3366 (file :tag "JAR file" :must-match t)))
3368 (defcustom org-latex-to-mathml-convert-command nil
3369 "Command to convert LaTeX fragments to MathML.
3370 Replace format-specifiers in the command as noted below and use
3371 `shell-command' to convert LaTeX to MathML.
3372 %j: Executable file in fully expanded form as specified by
3373 `org-latex-to-mathml-jar-file'.
3374 %I: Input LaTeX file in fully expanded form
3375 %o: Output MathML file
3376 This command is used by `org-create-math-formula'.
3378 When using MathToWeb as the converter, set this to
3379 \"java -jar %j -unicode -force -df %o %I\"."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type '(choice
3383 (const :tag "None" nil)
3384 (string :tag "\nShell command")))
3386 (defun org-format-latex-mathml-available-p ()
3387 "Return t if `org-latex-to-mathml-convert-command' is usable."
3388 (save-match-data
3389 (when (and (boundp 'org-latex-to-mathml-convert-command)
3390 org-latex-to-mathml-convert-command)
3391 (let ((executable (car (split-string
3392 org-latex-to-mathml-convert-command))))
3393 (when (executable-find executable)
3394 (if (string-match
3395 "%j" org-latex-to-mathml-convert-command)
3396 (file-readable-p org-latex-to-mathml-jar-file)
3397 t))))))
3399 (defcustom org-format-latex-header "\\documentclass{article}
3400 \\usepackage[usenames]{color}
3401 \\usepackage{amsmath}
3402 \\usepackage[mathscr]{eucal}
3403 \\pagestyle{empty} % do not remove
3404 \[PACKAGES]
3405 \[DEFAULT-PACKAGES]
3406 % The settings below are copied from fullpage.sty
3407 \\setlength{\\textwidth}{\\paperwidth}
3408 \\addtolength{\\textwidth}{-3cm}
3409 \\setlength{\\oddsidemargin}{1.5cm}
3410 \\addtolength{\\oddsidemargin}{-2.54cm}
3411 \\setlength{\\evensidemargin}{\\oddsidemargin}
3412 \\setlength{\\textheight}{\\paperheight}
3413 \\addtolength{\\textheight}{-\\headheight}
3414 \\addtolength{\\textheight}{-\\headsep}
3415 \\addtolength{\\textheight}{-\\footskip}
3416 \\addtolength{\\textheight}{-3cm}
3417 \\setlength{\\topmargin}{1.5cm}
3418 \\addtolength{\\topmargin}{-2.54cm}"
3419 "The document header used for processing LaTeX fragments.
3420 It is imperative that this header make sure that no page number
3421 appears on the page. The package defined in the variables
3422 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3423 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3424 will be appended."
3425 :group 'org-latex
3426 :type 'string)
3428 (defvar org-format-latex-header-extra nil)
3430 (defun org-set-packages-alist (var val)
3431 "Set the packages alist and make sure it has 3 elements per entry."
3432 (set var (mapcar (lambda (x)
3433 (if (and (consp x) (= (length x) 2))
3434 (list (car x) (nth 1 x) t)
3436 val)))
3438 (defun org-get-packages-alist (var)
3440 "Get the packages alist and make sure it has 3 elements per entry."
3441 (mapcar (lambda (x)
3442 (if (and (consp x) (= (length x) 2))
3443 (list (car x) (nth 1 x) t)
3445 (default-value var)))
3447 ;; The following variables are defined here because is it also used
3448 ;; when formatting latex fragments. Originally it was part of the
3449 ;; LaTeX exporter, which is why the name includes "export".
3450 (defcustom org-export-latex-default-packages-alist
3451 '(("AUTO" "inputenc" t)
3452 ("T1" "fontenc" t)
3453 ("" "fixltx2e" nil)
3454 ("" "graphicx" t)
3455 ("" "longtable" nil)
3456 ("" "float" nil)
3457 ("" "wrapfig" nil)
3458 ("" "soul" t)
3459 ("" "textcomp" t)
3460 ("" "marvosym" t)
3461 ("" "wasysym" t)
3462 ("" "latexsym" t)
3463 ("" "amssymb" t)
3464 ("" "hyperref" nil)
3465 "\\tolerance=1000"
3467 "Alist of default packages to be inserted in the header.
3468 Change this only if one of the packages here causes an incompatibility
3469 with another package you are using.
3470 The packages in this list are needed by one part or another of Org-mode
3471 to function properly.
3473 - inputenc, fontenc: for basic font and character selection
3474 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3475 for interpreting the entities in `org-entities'. You can skip some of these
3476 packages if you don't use any of the symbols in it.
3477 - graphicx: for including images
3478 - float, wrapfig: for figure placement
3479 - longtable: for long tables
3480 - hyperref: for cross references
3482 Therefore you should not modify this variable unless you know what you
3483 are doing. The one reason to change it anyway is that you might be loading
3484 some other package that conflicts with one of the default packages.
3485 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3486 If SNIPPET-FLAG is t, the package also needs to be included when
3487 compiling LaTeX snippets into images for inclusion into HTML."
3488 :group 'org-export-latex
3489 :set 'org-set-packages-alist
3490 :get 'org-get-packages-alist
3491 :version "24.1"
3492 :type '(repeat
3493 (choice
3494 (list :tag "options/package pair"
3495 (string :tag "options")
3496 (string :tag "package")
3497 (boolean :tag "Snippet"))
3498 (string :tag "A line of LaTeX"))))
3500 (defcustom org-export-latex-packages-alist nil
3501 "Alist of packages to be inserted in every LaTeX header.
3502 These will be inserted after `org-export-latex-default-packages-alist'.
3503 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3504 SNIPPET-FLAG, when t, indicates that this package is also needed when
3505 turning LaTeX snippets into images for inclusion into HTML.
3506 Make sure that you only list packages here which:
3507 - you want in every file
3508 - do not conflict with the default packages in
3509 `org-export-latex-default-packages-alist'
3510 - do not conflict with the setup in `org-format-latex-header'."
3511 :group 'org-export-latex
3512 :set 'org-set-packages-alist
3513 :get 'org-get-packages-alist
3514 :type '(repeat
3515 (choice
3516 (list :tag "options/package pair"
3517 (string :tag "options")
3518 (string :tag "package")
3519 (boolean :tag "Snippet"))
3520 (string :tag "A line of LaTeX"))))
3523 (defgroup org-appearance nil
3524 "Settings for Org-mode appearance."
3525 :tag "Org Appearance"
3526 :group 'org)
3528 (defcustom org-level-color-stars-only nil
3529 "Non-nil means fontify only the stars in each headline.
3530 When nil, the entire headline is fontified.
3531 Changing it requires restart of `font-lock-mode' to become effective
3532 also in regions already fontified."
3533 :group 'org-appearance
3534 :type 'boolean)
3536 (defcustom org-hide-leading-stars nil
3537 "Non-nil means hide the first N-1 stars in a headline.
3538 This works by using the face `org-hide' for these stars. This
3539 face is white for a light background, and black for a dark
3540 background. You may have to customize the face `org-hide' to
3541 make this work.
3542 Changing it requires restart of `font-lock-mode' to become effective
3543 also in regions already fontified.
3544 You may also set this on a per-file basis by adding one of the following
3545 lines to the buffer:
3547 #+STARTUP: hidestars
3548 #+STARTUP: showstars"
3549 :group 'org-appearance
3550 :type 'boolean)
3552 (defcustom org-hidden-keywords nil
3553 "List of symbols corresponding to keywords to be hidden the org buffer.
3554 For example, a value '(title) for this list will make the document's title
3555 appear in the buffer without the initial #+TITLE: keyword."
3556 :group 'org-appearance
3557 :version "24.1"
3558 :type '(set (const :tag "#+AUTHOR" author)
3559 (const :tag "#+DATE" date)
3560 (const :tag "#+EMAIL" email)
3561 (const :tag "#+TITLE" title)))
3563 (defcustom org-fontify-done-headline nil
3564 "Non-nil means change the face of a headline if it is marked DONE.
3565 Normally, only the TODO/DONE keyword indicates the state of a headline.
3566 When this is non-nil, the headline after the keyword is set to the
3567 `org-headline-done' as an additional indication."
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-fontify-emphasized-text t
3572 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3573 Changing this variable requires a restart of Emacs to take effect."
3574 :group 'org-appearance
3575 :type 'boolean)
3577 (defcustom org-fontify-whole-heading-line nil
3578 "Non-nil means fontify the whole line for headings.
3579 This is useful when setting a background color for the
3580 org-level-* faces."
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-highlight-latex-fragments-and-specials nil
3585 "Non-nil means fontify what is treated specially by the exporters."
3586 :group 'org-appearance
3587 :type 'boolean)
3589 (defcustom org-hide-emphasis-markers nil
3590 "Non-nil mean font-lock should hide the emphasis marker characters."
3591 :group 'org-appearance
3592 :type 'boolean)
3594 (defcustom org-pretty-entities nil
3595 "Non-nil means show entities as UTF8 characters.
3596 When nil, the \\name form remains in the buffer."
3597 :group 'org-appearance
3598 :version "24.1"
3599 :type 'boolean)
3601 (defcustom org-pretty-entities-include-sub-superscripts t
3602 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3603 :group 'org-appearance
3604 :version "24.1"
3605 :type 'boolean)
3607 (defvar org-emph-re nil
3608 "Regular expression for matching emphasis.
3609 After a match, the match groups contain these elements:
3610 0 The match of the full regular expression, including the characters
3611 before and after the proper match
3612 1 The character before the proper match, or empty at beginning of line
3613 2 The proper match, including the leading and trailing markers
3614 3 The leading marker like * or /, indicating the type of highlighting
3615 4 The text between the emphasis markers, not including the markers
3616 5 The character after the match, empty at the end of a line")
3617 (defvar org-verbatim-re nil
3618 "Regular expression for matching verbatim text.")
3619 (defvar org-emphasis-regexp-components) ; defined just below
3620 (defvar org-emphasis-alist) ; defined just below
3621 (defun org-set-emph-re (var val)
3622 "Set variable and compute the emphasis regular expression."
3623 (set var val)
3624 (when (and (boundp 'org-emphasis-alist)
3625 (boundp 'org-emphasis-regexp-components)
3626 org-emphasis-alist org-emphasis-regexp-components)
3627 (let* ((e org-emphasis-regexp-components)
3628 (pre (car e))
3629 (post (nth 1 e))
3630 (border (nth 2 e))
3631 (body (nth 3 e))
3632 (nl (nth 4 e))
3633 (body1 (concat body "*?"))
3634 (markers (mapconcat 'car org-emphasis-alist ""))
3635 (vmarkers (mapconcat
3636 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3637 org-emphasis-alist "")))
3638 ;; make sure special characters appear at the right position in the class
3639 (if (string-match "\\^" markers)
3640 (setq markers (concat (replace-match "" t t markers) "^")))
3641 (if (string-match "-" markers)
3642 (setq markers (concat (replace-match "" t t markers) "-")))
3643 (if (string-match "\\^" vmarkers)
3644 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3645 (if (string-match "-" vmarkers)
3646 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3647 (if (> nl 0)
3648 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3649 (int-to-string nl) "\\}")))
3650 ;; Make the regexp
3651 (setq org-emph-re
3652 (concat "\\([" pre "]\\|^\\)"
3653 "\\("
3654 "\\([" markers "]\\)"
3655 "\\("
3656 "[^" border "]\\|"
3657 "[^" border "]"
3658 body1
3659 "[^" border "]"
3660 "\\)"
3661 "\\3\\)"
3662 "\\([" post "]\\|$\\)"))
3663 (setq org-verbatim-re
3664 (concat "\\([" pre "]\\|^\\)"
3665 "\\("
3666 "\\([" vmarkers "]\\)"
3667 "\\("
3668 "[^" border "]\\|"
3669 "[^" border "]"
3670 body1
3671 "[^" border "]"
3672 "\\)"
3673 "\\3\\)"
3674 "\\([" post "]\\|$\\)")))))
3676 (defcustom org-emphasis-regexp-components
3677 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3678 "Components used to build the regular expression for emphasis.
3679 This is a list with five entries. Terminology: In an emphasis string
3680 like \" *strong word* \", we call the initial space PREMATCH, the final
3681 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3682 and \"trong wor\" is the body. The different components in this variable
3683 specify what is allowed/forbidden in each part:
3685 pre Chars allowed as prematch. Beginning of line will be allowed too.
3686 post Chars allowed as postmatch. End of line will be allowed too.
3687 border The chars *forbidden* as border characters.
3688 body-regexp A regexp like \".\" to match a body character. Don't use
3689 non-shy groups here, and don't allow newline here.
3690 newline The maximum number of newlines allowed in an emphasis exp.
3692 Use customize to modify this, or restart Emacs after changing it."
3693 :group 'org-appearance
3694 :set 'org-set-emph-re
3695 :type '(list
3696 (sexp :tag "Allowed chars in pre ")
3697 (sexp :tag "Allowed chars in post ")
3698 (sexp :tag "Forbidden chars in border ")
3699 (sexp :tag "Regexp for body ")
3700 (integer :tag "number of newlines allowed")
3701 (option (boolean :tag "Please ignore this button"))))
3703 (defcustom org-emphasis-alist
3704 `(("*" bold "<b>" "</b>")
3705 ("/" italic "<i>" "</i>")
3706 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3707 ("=" org-code "<code>" "</code>" verbatim)
3708 ("~" org-verbatim "<code>" "</code>" verbatim)
3709 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3710 "<del>" "</del>")
3712 "Special syntax for emphasized text.
3713 Text starting and ending with a special character will be emphasized, for
3714 example *bold*, _underlined_ and /italic/. This variable sets the marker
3715 characters, the face to be used by font-lock for highlighting in Org-mode
3716 Emacs buffers, and the HTML tags to be used for this.
3717 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3718 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3719 Use customize to modify this, or restart Emacs after changing it."
3720 :group 'org-appearance
3721 :set 'org-set-emph-re
3722 :type '(repeat
3723 (list
3724 (string :tag "Marker character")
3725 (choice
3726 (face :tag "Font-lock-face")
3727 (plist :tag "Face property list"))
3728 (string :tag "HTML start tag")
3729 (string :tag "HTML end tag")
3730 (option (const verbatim)))))
3732 (defvar org-protecting-blocks
3733 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3734 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3735 This is needed for font-lock setup.")
3737 ;;; Miscellaneous options
3739 (defgroup org-completion nil
3740 "Completion in Org-mode."
3741 :tag "Org Completion"
3742 :group 'org)
3744 (defcustom org-completion-use-ido nil
3745 "Non-nil means use ido completion wherever possible.
3746 Note that `ido-mode' must be active for this variable to be relevant.
3747 If you decide to turn this variable on, you might well want to turn off
3748 `org-outline-path-complete-in-steps'.
3749 See also `org-completion-use-iswitchb'."
3750 :group 'org-completion
3751 :type 'boolean)
3753 (defcustom org-completion-use-iswitchb nil
3754 "Non-nil means use iswitchb completion wherever possible.
3755 Note that `iswitchb-mode' must be active for this variable to be relevant.
3756 If you decide to turn this variable on, you might well want to turn off
3757 `org-outline-path-complete-in-steps'.
3758 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3759 :group 'org-completion
3760 :type 'boolean)
3762 (defcustom org-completion-fallback-command 'hippie-expand
3763 "The expansion command called by \\[pcomplete] in normal context.
3764 Normal means, no org-mode-specific context."
3765 :group 'org-completion
3766 :type 'function)
3768 ;;; Functions and variables from their packages
3769 ;; Declared here to avoid compiler warnings
3771 ;; XEmacs only
3772 (defvar outline-mode-menu-heading)
3773 (defvar outline-mode-menu-show)
3774 (defvar outline-mode-menu-hide)
3775 (defvar zmacs-regions) ; XEmacs regions
3777 ;; Emacs only
3778 (defvar mark-active)
3780 ;; Various packages
3781 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3782 (declare-function calendar-forward-day "cal-move" (arg))
3783 (declare-function calendar-goto-date "cal-move" (date))
3784 (declare-function calendar-goto-today "cal-move" ())
3785 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3786 (defvar calc-embedded-close-formula)
3787 (defvar calc-embedded-open-formula)
3788 (declare-function cdlatex-tab "ext:cdlatex" ())
3789 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3790 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3791 (defvar font-lock-unfontify-region-function)
3792 (declare-function iswitchb-read-buffer "iswitchb"
3793 (prompt &optional default require-match start matches-set))
3794 (defvar iswitchb-temp-buflist)
3795 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3796 (defvar org-agenda-tags-todo-honor-ignore-options)
3797 (declare-function org-agenda-skip "org-agenda" ())
3798 (declare-function
3799 org-agenda-format-item "org-agenda"
3800 (extra txt &optional category tags dotime noprefix remove-re habitp))
3801 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3802 (declare-function org-agenda-change-all-lines "org-agenda"
3803 (newhead hdmarker &optional fixface just-this))
3804 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3805 (declare-function org-agenda-maybe-redo "org-agenda" ())
3806 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3807 (beg end))
3808 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3809 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3810 "org-agenda" (&optional end))
3811 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3812 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3813 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3814 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3815 (declare-function org-indent-mode "org-indent" (&optional arg))
3816 (declare-function parse-time-string "parse-time" (string))
3817 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3818 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3819 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3820 (defvar remember-data-file)
3821 (defvar texmathp-why)
3822 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3823 (declare-function table--at-cell-p "table" (position &optional object at-column))
3825 (defvar w3m-current-url)
3826 (defvar w3m-current-title)
3828 (defvar org-latex-regexps)
3830 ;;; Autoload and prepare some org modules
3832 ;; Some table stuff that needs to be defined here, because it is used
3833 ;; by the functions setting up org-mode or checking for table context.
3835 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3836 "Detect an org-type or table-type table.")
3837 (defconst org-table-line-regexp "^[ \t]*|"
3838 "Detect an org-type table line.")
3839 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3840 "Detect an org-type table line.")
3841 (defconst org-table-hline-regexp "^[ \t]*|-"
3842 "Detect an org-type table hline.")
3843 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3844 "Detect a table-type table hline.")
3845 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3846 "Detect the first line outside a table when searching from within it.
3847 This works for both table types.")
3849 ;; Autoload the functions in org-table.el that are needed by functions here.
3851 (eval-and-compile
3852 (org-autoload "org-table"
3853 '(org-table-align org-table-begin org-table-blank-field
3854 org-table-convert org-table-convert-region org-table-copy-down
3855 org-table-copy-region org-table-create
3856 org-table-create-or-convert-from-region
3857 org-table-create-with-table.el org-table-current-dline
3858 org-table-cut-region org-table-delete-column org-table-edit-field
3859 org-table-edit-formulas org-table-end org-table-eval-formula
3860 org-table-export org-table-field-info
3861 org-table-get-stored-formulas org-table-goto-column
3862 org-table-hline-and-move org-table-import org-table-insert-column
3863 org-table-insert-hline org-table-insert-row org-table-iterate
3864 org-table-justify-field-maybe org-table-kill-row
3865 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3866 org-table-move-column org-table-move-column-left
3867 org-table-move-column-right org-table-move-row
3868 org-table-move-row-down org-table-move-row-up
3869 org-table-next-field org-table-next-row org-table-paste-rectangle
3870 org-table-previous-field org-table-recalculate
3871 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3872 org-table-toggle-coordinate-overlays
3873 org-table-toggle-formula-debugger org-table-wrap-region
3874 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3875 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3876 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3878 (defun org-at-table-p (&optional table-type)
3879 "Return t if the cursor is inside an org-type table.
3880 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3881 (if org-enable-table-editor
3882 (save-excursion
3883 (beginning-of-line 1)
3884 (looking-at (if table-type org-table-any-line-regexp
3885 org-table-line-regexp)))
3886 nil))
3887 (defsubst org-table-p () (org-at-table-p))
3889 (defun org-at-table.el-p ()
3890 "Return t if and only if we are at a table.el table."
3891 (and (org-at-table-p 'any)
3892 (save-excursion
3893 (goto-char (org-table-begin 'any))
3894 (looking-at org-table1-hline-regexp))))
3895 (defun org-table-recognize-table.el ()
3896 "If there is a table.el table nearby, recognize it and move into it."
3897 (if org-table-tab-recognizes-table.el
3898 (if (org-at-table.el-p)
3899 (progn
3900 (beginning-of-line 1)
3901 (if (looking-at org-table-dataline-regexp)
3903 (if (looking-at org-table1-hline-regexp)
3904 (progn
3905 (beginning-of-line 2)
3906 (if (looking-at org-table-any-border-regexp)
3907 (beginning-of-line -1)))))
3908 (if (re-search-forward "|" (org-table-end t) t)
3909 (progn
3910 (require 'table)
3911 (if (table--at-cell-p (point))
3913 (message "recognizing table.el table...")
3914 (table-recognize-table)
3915 (message "recognizing table.el table...done")))
3916 (error "This should not happen"))
3918 nil)
3919 nil))
3921 (defun org-at-table-hline-p ()
3922 "Return t if the cursor is inside a hline in a table."
3923 (if org-enable-table-editor
3924 (save-excursion
3925 (beginning-of-line 1)
3926 (looking-at org-table-hline-regexp))
3927 nil))
3929 (defvar org-table-clean-did-remove-column nil)
3931 (defun org-table-map-tables (function &optional quietly)
3932 "Apply FUNCTION to the start of all tables in the buffer."
3933 (save-excursion
3934 (save-restriction
3935 (widen)
3936 (goto-char (point-min))
3937 (while (re-search-forward org-table-any-line-regexp nil t)
3938 (unless quietly
3939 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3940 (beginning-of-line 1)
3941 (when (looking-at org-table-line-regexp)
3942 (save-excursion (funcall function))
3943 (or (looking-at org-table-line-regexp)
3944 (forward-char 1)))
3945 (re-search-forward org-table-any-border-regexp nil 1))))
3946 (unless quietly (message "Mapping tables: done")))
3948 ;; Declare and autoload functions from org-exp.el & Co
3950 (declare-function org-default-export-plist "org-exp")
3951 (declare-function org-infile-export-plist "org-exp")
3952 (declare-function org-get-current-options "org-exp")
3953 (eval-and-compile
3954 (org-autoload "org-exp"
3955 '(org-export org-export-visible
3956 org-insert-export-options-template
3957 org-table-clean-before-export))
3958 (org-autoload "org-ascii"
3959 '(org-export-as-ascii org-export-ascii-preprocess
3960 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3961 org-export-region-as-ascii))
3962 (org-autoload "org-latex"
3963 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3964 org-replace-region-by-latex org-export-region-as-latex
3965 org-export-as-latex org-export-as-pdf
3966 org-export-as-pdf-and-open))
3967 (org-autoload "org-html"
3968 '(org-export-as-html-and-open
3969 org-export-as-html-batch org-export-as-html-to-buffer
3970 org-replace-region-by-html org-export-region-as-html
3971 org-export-as-html))
3972 (org-autoload "org-docbook"
3973 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3974 org-replace-region-by-docbook org-export-region-as-docbook
3975 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3976 org-export-as-docbook))
3977 (org-autoload "org-icalendar"
3978 '(org-export-icalendar-this-file
3979 org-export-icalendar-all-agenda-files
3980 org-export-icalendar-combine-agenda-files))
3981 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3982 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3984 ;; Declare and autoload functions from org-agenda.el
3986 (eval-and-compile
3987 (org-autoload "org-agenda"
3988 '(org-agenda org-agenda-list org-search-view
3989 org-todo-list org-tags-view org-agenda-list-stuck-projects
3990 org-diary org-agenda-to-appt
3991 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3993 ;; Autoload org-remember
3995 (eval-and-compile
3996 (org-autoload "org-remember"
3997 '(org-remember-insinuate org-remember-annotation
3998 org-remember-apply-template org-remember org-remember-handler)))
4000 (eval-and-compile
4001 (org-autoload "org-capture"
4002 '(org-capture org-capture-insert-template-here
4003 org-capture-import-remember-templates)))
4005 ;; Autoload org-clock.el
4007 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4008 (beg end))
4009 (declare-function org-clock-update-mode-line "org-clock" ())
4010 (declare-function org-resolve-clocks "org-clock"
4011 (&optional also-non-dangling-p prompt last-valid))
4012 (defvar org-clock-start-time)
4013 (defvar org-clock-marker (make-marker)
4014 "Marker recording the last clock-in.")
4015 (defvar org-clock-hd-marker (make-marker)
4016 "Marker recording the last clock-in, but the headline position.")
4017 (defvar org-clock-heading ""
4018 "The heading of the current clock entry.")
4019 (defun org-clock-is-active ()
4020 "Return non-nil if clock is currently running.
4021 The return value is actually the clock marker."
4022 (marker-buffer org-clock-marker))
4024 (eval-and-compile
4025 (org-autoload
4026 "org-clock"
4027 '(org-clock-in org-clock-out org-clock-cancel
4028 org-clock-goto org-clock-sum org-clock-display
4029 org-clock-remove-overlays org-clock-report
4030 org-clocktable-shift org-dblock-write:clocktable
4031 org-get-clocktable org-resolve-clocks)))
4033 (defun org-clock-update-time-maybe ()
4034 "If this is a CLOCK line, update it and return t.
4035 Otherwise, return nil."
4036 (interactive)
4037 (save-excursion
4038 (beginning-of-line 1)
4039 (skip-chars-forward " \t")
4040 (when (looking-at org-clock-string)
4041 (let ((re (concat "[ \t]*" org-clock-string
4042 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4043 "\\([ \t]*=>.*\\)?\\)?"))
4044 ts te h m s neg)
4045 (cond
4046 ((not (looking-at re))
4047 nil)
4048 ((not (match-end 2))
4049 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4050 (> org-clock-marker (point))
4051 (<= org-clock-marker (point-at-eol)))
4052 ;; The clock is running here
4053 (setq org-clock-start-time
4054 (apply 'encode-time
4055 (org-parse-time-string (match-string 1))))
4056 (org-clock-update-mode-line)))
4058 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4059 (end-of-line 1)
4060 (setq ts (match-string 1)
4061 te (match-string 3))
4062 (setq s (- (org-float-time
4063 (apply 'encode-time (org-parse-time-string te)))
4064 (org-float-time
4065 (apply 'encode-time (org-parse-time-string ts))))
4066 neg (< s 0)
4067 s (abs s)
4068 h (floor (/ s 3600))
4069 s (- s (* 3600 h))
4070 m (floor (/ s 60))
4071 s (- s (* 60 s)))
4072 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4073 t))))))
4075 (defun org-check-running-clock ()
4076 "Check if the current buffer contains the running clock.
4077 If yes, offer to stop it and to save the buffer with the changes."
4078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4079 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4080 (buffer-name))))
4081 (org-clock-out)
4082 (when (y-or-n-p "Save changed buffer?")
4083 (save-buffer))))
4085 (defun org-clocktable-try-shift (dir n)
4086 "Check if this line starts a clock table, if yes, shift the time block."
4087 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4088 (org-clocktable-shift dir n)))
4090 ;; Autoload org-timer.el
4092 (eval-and-compile
4093 (org-autoload
4094 "org-timer"
4095 '(org-timer-start org-timer org-timer-item
4096 org-timer-change-times-in-region
4097 org-timer-set-timer
4098 org-timer-reset-timers
4099 org-timer-show-remaining-time)))
4101 ;; Autoload org-feed.el
4103 (eval-and-compile
4104 (org-autoload
4105 "org-feed"
4106 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4109 ;; Autoload org-indent.el
4111 ;; Define the variable already here, to make sure we have it.
4112 (defvar org-indent-mode nil
4113 "Non-nil if Org-Indent mode is enabled.
4114 Use the command `org-indent-mode' to change this variable.")
4116 (eval-and-compile
4117 (org-autoload
4118 "org-indent"
4119 '(org-indent-mode)))
4121 ;; Autoload org-mobile.el
4123 (eval-and-compile
4124 (org-autoload
4125 "org-mobile"
4126 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4128 ;; Autoload archiving code
4129 ;; The stuff that is needed for cycling and tags has to be defined here.
4131 (defgroup org-archive nil
4132 "Options concerning archiving in Org-mode."
4133 :tag "Org Archive"
4134 :group 'org-structure)
4136 (defcustom org-archive-location "%s_archive::"
4137 "The location where subtrees should be archived.
4139 The value of this variable is a string, consisting of two parts,
4140 separated by a double-colon. The first part is a filename and
4141 the second part is a headline.
4143 When the filename is omitted, archiving happens in the same file.
4144 %s in the filename will be replaced by the current file
4145 name (without the directory part). Archiving to a different file
4146 is useful to keep archived entries from contributing to the
4147 Org-mode Agenda.
4149 The archived entries will be filed as subtrees of the specified
4150 headline. When the headline is omitted, the subtrees are simply
4151 filed away at the end of the file, as top-level entries. Also in
4152 the heading you can use %s to represent the file name, this can be
4153 useful when using the same archive for a number of different files.
4155 Here are a few examples:
4156 \"%s_archive::\"
4157 If the current file is Projects.org, archive in file
4158 Projects.org_archive, as top-level trees. This is the default.
4160 \"::* Archived Tasks\"
4161 Archive in the current file, under the top-level headline
4162 \"* Archived Tasks\".
4164 \"~/org/archive.org::\"
4165 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4167 \"~/org/archive.org::* From %s\"
4168 Archive in file ~/org/archive.org (absolute path), under headlines
4169 \"From FILENAME\" where file name is the current file name.
4171 \"basement::** Finished Tasks\"
4172 Archive in file ./basement (relative path), as level 3 trees
4173 below the level 2 heading \"** Finished Tasks\".
4175 You may set this option on a per-file basis by adding to the buffer a
4176 line like
4178 #+ARCHIVE: basement::** Finished Tasks
4180 You may also define it locally for a subtree by setting an ARCHIVE property
4181 in the entry. If such a property is found in an entry, or anywhere up
4182 the hierarchy, it will be used."
4183 :group 'org-archive
4184 :type 'string)
4186 (defcustom org-archive-tag "ARCHIVE"
4187 "The tag that marks a subtree as archived.
4188 An archived subtree does not open during visibility cycling, and does
4189 not contribute to the agenda listings.
4190 After changing this, font-lock must be restarted in the relevant buffers to
4191 get the proper fontification."
4192 :group 'org-archive
4193 :group 'org-keywords
4194 :type 'string)
4196 (defcustom org-agenda-skip-archived-trees t
4197 "Non-nil means the agenda will skip any items located in archived trees.
4198 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4199 variable is no longer recommended, you should leave it at the value t.
4200 Instead, use the key `v' to cycle the archives-mode in the agenda."
4201 :group 'org-archive
4202 :group 'org-agenda-skip
4203 :type 'boolean)
4205 (defcustom org-columns-skip-archived-trees t
4206 "Non-nil means ignore archived trees when creating column view."
4207 :group 'org-archive
4208 :group 'org-properties
4209 :type 'boolean)
4211 (defcustom org-cycle-open-archived-trees nil
4212 "Non-nil means `org-cycle' will open archived trees.
4213 An archived tree is a tree marked with the tag ARCHIVE.
4214 When nil, archived trees will stay folded. You can still open them with
4215 normal outline commands like `show-all', but not with the cycling commands."
4216 :group 'org-archive
4217 :group 'org-cycle
4218 :type 'boolean)
4220 (defcustom org-sparse-tree-open-archived-trees nil
4221 "Non-nil means sparse tree construction shows matches in archived trees.
4222 When nil, matches in these trees are highlighted, but the trees are kept in
4223 collapsed state."
4224 :group 'org-archive
4225 :group 'org-sparse-trees
4226 :type 'boolean)
4228 (defun org-cycle-hide-archived-subtrees (state)
4229 "Re-hide all archived subtrees after a visibility state change."
4230 (when (and (not org-cycle-open-archived-trees)
4231 (not (memq state '(overview folded))))
4232 (save-excursion
4233 (let* ((globalp (memq state '(contents all)))
4234 (beg (if globalp (point-min) (point)))
4235 (end (if globalp (point-max) (org-end-of-subtree t))))
4236 (org-hide-archived-subtrees beg end)
4237 (goto-char beg)
4238 (if (looking-at (concat ".*:" org-archive-tag ":"))
4239 (message "%s" (substitute-command-keys
4240 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4242 (defun org-force-cycle-archived ()
4243 "Cycle subtree even if it is archived."
4244 (interactive)
4245 (setq this-command 'org-cycle)
4246 (let ((org-cycle-open-archived-trees t))
4247 (call-interactively 'org-cycle)))
4249 (defun org-hide-archived-subtrees (beg end)
4250 "Re-hide all archived subtrees after a visibility state change."
4251 (save-excursion
4252 (let* ((re (concat ":" org-archive-tag ":")))
4253 (goto-char beg)
4254 (while (re-search-forward re end t)
4255 (when (org-at-heading-p)
4256 (org-flag-subtree t)
4257 (org-end-of-subtree t))))))
4259 (defun org-flag-subtree (flag)
4260 (save-excursion
4261 (org-back-to-heading t)
4262 (outline-end-of-heading)
4263 (outline-flag-region (point)
4264 (progn (org-end-of-subtree t) (point))
4265 flag)))
4267 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4269 (eval-and-compile
4270 (org-autoload "org-archive"
4271 '(org-add-archive-files org-archive-subtree
4272 org-archive-to-archive-sibling org-toggle-archive-tag
4273 org-archive-subtree-default
4274 org-archive-subtree-default-with-confirmation)))
4276 ;; Autoload Column View Code
4278 (declare-function org-columns-number-to-string "org-colview")
4279 (declare-function org-columns-get-format-and-top-level "org-colview")
4280 (declare-function org-columns-compute "org-colview")
4282 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4283 '(org-columns-number-to-string org-columns-get-format-and-top-level
4284 org-columns-compute org-agenda-columns org-columns-remove-overlays
4285 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4287 ;; Autoload ID code
4289 (declare-function org-id-store-link "org-id")
4290 (declare-function org-id-locations-load "org-id")
4291 (declare-function org-id-locations-save "org-id")
4292 (defvar org-id-track-globally)
4293 (org-autoload "org-id"
4294 '(org-id-get-create org-id-new org-id-copy org-id-get
4295 org-id-get-with-outline-path-completion
4296 org-id-get-with-outline-drilling org-id-store-link
4297 org-id-goto org-id-find org-id-store-link))
4299 ;; Autoload Plotting Code
4301 (org-autoload "org-plot"
4302 '(org-plot/gnuplot))
4304 ;;; Variables for pre-computed regular expressions, all buffer local
4306 (defvar org-drawer-regexp nil
4307 "Matches first line of a hidden block.")
4308 (make-variable-buffer-local 'org-drawer-regexp)
4309 (defvar org-todo-regexp nil
4310 "Matches any of the TODO state keywords.")
4311 (make-variable-buffer-local 'org-todo-regexp)
4312 (defvar org-not-done-regexp nil
4313 "Matches any of the TODO state keywords except the last one.")
4314 (make-variable-buffer-local 'org-not-done-regexp)
4315 (defvar org-not-done-heading-regexp nil
4316 "Matches a TODO headline that is not done.")
4317 (make-variable-buffer-local 'org-not-done-regexp)
4318 (defvar org-todo-line-regexp nil
4319 "Matches a headline and puts TODO state into group 2 if present.")
4320 (make-variable-buffer-local 'org-todo-line-regexp)
4321 (defvar org-complex-heading-regexp nil
4322 "Matches a headline and puts everything into groups:
4323 group 1: the stars
4324 group 2: The todo keyword, maybe
4325 group 3: Priority cookie
4326 group 4: True headline
4327 group 5: Tags")
4328 (make-variable-buffer-local 'org-complex-heading-regexp)
4329 (defvar org-complex-heading-regexp-format nil
4330 "Printf format to make regexp to match an exact headline.
4331 This regexp will match the headline of any node which has the
4332 exact headline text that is put into the format, but may have any
4333 TODO state, priority and tags.")
4334 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4335 (defvar org-todo-line-tags-regexp nil
4336 "Matches a headline and puts TODO state into group 2 if present.
4337 Also put tags into group 4 if tags are present.")
4338 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4339 (defvar org-ds-keyword-length 12
4340 "Maximum length of the Deadline and SCHEDULED keywords.")
4341 (make-variable-buffer-local 'org-ds-keyword-length)
4342 (defvar org-deadline-regexp nil
4343 "Matches the DEADLINE keyword.")
4344 (make-variable-buffer-local 'org-deadline-regexp)
4345 (defvar org-deadline-time-regexp nil
4346 "Matches the DEADLINE keyword together with a time stamp.")
4347 (make-variable-buffer-local 'org-deadline-time-regexp)
4348 (defvar org-deadline-line-regexp nil
4349 "Matches the DEADLINE keyword and the rest of the line.")
4350 (make-variable-buffer-local 'org-deadline-line-regexp)
4351 (defvar org-scheduled-regexp nil
4352 "Matches the SCHEDULED keyword.")
4353 (make-variable-buffer-local 'org-scheduled-regexp)
4354 (defvar org-scheduled-time-regexp nil
4355 "Matches the SCHEDULED keyword together with a time stamp.")
4356 (make-variable-buffer-local 'org-scheduled-time-regexp)
4357 (defvar org-closed-time-regexp nil
4358 "Matches the CLOSED keyword together with a time stamp.")
4359 (make-variable-buffer-local 'org-closed-time-regexp)
4361 (defvar org-keyword-time-regexp nil
4362 "Matches any of the 4 keywords, together with the time stamp.")
4363 (make-variable-buffer-local 'org-keyword-time-regexp)
4364 (defvar org-keyword-time-not-clock-regexp nil
4365 "Matches any of the 3 keywords, together with the time stamp.")
4366 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4367 (defvar org-maybe-keyword-time-regexp nil
4368 "Matches a timestamp, possibly preceded by a keyword.")
4369 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4370 (defvar org-planning-or-clock-line-re nil
4371 "Matches a line with planning or clock info.")
4372 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4373 (defvar org-all-time-keywords nil
4374 "List of time keywords.")
4375 (make-variable-buffer-local 'org-all-time-keywords)
4377 (defconst org-plain-time-of-day-regexp
4378 (concat
4379 "\\(\\<[012]?[0-9]"
4380 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4381 "\\(--?"
4382 "\\(\\<[012]?[0-9]"
4383 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4384 "\\)?")
4385 "Regular expression to match a plain time or time range.
4386 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4387 groups carry important information:
4388 0 the full match
4389 1 the first time, range or not
4390 8 the second time, if it is a range.")
4392 (defconst org-plain-time-extension-regexp
4393 (concat
4394 "\\(\\<[012]?[0-9]"
4395 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4396 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4397 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4398 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4399 groups carry important information:
4400 0 the full match
4401 7 hours of duration
4402 9 minutes of duration")
4404 (defconst org-stamp-time-of-day-regexp
4405 (concat
4406 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4407 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4408 "\\(--?"
4409 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4410 "Regular expression to match a timestamp time or time range.
4411 After a match, the following groups carry important information:
4412 0 the full match
4413 1 date plus weekday, for back referencing to make sure both times are on the same day
4414 2 the first time, range or not
4415 4 the second time, if it is a range.")
4417 (defconst org-startup-options
4418 '(("fold" org-startup-folded t)
4419 ("overview" org-startup-folded t)
4420 ("nofold" org-startup-folded nil)
4421 ("showall" org-startup-folded nil)
4422 ("showeverything" org-startup-folded showeverything)
4423 ("content" org-startup-folded content)
4424 ("indent" org-startup-indented t)
4425 ("noindent" org-startup-indented nil)
4426 ("hidestars" org-hide-leading-stars t)
4427 ("showstars" org-hide-leading-stars nil)
4428 ("odd" org-odd-levels-only t)
4429 ("oddeven" org-odd-levels-only nil)
4430 ("align" org-startup-align-all-tables t)
4431 ("noalign" org-startup-align-all-tables nil)
4432 ("inlineimages" org-startup-with-inline-images t)
4433 ("noinlineimages" org-startup-with-inline-images nil)
4434 ("customtime" org-display-custom-times t)
4435 ("logdone" org-log-done time)
4436 ("lognotedone" org-log-done note)
4437 ("nologdone" org-log-done nil)
4438 ("lognoteclock-out" org-log-note-clock-out t)
4439 ("nolognoteclock-out" org-log-note-clock-out nil)
4440 ("logrepeat" org-log-repeat state)
4441 ("lognoterepeat" org-log-repeat note)
4442 ("nologrepeat" org-log-repeat nil)
4443 ("logreschedule" org-log-reschedule time)
4444 ("lognotereschedule" org-log-reschedule note)
4445 ("nologreschedule" org-log-reschedule nil)
4446 ("logredeadline" org-log-redeadline time)
4447 ("lognoteredeadline" org-log-redeadline note)
4448 ("nologredeadline" org-log-redeadline nil)
4449 ("logrefile" org-log-refile time)
4450 ("lognoterefile" org-log-refile note)
4451 ("nologrefile" org-log-refile nil)
4452 ("fninline" org-footnote-define-inline t)
4453 ("nofninline" org-footnote-define-inline nil)
4454 ("fnlocal" org-footnote-section nil)
4455 ("fnauto" org-footnote-auto-label t)
4456 ("fnprompt" org-footnote-auto-label nil)
4457 ("fnconfirm" org-footnote-auto-label confirm)
4458 ("fnplain" org-footnote-auto-label plain)
4459 ("fnadjust" org-footnote-auto-adjust t)
4460 ("nofnadjust" org-footnote-auto-adjust nil)
4461 ("constcgs" constants-unit-system cgs)
4462 ("constSI" constants-unit-system SI)
4463 ("noptag" org-tag-persistent-alist nil)
4464 ("hideblocks" org-hide-block-startup t)
4465 ("nohideblocks" org-hide-block-startup nil)
4466 ("beamer" org-startup-with-beamer-mode t)
4467 ("entitiespretty" org-pretty-entities t)
4468 ("entitiesplain" org-pretty-entities nil))
4469 "Variable associated with STARTUP options for org-mode.
4470 Each element is a list of three items: The startup options as written
4471 in the #+STARTUP line, the corresponding variable, and the value to
4472 set this variable to if the option is found. An optional forth element PUSH
4473 means to push this value onto the list in the variable.")
4475 (defun org-update-property-plist (key val props)
4476 "Update PROPS with KEY and VAL."
4477 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4478 (key (if appending (substring key 0 (- (length key) 1)) key))
4479 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4480 (previous (cdr (assoc key props))))
4481 (if appending
4482 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4483 (cons (cons key val) remainder))))
4485 (defconst org-block-regexp
4486 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4487 "Regular expression for hiding blocks.")
4488 (defconst org-heading-keyword-regexp-format
4489 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4490 "Printf format for a regexp matching an headline with some keyword.
4491 This regexp will match the headline of any node which has the
4492 exact keyword that is put into the format. The keyword isn't in
4493 any group by default, but the stars and the body are.")
4494 (defconst org-heading-keyword-maybe-regexp-format
4495 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4496 "Printf format for a regexp matching an headline, possibly with some keyword.
4497 This regexp can match any headline with the specified keyword, or
4498 without a keyword. The keyword isn't in any group by default,
4499 but the stars and the body are.")
4501 (defun org-set-regexps-and-options ()
4502 "Precompute regular expressions for current buffer."
4503 (when (eq major-mode 'org-mode)
4504 (org-set-local 'org-todo-kwd-alist nil)
4505 (org-set-local 'org-todo-key-alist nil)
4506 (org-set-local 'org-todo-key-trigger nil)
4507 (org-set-local 'org-todo-keywords-1 nil)
4508 (org-set-local 'org-done-keywords nil)
4509 (org-set-local 'org-todo-heads nil)
4510 (org-set-local 'org-todo-sets nil)
4511 (org-set-local 'org-todo-log-states nil)
4512 (org-set-local 'org-file-properties nil)
4513 (org-set-local 'org-file-tags nil)
4514 (let ((re (org-make-options-regexp
4515 '("CATEGORY" "TODO" "COLUMNS"
4516 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4517 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4518 "OPTIONS")
4519 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4520 (splitre "[ \t]+")
4521 (scripts org-use-sub-superscripts)
4522 kwds kws0 kwsa key log value cat arch tags const links hw dws
4523 tail sep kws1 prio props ftags drawers beamer-p
4524 ext-setup-or-nil setup-contents (start 0))
4525 (save-excursion
4526 (save-restriction
4527 (widen)
4528 (goto-char (point-min))
4529 (while (or (and ext-setup-or-nil
4530 (string-match re ext-setup-or-nil start)
4531 (setq start (match-end 0)))
4532 (and (setq ext-setup-or-nil nil start 0)
4533 (re-search-forward re nil t)))
4534 (setq key (upcase (match-string 1 ext-setup-or-nil))
4535 value (org-match-string-no-properties 2 ext-setup-or-nil))
4536 (if (stringp value) (setq value (org-trim value)))
4537 (cond
4538 ((equal key "CATEGORY")
4539 (setq cat value))
4540 ((member key '("SEQ_TODO" "TODO"))
4541 (push (cons 'sequence (org-split-string value splitre)) kwds))
4542 ((equal key "TYP_TODO")
4543 (push (cons 'type (org-split-string value splitre)) kwds))
4544 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4545 ;; general TODO-like setup
4546 (push (cons (intern (downcase (match-string 1 key)))
4547 (org-split-string value splitre)) kwds))
4548 ((equal key "TAGS")
4549 (setq tags (append tags (if tags '("\\n") nil)
4550 (org-split-string value splitre))))
4551 ((equal key "COLUMNS")
4552 (org-set-local 'org-columns-default-format value))
4553 ((equal key "LINK")
4554 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4555 (push (cons (match-string 1 value)
4556 (org-trim (match-string 2 value)))
4557 links)))
4558 ((equal key "PRIORITIES")
4559 (setq prio (org-split-string value " +")))
4560 ((equal key "PROPERTY")
4561 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4562 (setq props (org-update-property-plist (match-string 1 value)
4563 (match-string 2 value)
4564 props))))
4565 ((equal key "FILETAGS")
4566 (when (string-match "\\S-" value)
4567 (setq ftags
4568 (append
4569 ftags
4570 (apply 'append
4571 (mapcar (lambda (x) (org-split-string x ":"))
4572 (org-split-string value)))))))
4573 ((equal key "DRAWERS")
4574 (setq drawers (org-split-string value splitre)))
4575 ((equal key "CONSTANTS")
4576 (setq const (append const (org-split-string value splitre))))
4577 ((equal key "STARTUP")
4578 (let ((opts (org-split-string value splitre))
4579 l var val)
4580 (while (setq l (pop opts))
4581 (when (setq l (assoc l org-startup-options))
4582 (setq var (nth 1 l) val (nth 2 l))
4583 (if (not (nth 3 l))
4584 (set (make-local-variable var) val)
4585 (if (not (listp (symbol-value var)))
4586 (set (make-local-variable var) nil))
4587 (set (make-local-variable var) (symbol-value var))
4588 (add-to-list var val))))))
4589 ((equal key "ARCHIVE")
4590 (setq arch value)
4591 (remove-text-properties 0 (length arch)
4592 '(face t fontified t) arch))
4593 ((equal key "LATEX_CLASS")
4594 (setq beamer-p (equal value "beamer")))
4595 ((equal key "OPTIONS")
4596 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4597 (setq scripts (read (match-string 2 value)))))
4598 ((equal key "SETUPFILE")
4599 (setq setup-contents (org-file-contents
4600 (expand-file-name
4601 (org-remove-double-quotes value))
4602 'noerror))
4603 (if (not ext-setup-or-nil)
4604 (setq ext-setup-or-nil setup-contents start 0)
4605 (setq ext-setup-or-nil
4606 (concat (substring ext-setup-or-nil 0 start)
4607 "\n" setup-contents "\n"
4608 (substring ext-setup-or-nil start)))))))
4609 ;; search for property blocks
4610 (goto-char (point-min))
4611 (while (re-search-forward org-block-regexp nil t)
4612 (when (equal "PROPERTY" (upcase (match-string 1)))
4613 (setq value (replace-regexp-in-string
4614 "[\n\r]" " " (match-string 4)))
4615 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4616 (setq props (org-update-property-plist (match-string 1 value)
4617 (match-string 2 value)
4618 props)))))))
4619 (org-set-local 'org-use-sub-superscripts scripts)
4620 (when cat
4621 (org-set-local 'org-category (intern cat))
4622 (push (cons "CATEGORY" cat) props))
4623 (when prio
4624 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4625 (setq prio (mapcar 'string-to-char prio))
4626 (org-set-local 'org-highest-priority (nth 0 prio))
4627 (org-set-local 'org-lowest-priority (nth 1 prio))
4628 (org-set-local 'org-default-priority (nth 2 prio)))
4629 (and props (org-set-local 'org-file-properties (nreverse props)))
4630 (and ftags (org-set-local 'org-file-tags
4631 (mapcar 'org-add-prop-inherited ftags)))
4632 (and drawers (org-set-local 'org-drawers drawers))
4633 (and arch (org-set-local 'org-archive-location arch))
4634 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4635 ;; Process the TODO keywords
4636 (unless kwds
4637 ;; Use the global values as if they had been given locally.
4638 (setq kwds (default-value 'org-todo-keywords))
4639 (if (stringp (car kwds))
4640 (setq kwds (list (cons org-todo-interpretation
4641 (default-value 'org-todo-keywords)))))
4642 (setq kwds (reverse kwds)))
4643 (setq kwds (nreverse kwds))
4644 (let (inter kws kw)
4645 (while (setq kws (pop kwds))
4646 (let ((kws (or
4647 (run-hook-with-args-until-success
4648 'org-todo-setup-filter-hook kws)
4649 kws)))
4650 (setq inter (pop kws) sep (member "|" kws)
4651 kws0 (delete "|" (copy-sequence kws))
4652 kwsa nil
4653 kws1 (mapcar
4654 (lambda (x)
4655 ;; 1 2
4656 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4657 (progn
4658 (setq kw (match-string 1 x)
4659 key (and (match-end 2) (match-string 2 x))
4660 log (org-extract-log-state-settings x))
4661 (push (cons kw (and key (string-to-char key))) kwsa)
4662 (and log (push log org-todo-log-states))
4664 (error "Invalid TODO keyword %s" x)))
4665 kws0)
4666 kwsa (if kwsa (append '((:startgroup))
4667 (nreverse kwsa)
4668 '((:endgroup))))
4669 hw (car kws1)
4670 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4671 tail (list inter hw (car dws) (org-last dws))))
4672 (add-to-list 'org-todo-heads hw 'append)
4673 (push kws1 org-todo-sets)
4674 (setq org-done-keywords (append org-done-keywords dws nil))
4675 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4676 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4677 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4678 (setq org-todo-sets (nreverse org-todo-sets)
4679 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4680 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4681 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4682 ;; Process the constants
4683 (when const
4684 (let (e cst)
4685 (while (setq e (pop const))
4686 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4687 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4688 (setq org-table-formula-constants-local cst)))
4690 ;; Process the tags.
4691 (when tags
4692 (let (e tgs)
4693 (while (setq e (pop tags))
4694 (cond
4695 ((equal e "{") (push '(:startgroup) tgs))
4696 ((equal e "}") (push '(:endgroup) tgs))
4697 ((equal e "\\n") (push '(:newline) tgs))
4698 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4699 (push (cons (match-string 1 e)
4700 (string-to-char (match-string 2 e)))
4701 tgs))
4702 (t (push (list e) tgs))))
4703 (org-set-local 'org-tag-alist nil)
4704 (while (setq e (pop tgs))
4705 (or (and (stringp (car e))
4706 (assoc (car e) org-tag-alist))
4707 (push e org-tag-alist)))))
4709 ;; Compute the regular expressions and other local variables.
4710 ;; Using `org-outline-regexp-bol' would complicate them much,
4711 ;; because of the fixed white space at the end of that string.
4712 (if (not org-done-keywords)
4713 (setq org-done-keywords (and org-todo-keywords-1
4714 (list (org-last org-todo-keywords-1)))))
4715 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4716 (length org-scheduled-string)
4717 (length org-clock-string)
4718 (length org-closed-string)))
4719 org-drawer-regexp
4720 (concat "^[ \t]*:\\("
4721 (mapconcat 'regexp-quote org-drawers "\\|")
4722 "\\):[ \t]*$")
4723 org-not-done-keywords
4724 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4725 org-todo-regexp
4726 (concat "\\("
4727 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4728 "\\)")
4729 org-not-done-regexp
4730 (concat "\\("
4731 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4732 "\\)")
4733 org-not-done-heading-regexp
4734 (format org-heading-keyword-regexp-format org-not-done-regexp)
4735 org-todo-line-regexp
4736 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4737 org-complex-heading-regexp
4738 (concat "^\\(\\*+\\)"
4739 "\\(?: +" org-todo-regexp "\\)?"
4740 "\\(?: +\\(\\[#.\\]\\)\\)?"
4741 "\\(?: +\\(.*?\\)\\)?"
4742 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4743 "[ \t]*$")
4744 org-complex-heading-regexp-format
4745 (concat "^\\(\\*+\\)"
4746 "\\(?: +" org-todo-regexp "\\)?"
4747 "\\(?: +\\(\\[#.\\]\\)\\)?"
4748 "\\(?: +"
4749 ;; Stats cookies can be stuck to body.
4750 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4751 "\\(%s\\)"
4752 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4753 "\\)"
4754 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4755 "[ \t]*$")
4756 org-todo-line-tags-regexp
4757 (concat "^\\(\\*+\\)"
4758 "\\(?: +" org-todo-regexp "\\)?"
4759 "\\(?: +\\(.*?\\)\\)?"
4760 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4761 "[ \t]*$")
4762 org-deadline-regexp (concat "\\<" org-deadline-string)
4763 org-deadline-time-regexp
4764 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4765 org-deadline-line-regexp
4766 (concat "\\<\\(" org-deadline-string "\\).*")
4767 org-scheduled-regexp
4768 (concat "\\<" org-scheduled-string)
4769 org-scheduled-time-regexp
4770 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4771 org-closed-time-regexp
4772 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4773 org-keyword-time-regexp
4774 (concat "\\<\\(" org-scheduled-string
4775 "\\|" org-deadline-string
4776 "\\|" org-closed-string
4777 "\\|" org-clock-string "\\)"
4778 " *[[<]\\([^]>]+\\)[]>]")
4779 org-keyword-time-not-clock-regexp
4780 (concat "\\<\\(" org-scheduled-string
4781 "\\|" org-deadline-string
4782 "\\|" org-closed-string
4783 "\\)"
4784 " *[[<]\\([^]>]+\\)[]>]")
4785 org-maybe-keyword-time-regexp
4786 (concat "\\(\\<\\(" org-scheduled-string
4787 "\\|" org-deadline-string
4788 "\\|" org-closed-string
4789 "\\|" org-clock-string "\\)\\)?"
4790 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4791 org-planning-or-clock-line-re
4792 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4793 "\\|" org-deadline-string
4794 "\\|" org-closed-string "\\|" org-clock-string
4795 "\\)\\>\\)")
4796 org-all-time-keywords
4797 (mapcar (lambda (w) (substring w 0 -1))
4798 (list org-scheduled-string org-deadline-string
4799 org-clock-string org-closed-string))
4801 (org-compute-latex-and-specials-regexp)
4802 (org-set-font-lock-defaults))))
4804 (defun org-file-contents (file &optional noerror)
4805 "Return the contents of FILE, as a string."
4806 (if (or (not file)
4807 (not (file-readable-p file)))
4808 (if noerror
4809 (progn
4810 (message "Cannot read file \"%s\"" file)
4811 (ding) (sit-for 2)
4813 (error "Cannot read file \"%s\"" file))
4814 (with-temp-buffer
4815 (insert-file-contents file)
4816 (buffer-string))))
4818 (defun org-extract-log-state-settings (x)
4819 "Extract the log state setting from a TODO keyword string.
4820 This will extract info from a string like \"WAIT(w@/!)\"."
4821 (let (kw key log1 log2)
4822 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4823 (setq kw (match-string 1 x)
4824 key (and (match-end 2) (match-string 2 x))
4825 log1 (and (match-end 3) (match-string 3 x))
4826 log2 (and (match-end 4) (match-string 4 x)))
4827 (and (or log1 log2)
4828 (list kw
4829 (and log1 (if (equal log1 "!") 'time 'note))
4830 (and log2 (if (equal log2 "!") 'time 'note)))))))
4832 (defun org-remove-keyword-keys (list)
4833 "Remove a pair of parenthesis at the end of each string in LIST."
4834 (mapcar (lambda (x)
4835 (if (string-match "(.*)$" x)
4836 (substring x 0 (match-beginning 0))
4838 list))
4840 (defun org-assign-fast-keys (alist)
4841 "Assign fast keys to a keyword-key alist.
4842 Respect keys that are already there."
4843 (let (new e (alt ?0))
4844 (while (setq e (pop alist))
4845 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4846 (cdr e)) ;; Key already assigned.
4847 (push e new)
4848 (let ((clist (string-to-list (downcase (car e))))
4849 (used (append new alist)))
4850 (when (= (car clist) ?@)
4851 (pop clist))
4852 (while (and clist (rassoc (car clist) used))
4853 (pop clist))
4854 (unless clist
4855 (while (rassoc alt used)
4856 (incf alt)))
4857 (push (cons (car e) (or (car clist) alt)) new))))
4858 (nreverse new)))
4860 ;;; Some variables used in various places
4862 (defvar org-window-configuration nil
4863 "Used in various places to store a window configuration.")
4864 (defvar org-selected-window nil
4865 "Used in various places to store a window configuration.")
4866 (defvar org-finish-function nil
4867 "Function to be called when `C-c C-c' is used.
4868 This is for getting out of special buffers like remember.")
4871 ;; FIXME: Occasionally check by commenting these, to make sure
4872 ;; no other functions uses these, forgetting to let-bind them.
4873 (defvar entry)
4874 (defvar org-last-state)
4875 (defvar date)
4877 ;; Defined somewhere in this file, but used before definition.
4878 (defvar org-entities) ;; defined in org-entities.el
4879 (defvar org-struct-menu)
4880 (defvar org-org-menu)
4881 (defvar org-tbl-menu)
4883 ;;;; Define the Org-mode
4885 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4886 (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"))
4889 ;; We use a before-change function to check if a table might need
4890 ;; an update.
4891 (defvar org-table-may-need-update t
4892 "Indicates that a table might need an update.
4893 This variable is set by `org-before-change-function'.
4894 `org-table-align' sets it back to nil.")
4895 (defun org-before-change-function (beg end)
4896 "Every change indicates that a table might need an update."
4897 (setq org-table-may-need-update t))
4898 (defvar org-mode-map)
4899 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4900 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4901 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4902 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4903 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4904 (defvar org-table-buffer-is-an nil)
4906 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4907 ;; some places -- e.g. see the macro org-with-limited-levels.
4909 ;; In Org buffers, the value of `outline-regexp' is that of
4910 ;; `org-outline-regexp'. The only function still directly relying on
4911 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4912 ;; job when `orgstruct-mode' is active.
4913 (defvar org-outline-regexp "\\*+ "
4914 "Regexp to match Org headlines.")
4915 (defconst org-outline-regexp-bol "^\\*+ "
4916 "Regexp to match Org headlines.
4917 This is similar to `org-outline-regexp' but additionally makes
4918 sure that we are at the beginning of the line.")
4920 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4921 "Matches an headline, putting stars and text into groups.
4922 Stars are put in group 1 and the trimmed body in group 2.")
4924 (defvar buffer-face-mode-face)
4926 ;;;###autoload
4927 (define-derived-mode org-mode outline-mode "Org"
4928 "Outline-based notes management and organizer, alias
4929 \"Carsten's outline-mode for keeping track of everything.\"
4931 Org-mode develops organizational tasks around a NOTES file which
4932 contains information about projects as plain text. Org-mode is
4933 implemented on top of outline-mode, which is ideal to keep the content
4934 of large files well structured. It supports ToDo items, deadlines and
4935 time stamps, which magically appear in the diary listing of the Emacs
4936 calendar. Tables are easily created with a built-in table editor.
4937 Plain text URL-like links connect to websites, emails (VM), Usenet
4938 messages (Gnus), BBDB entries, and any files related to the project.
4939 For printing and sharing of notes, an Org-mode file (or a part of it)
4940 can be exported as a structured ASCII or HTML file.
4942 The following commands are available:
4944 \\{org-mode-map}"
4946 ;; Get rid of Outline menus, they are not needed
4947 ;; Need to do this here because define-derived-mode sets up
4948 ;; the keymap so late. Still, it is a waste to call this each time
4949 ;; we switch another buffer into org-mode.
4950 (if (featurep 'xemacs)
4951 (when (boundp 'outline-mode-menu-heading)
4952 ;; Assume this is Greg's port, it uses easymenu
4953 (easy-menu-remove outline-mode-menu-heading)
4954 (easy-menu-remove outline-mode-menu-show)
4955 (easy-menu-remove outline-mode-menu-hide))
4956 (define-key org-mode-map [menu-bar headings] 'undefined)
4957 (define-key org-mode-map [menu-bar hide] 'undefined)
4958 (define-key org-mode-map [menu-bar show] 'undefined))
4960 (org-load-modules-maybe)
4961 (easy-menu-add org-org-menu)
4962 (easy-menu-add org-tbl-menu)
4963 (org-install-agenda-files-menu)
4964 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4965 (add-to-invisibility-spec '(org-cwidth))
4966 (add-to-invisibility-spec '(org-hide-block . t))
4967 (when (featurep 'xemacs)
4968 (org-set-local 'line-move-ignore-invisible t))
4969 (org-set-local 'outline-regexp org-outline-regexp)
4970 (org-set-local 'outline-level 'org-outline-level)
4971 (setq bidi-paragraph-direction 'left-to-right)
4972 (when (and org-ellipsis
4973 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4974 (fboundp 'make-glyph-code))
4975 (unless org-display-table
4976 (setq org-display-table (make-display-table)))
4977 (set-display-table-slot
4978 org-display-table 4
4979 (vconcat (mapcar
4980 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4981 org-ellipsis)))
4982 (if (stringp org-ellipsis) org-ellipsis "..."))))
4983 (setq buffer-display-table org-display-table))
4984 (org-set-regexps-and-options)
4985 (when (and org-tag-faces (not org-tags-special-faces-re))
4986 ;; tag faces set outside customize.... force initialization.
4987 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4988 ;; Calc embedded
4989 (org-set-local 'calc-embedded-open-mode "# ")
4990 (modify-syntax-entry ?@ "w")
4991 (if org-startup-truncated (setq truncate-lines t))
4992 (org-set-local 'font-lock-unfontify-region-function
4993 'org-unfontify-region)
4994 ;; Activate before-change-function
4995 (org-set-local 'org-table-may-need-update t)
4996 (org-add-hook 'before-change-functions 'org-before-change-function nil
4997 'local)
4998 ;; Check for running clock before killing a buffer
4999 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5000 ;; Paragraphs and auto-filling
5001 (org-set-autofill-regexps)
5002 (setq indent-line-function 'org-indent-line-function)
5003 (org-update-radio-target-regexp)
5004 ;; Beginning/end of defun
5005 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5006 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5007 ;; Next error for sparse trees
5008 (org-set-local 'next-error-function 'org-occur-next-match)
5009 ;; Make sure dependence stuff works reliably, even for users who set it
5010 ;; too late :-(
5011 (if org-enforce-todo-dependencies
5012 (add-hook 'org-blocker-hook
5013 'org-block-todo-from-children-or-siblings-or-parent)
5014 (remove-hook 'org-blocker-hook
5015 'org-block-todo-from-children-or-siblings-or-parent))
5016 (if org-enforce-todo-checkbox-dependencies
5017 (add-hook 'org-blocker-hook
5018 'org-block-todo-from-checkboxes)
5019 (remove-hook 'org-blocker-hook
5020 'org-block-todo-from-checkboxes))
5022 ;; Comment characters
5023 (org-set-local 'comment-start "#")
5024 (org-set-local 'comment-padding " ")
5026 ;; Align options lines
5027 (org-set-local
5028 'align-mode-rules-list
5029 '((org-in-buffer-settings
5030 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5031 (modes . '(org-mode)))))
5033 ;; Imenu
5034 (org-set-local 'imenu-create-index-function
5035 'org-imenu-get-tree)
5037 ;; Make isearch reveal context
5038 (if (or (featurep 'xemacs)
5039 (not (boundp 'outline-isearch-open-invisible-function)))
5040 ;; Emacs 21 and XEmacs make use of the hook
5041 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5042 ;; Emacs 22 deals with this through a special variable
5043 (org-set-local 'outline-isearch-open-invisible-function
5044 (lambda (&rest ignore) (org-show-context 'isearch))))
5046 ;; Turn on org-beamer-mode?
5047 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5049 ;; Setup the pcomplete hooks
5050 (set (make-local-variable 'pcomplete-command-completion-function)
5051 'org-pcomplete-initial)
5052 (set (make-local-variable 'pcomplete-command-name-function)
5053 'org-command-at-point)
5054 (set (make-local-variable 'pcomplete-default-completion-function)
5055 'ignore)
5056 (set (make-local-variable 'pcomplete-parse-arguments-function)
5057 'org-parse-arguments)
5058 (set (make-local-variable 'pcomplete-termination-string) "")
5059 (when (>= emacs-major-version 23)
5060 (set (make-local-variable 'buffer-face-mode-face) 'org-default)
5061 (buffer-face-mode))
5063 ;; If empty file that did not turn on org-mode automatically, make it to.
5064 (if (and org-insert-mode-line-in-empty-file
5065 (org-called-interactively-p 'any)
5066 (= (point-min) (point-max)))
5067 (insert "# -*- mode: org -*-\n\n"))
5068 (unless org-inhibit-startup
5069 (when org-startup-align-all-tables
5070 (let ((bmp (buffer-modified-p)))
5071 (org-table-map-tables 'org-table-align 'quietly)
5072 (set-buffer-modified-p bmp)))
5073 (when org-startup-with-inline-images
5074 (org-display-inline-images))
5075 (when org-startup-indented
5076 (require 'org-indent)
5077 (org-indent-mode 1))
5078 (unless org-inhibit-startup-visibility-stuff
5079 (org-set-startup-visibility))))
5081 (when (fboundp 'abbrev-table-put)
5082 (abbrev-table-put org-mode-abbrev-table
5083 :parents (list text-mode-abbrev-table)))
5085 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5087 (defun org-current-time ()
5088 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5089 (if (> (car org-time-stamp-rounding-minutes) 1)
5090 (let ((r (car org-time-stamp-rounding-minutes))
5091 (time (decode-time)))
5092 (apply 'encode-time
5093 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5094 (nthcdr 2 time))))
5095 (current-time)))
5097 (defun org-today ()
5098 "Return today date, considering `org-extend-today-until'."
5099 (time-to-days
5100 (time-subtract (current-time)
5101 (list 0 (* 3600 org-extend-today-until) 0))))
5103 ;;;; Font-Lock stuff, including the activators
5105 (defvar org-mouse-map (make-sparse-keymap))
5106 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5107 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5108 (when org-mouse-1-follows-link
5109 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5110 (when org-tab-follows-link
5111 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5112 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5114 (require 'font-lock)
5116 (defconst org-non-link-chars "]\t\n\r<>")
5117 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5118 "shell" "elisp" "doi" "message"))
5119 (defvar org-link-types-re nil
5120 "Matches a link that has a url-like prefix like \"http:\"")
5121 (defvar org-link-re-with-space nil
5122 "Matches a link with spaces, optional angular brackets around it.")
5123 (defvar org-link-re-with-space2 nil
5124 "Matches a link with spaces, optional angular brackets around it.")
5125 (defvar org-link-re-with-space3 nil
5126 "Matches a link with spaces, only for internal part in bracket links.")
5127 (defvar org-angle-link-re nil
5128 "Matches link with angular brackets, spaces are allowed.")
5129 (defvar org-plain-link-re nil
5130 "Matches plain link, without spaces.")
5131 (defvar org-bracket-link-regexp nil
5132 "Matches a link in double brackets.")
5133 (defvar org-bracket-link-analytic-regexp nil
5134 "Regular expression used to analyze links.
5135 Here is what the match groups contain after a match:
5136 1: http:
5137 2: http
5138 3: path
5139 4: [desc]
5140 5: desc")
5141 (defvar org-bracket-link-analytic-regexp++ nil
5142 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5143 (defvar org-any-link-re nil
5144 "Regular expression matching any link.")
5146 (defcustom org-match-sexp-depth 3
5147 "Number of stacked braces for sub/superscript matching.
5148 This has to be set before loading org.el to be effective."
5149 :group 'org-export-translation ; ??????????????????????????/
5150 :type 'integer)
5152 (defun org-create-multibrace-regexp (left right n)
5153 "Create a regular expression which will match a balanced sexp.
5154 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5155 as single character strings.
5156 The regexp returned will match the entire expression including the
5157 delimiters. It will also define a single group which contains the
5158 match except for the outermost delimiters. The maximum depth of
5159 stacked delimiters is N. Escaping delimiters is not possible."
5160 (let* ((nothing (concat "[^" left right "]*?"))
5161 (or "\\|")
5162 (re nothing)
5163 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5164 (while (> n 1)
5165 (setq n (1- n)
5166 re (concat re or next)
5167 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5168 (concat left "\\(" re "\\)" right)))
5170 (defvar org-match-substring-regexp
5171 (concat
5172 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5173 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5174 "\\|"
5175 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5176 "\\|"
5177 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5178 "The regular expression matching a sub- or superscript.")
5180 (defvar org-match-substring-with-braces-regexp
5181 (concat
5182 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5183 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5184 "\\)")
5185 "The regular expression matching a sub- or superscript, forcing braces.")
5187 (defun org-make-link-regexps ()
5188 "Update the link regular expressions.
5189 This should be called after the variable `org-link-types' has changed."
5190 (setq org-link-types-re
5191 (concat
5192 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5193 org-link-re-with-space
5194 (concat
5195 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5196 "\\([^" org-non-link-chars " ]"
5197 "[^" org-non-link-chars "]*"
5198 "[^" org-non-link-chars " ]\\)>?")
5199 org-link-re-with-space2
5200 (concat
5201 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5202 "\\([^" org-non-link-chars " ]"
5203 "[^\t\n\r]*"
5204 "[^" org-non-link-chars " ]\\)>?")
5205 org-link-re-with-space3
5206 (concat
5207 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5208 "\\([^" org-non-link-chars " ]"
5209 "[^\t\n\r]*\\)")
5210 org-angle-link-re
5211 (concat
5212 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^" org-non-link-chars "]*"
5215 "\\)>")
5216 org-plain-link-re
5217 (concat
5218 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5220 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5221 org-bracket-link-regexp
5222 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5223 org-bracket-link-analytic-regexp
5224 (concat
5225 "\\[\\["
5226 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5227 "\\([^]]+\\)"
5228 "\\]"
5229 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5230 "\\]")
5231 org-bracket-link-analytic-regexp++
5232 (concat
5233 "\\[\\["
5234 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5235 "\\([^]]+\\)"
5236 "\\]"
5237 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5238 "\\]")
5239 org-any-link-re
5240 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5241 org-angle-link-re "\\)\\|\\("
5242 org-plain-link-re "\\)")))
5244 (org-make-link-regexps)
5246 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5247 "Regular expression for fast time stamp matching.")
5248 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5249 "Regular expression for fast time stamp matching.")
5250 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5251 "Regular expression matching time strings for analysis.
5252 This one does not require the space after the date, so it can be used
5253 on a string that terminates immediately after the date.")
5254 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5255 "Regular expression matching time strings for analysis.")
5256 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5257 "Regular expression matching time stamps, with groups.")
5258 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5259 "Regular expression matching time stamps (also [..]), with groups.")
5260 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5261 "Regular expression matching a time stamp range.")
5262 (defconst org-tr-regexp-both
5263 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5264 "Regular expression matching a time stamp range.")
5265 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5266 org-ts-regexp "\\)?")
5267 "Regular expression matching a time stamp or time stamp range.")
5268 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5269 org-ts-regexp-both "\\)?")
5270 "Regular expression matching a time stamp or time stamp range.
5271 The time stamps may be either active or inactive.")
5273 (defvar org-emph-face nil)
5275 (defun org-do-emphasis-faces (limit)
5276 "Run through the buffer and add overlays to emphasized strings."
5277 (let (rtn a)
5278 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5279 (if (not (= (char-after (match-beginning 3))
5280 (char-after (match-beginning 4))))
5281 (progn
5282 (setq rtn t)
5283 (setq a (assoc (match-string 3) org-emphasis-alist))
5284 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5285 'face
5286 (nth 1 a))
5287 (and (nth 4 a)
5288 (org-remove-flyspell-overlays-in
5289 (match-beginning 0) (match-end 0)))
5290 (add-text-properties (match-beginning 2) (match-end 2)
5291 '(font-lock-multiline t org-emphasis t))
5292 (when org-hide-emphasis-markers
5293 (add-text-properties (match-end 4) (match-beginning 5)
5294 '(invisible org-link))
5295 (add-text-properties (match-beginning 3) (match-end 3)
5296 '(invisible org-link)))))
5297 (backward-char 1))
5298 rtn))
5300 (defun org-emphasize (&optional char)
5301 "Insert or change an emphasis, i.e. a font like bold or italic.
5302 If there is an active region, change that region to a new emphasis.
5303 If there is no region, just insert the marker characters and position
5304 the cursor between them.
5305 CHAR should be either the marker character, or the first character of the
5306 HTML tag associated with that emphasis. If CHAR is a space, the means
5307 to remove the emphasis of the selected region.
5308 If char is not given (for example in an interactive call) it
5309 will be prompted for."
5310 (interactive)
5311 (let ((eal org-emphasis-alist) e det
5312 (erc org-emphasis-regexp-components)
5313 (prompt "")
5314 (string "") beg end move tag c s)
5315 (if (org-region-active-p)
5316 (setq beg (region-beginning) end (region-end)
5317 string (buffer-substring beg end))
5318 (setq move t))
5320 (while (setq e (pop eal))
5321 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5322 c (aref tag 0))
5323 (push (cons c (string-to-char (car e))) det)
5324 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5325 (substring tag 1)))))
5326 (setq det (nreverse det))
5327 (unless char
5328 (message "%s" (concat "Emphasis marker or tag:" prompt))
5329 (setq char (read-char-exclusive)))
5330 (setq char (or (cdr (assoc char det)) char))
5331 (if (equal char ?\ )
5332 (setq s "" move nil)
5333 (unless (assoc (char-to-string char) org-emphasis-alist)
5334 (error "No such emphasis marker: \"%c\"" char))
5335 (setq s (char-to-string char)))
5336 (while (and (> (length string) 1)
5337 (equal (substring string 0 1) (substring string -1))
5338 (assoc (substring string 0 1) org-emphasis-alist))
5339 (setq string (substring string 1 -1)))
5340 (setq string (concat s string s))
5341 (if beg (delete-region beg end))
5342 (unless (or (bolp)
5343 (string-match (concat "[" (nth 0 erc) "\n]")
5344 (char-to-string (char-before (point)))))
5345 (insert " "))
5346 (unless (or (eobp)
5347 (string-match (concat "[" (nth 1 erc) "\n]")
5348 (char-to-string (char-after (point)))))
5349 (insert " ") (backward-char 1))
5350 (insert string)
5351 (and move (backward-char 1))))
5353 (defconst org-nonsticky-props
5354 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5356 (defsubst org-rear-nonsticky-at (pos)
5357 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5359 (defun org-activate-plain-links (limit)
5360 "Run through the buffer and add overlays to links."
5361 (catch 'exit
5362 (let (f)
5363 (if (re-search-forward org-plain-link-re limit t)
5364 (progn
5365 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5366 (setq f (get-text-property (match-beginning 0) 'face))
5367 (if (or (eq f 'org-tag)
5368 (and (listp f) (memq 'org-tag f)))
5370 (add-text-properties (match-beginning 0) (match-end 0)
5371 (list 'mouse-face 'highlight
5372 'face 'org-link
5373 'keymap org-mouse-map))
5374 (org-rear-nonsticky-at (match-end 0)))
5375 t)))))
5377 (defun org-activate-code (limit)
5378 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5379 (progn
5380 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5381 (remove-text-properties (match-beginning 0) (match-end 0)
5382 '(display t invisible t intangible t))
5383 t)))
5385 (defcustom org-src-fontify-natively nil
5386 "When non-nil, fontify code in code blocks."
5387 :type 'boolean
5388 :version "24.1"
5389 :group 'org-appearance
5390 :group 'org-babel)
5392 (defun org-fontify-meta-lines-and-blocks (limit)
5393 (condition-case nil
5394 (org-fontify-meta-lines-and-blocks-1 limit)
5395 (error (message "org-mode fontification error"))))
5397 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5398 "Fontify #+ lines and blocks, in the correct ways."
5399 (let ((case-fold-search t))
5400 (if (re-search-forward
5401 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5402 limit t)
5403 (let ((beg (match-beginning 0))
5404 (block-start (match-end 0))
5405 (block-end nil)
5406 (lang (match-string 7))
5407 (beg1 (line-beginning-position 2))
5408 (dc1 (downcase (match-string 2)))
5409 (dc3 (downcase (match-string 3)))
5410 end end1 quoting block-type ovl)
5411 (cond
5412 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5413 ;; a single line of backend-specific content
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 (add-text-properties (match-beginning 1) (match-end 3)
5418 '(font-lock-fontified t face org-meta-line))
5419 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5420 '(font-lock-fontified t face org-block))
5421 ; for backend-specific code
5423 ((and (match-end 4) (equal dc3 "begin"))
5424 ;; Truly a block
5425 (setq block-type (downcase (match-string 5))
5426 quoting (member block-type org-protecting-blocks))
5427 (when (re-search-forward
5428 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5429 nil t) ;; on purpose, we look further than LIMIT
5430 (setq end (min (point-max) (match-end 0))
5431 end1 (min (point-max) (1- (match-beginning 0))))
5432 (setq block-end (match-beginning 0))
5433 (when quoting
5434 (remove-text-properties beg end
5435 '(display t invisible t intangible t)))
5436 (add-text-properties
5437 beg end
5438 '(font-lock-fontified t font-lock-multiline t))
5439 (add-text-properties beg beg1 '(face org-meta-line))
5440 (add-text-properties end1 (min (point-max) (1+ end))
5441 '(face org-meta-line)) ; for end_src
5442 (cond
5443 ((and lang (not (string= lang "")) org-src-fontify-natively)
5444 (org-src-font-lock-fontify-block lang block-start block-end)
5445 ;; remove old background overlays
5446 (mapc (lambda (ov)
5447 (if (eq (overlay-get ov 'face) 'org-block-background)
5448 (delete-overlay ov)))
5449 (overlays-at (/ (+ beg1 block-end) 2)))
5450 ;; add a background overlay
5451 (setq ovl (make-overlay beg1 block-end))
5452 (overlay-put ovl 'face 'org-block-background)
5453 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5454 (quoting
5455 (add-text-properties beg1 (min (point-max) (1+ end1))
5456 '(face org-block))) ; end of source block
5457 ((not org-fontify-quote-and-verse-blocks))
5458 ((string= block-type "quote")
5459 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5460 ((string= block-type "verse")
5461 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5462 (add-text-properties beg beg1 '(face org-block-begin-line))
5463 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5464 '(face org-block-end-line))
5466 ((member dc1 '("title:" "author:" "email:" "date:"))
5467 (add-text-properties
5468 beg (match-end 3)
5469 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5470 '(font-lock-fontified t invisible t)
5471 '(font-lock-fontified t face org-document-info-keyword)))
5472 (add-text-properties
5473 (match-beginning 6) (match-end 6)
5474 (if (string-equal dc1 "title:")
5475 '(font-lock-fontified t face org-document-title)
5476 '(font-lock-fontified t face org-document-info))))
5477 ((not (member (char-after beg) '(?\ ?\t)))
5478 ;; just any other in-buffer setting, but not indented
5479 (add-text-properties
5480 beg (match-end 0)
5481 '(font-lock-fontified t face org-meta-line))
5483 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5484 "orgtbl:" "tblfm:" "tblname:" "results:"
5485 "call:" "header:" "headers:" "name:"))
5486 (and (match-end 4) (equal dc3 "attr")))
5487 (add-text-properties
5488 beg (match-end 0)
5489 '(font-lock-fontified t face org-meta-line))
5491 ((member dc3 '(" " ""))
5492 (add-text-properties
5493 beg (match-end 0)
5494 '(font-lock-fontified t face font-lock-comment-face)))
5495 (t nil))))))
5497 (defun org-strip-protective-commas (beg end)
5498 "Strip protective commas between BEG and END in the current buffer."
5499 (interactive "r")
5500 (save-excursion
5501 (save-match-data
5502 (goto-char beg)
5503 (let ((front-line (save-excursion
5504 (re-search-forward
5505 "[^[:space:]]" end t)
5506 (goto-char (match-beginning 0))
5507 (current-column))))
5508 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5509 (goto-char (match-beginning 1))
5510 (when (= (current-column) front-line)
5511 (replace-match "" nil nil nil 1)))))))
5513 (defun org-activate-angle-links (limit)
5514 "Run through the buffer and add overlays to links."
5515 (if (re-search-forward org-angle-link-re limit t)
5516 (progn
5517 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5518 (add-text-properties (match-beginning 0) (match-end 0)
5519 (list 'mouse-face 'highlight
5520 'keymap org-mouse-map))
5521 (org-rear-nonsticky-at (match-end 0))
5522 t)))
5524 (defun org-activate-footnote-links (limit)
5525 "Run through the buffer and add overlays to footnotes."
5526 (let ((fn (org-footnote-next-reference-or-definition limit)))
5527 (when fn
5528 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5529 (org-remove-flyspell-overlays-in beg end)
5530 (add-text-properties beg end
5531 (list 'mouse-face 'highlight
5532 'keymap org-mouse-map
5533 'help-echo
5534 (if (= (point-at-bol) beg)
5535 "Footnote definition"
5536 "Footnote reference")
5537 'font-lock-fontified t
5538 'font-lock-multiline t
5539 'face 'org-footnote))))))
5541 (defun org-activate-bracket-links (limit)
5542 "Run through the buffer and add overlays to bracketed links."
5543 (if (re-search-forward org-bracket-link-regexp limit t)
5544 (let* ((help (concat "LINK: "
5545 (org-match-string-no-properties 1)))
5546 ;; FIXME: above we should remove the escapes.
5547 ;; but that requires another match, protecting match data,
5548 ;; a lot of overhead for font-lock.
5549 (ip (org-maybe-intangible
5550 (list 'invisible 'org-link
5551 'keymap org-mouse-map 'mouse-face 'highlight
5552 'font-lock-multiline t 'help-echo help)))
5553 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5554 'font-lock-multiline t 'help-echo help)))
5555 ;; We need to remove the invisible property here. Table narrowing
5556 ;; may have made some of this invisible.
5557 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5558 (remove-text-properties (match-beginning 0) (match-end 0)
5559 '(invisible nil))
5560 (if (match-end 3)
5561 (progn
5562 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5563 (org-rear-nonsticky-at (match-beginning 3))
5564 (add-text-properties (match-beginning 3) (match-end 3) vp)
5565 (org-rear-nonsticky-at (match-end 3))
5566 (add-text-properties (match-end 3) (match-end 0) ip)
5567 (org-rear-nonsticky-at (match-end 0)))
5568 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5569 (org-rear-nonsticky-at (match-beginning 1))
5570 (add-text-properties (match-beginning 1) (match-end 1) vp)
5571 (org-rear-nonsticky-at (match-end 1))
5572 (add-text-properties (match-end 1) (match-end 0) ip)
5573 (org-rear-nonsticky-at (match-end 0)))
5574 t)))
5576 (defun org-activate-dates (limit)
5577 "Run through the buffer and add overlays to dates."
5578 (if (re-search-forward org-tsr-regexp-both limit t)
5579 (progn
5580 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5581 (add-text-properties (match-beginning 0) (match-end 0)
5582 (list 'mouse-face 'highlight
5583 'keymap org-mouse-map))
5584 (org-rear-nonsticky-at (match-end 0))
5585 (when org-display-custom-times
5586 (if (match-end 3)
5587 (org-display-custom-time (match-beginning 3) (match-end 3)))
5588 (org-display-custom-time (match-beginning 1) (match-end 1)))
5589 t)))
5591 (defvar org-target-link-regexp nil
5592 "Regular expression matching radio targets in plain text.")
5593 (make-variable-buffer-local 'org-target-link-regexp)
5594 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5595 "Regular expression matching a link target.")
5596 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5597 "Regular expression matching a radio target.")
5598 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5599 "Regular expression matching any target.")
5601 (defun org-activate-target-links (limit)
5602 "Run through the buffer and add overlays to target matches."
5603 (when org-target-link-regexp
5604 (let ((case-fold-search t))
5605 (if (re-search-forward org-target-link-regexp limit t)
5606 (progn
5607 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5608 (add-text-properties (match-beginning 0) (match-end 0)
5609 (list 'mouse-face 'highlight
5610 'keymap org-mouse-map
5611 'help-echo "Radio target link"
5612 'org-linked-text t))
5613 (org-rear-nonsticky-at (match-end 0))
5614 t)))))
5616 (defun org-update-radio-target-regexp ()
5617 "Find all radio targets in this file and update the regular expression."
5618 (interactive)
5619 (when (memq 'radio org-activate-links)
5620 (setq org-target-link-regexp
5621 (org-make-target-link-regexp (org-all-targets 'radio)))
5622 (org-restart-font-lock)))
5624 (defun org-hide-wide-columns (limit)
5625 (let (s e)
5626 (setq s (text-property-any (point) (or limit (point-max))
5627 'org-cwidth t))
5628 (when s
5629 (setq e (next-single-property-change s 'org-cwidth))
5630 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5631 (goto-char e)
5632 t)))
5634 (defvar org-latex-and-specials-regexp nil
5635 "Regular expression for highlighting export special stuff.")
5636 (defvar org-match-substring-regexp)
5637 (defvar org-match-substring-with-braces-regexp)
5639 ;; This should be with the exporter code, but we also use if for font-locking
5640 (defconst org-export-html-special-string-regexps
5641 '(("\\\\-" . "&shy;")
5642 ("---\\([^-]\\)" . "&mdash;\\1")
5643 ("--\\([^-]\\)" . "&ndash;\\1")
5644 ("\\.\\.\\." . "&hellip;"))
5645 "Regular expressions for special string conversion.")
5648 (defun org-compute-latex-and-specials-regexp ()
5649 "Compute regular expression for stuff treated specially by exporters."
5650 (if (not org-highlight-latex-fragments-and-specials)
5651 (org-set-local 'org-latex-and-specials-regexp nil)
5652 (require 'org-exp)
5653 (let*
5654 ((matchers (plist-get org-format-latex-options :matchers))
5655 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5656 org-latex-regexps)))
5657 (org-export-allow-BIND nil)
5658 (options (org-combine-plists (org-default-export-plist)
5659 (org-infile-export-plist)))
5660 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5661 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5662 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5663 (org-export-html-expand (plist-get options :expand-quoted-html))
5664 (org-export-with-special-strings (plist-get options :special-strings))
5665 (re-sub
5666 (cond
5667 ((equal org-export-with-sub-superscripts '{})
5668 (list org-match-substring-with-braces-regexp))
5669 (org-export-with-sub-superscripts
5670 (list org-match-substring-regexp))
5671 (t nil)))
5672 (re-latex
5673 (if org-export-with-LaTeX-fragments
5674 (mapcar (lambda (x) (nth 1 x)) latexs)))
5675 (re-macros
5676 (if org-export-with-TeX-macros
5677 (list (concat "\\\\"
5678 (regexp-opt
5679 (append
5681 (delq nil
5682 (mapcar 'car-safe
5683 (append org-entities-user
5684 org-entities)))
5685 (if (boundp 'org-latex-entities)
5686 (mapcar (lambda (x)
5687 (or (car-safe x) x))
5688 org-latex-entities)
5689 nil))
5690 'words))) ; FIXME
5692 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5693 (re-special (if org-export-with-special-strings
5694 (mapcar (lambda (x) (car x))
5695 org-export-html-special-string-regexps)))
5696 (re-rest
5697 (delq nil
5698 (list
5699 (if org-export-html-expand "@<[^>\n]+>")
5700 ))))
5701 (org-set-local
5702 'org-latex-and-specials-regexp
5703 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5704 re-rest) "\\|")))))
5706 (defun org-do-latex-and-special-faces (limit)
5707 "Run through the buffer and add overlays to links."
5708 (when org-latex-and-specials-regexp
5709 (let (rtn d)
5710 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5711 limit t))
5712 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5713 'face))
5714 '(org-code org-verbatim underline)))
5715 (progn
5716 (setq rtn t
5717 d (cond ((member (char-after (1+ (match-beginning 0)))
5718 '(?_ ?^)) 1)
5719 (t 0)))
5720 (font-lock-prepend-text-property
5721 (+ d (match-beginning 0)) (match-end 0)
5722 'face 'org-latex-and-export-specials)
5723 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5724 '(font-lock-multiline t)))))
5725 rtn)))
5727 (defun org-restart-font-lock ()
5728 "Restart `font-lock-mode', to force refontification."
5729 (when (and (boundp 'font-lock-mode) font-lock-mode)
5730 (font-lock-mode -1)
5731 (font-lock-mode 1)))
5733 (defun org-all-targets (&optional radio)
5734 "Return a list of all targets in this file.
5735 With optional argument RADIO, only find radio targets."
5736 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5737 rtn)
5738 (save-excursion
5739 (goto-char (point-min))
5740 (while (re-search-forward re nil t)
5741 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5742 rtn)))
5744 (defun org-make-target-link-regexp (targets)
5745 "Make regular expression matching all strings in TARGETS.
5746 The regular expression finds the targets also if there is a line break
5747 between words."
5748 (and targets
5749 (concat
5750 "\\<\\("
5751 (mapconcat
5752 (lambda (x)
5753 (setq x (regexp-quote x))
5754 (while (string-match " +" x)
5755 (setq x (replace-match "\\s-+" t t x)))
5757 targets
5758 "\\|")
5759 "\\)\\>")))
5761 (defun org-activate-tags (limit)
5762 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5765 (add-text-properties (match-beginning 1) (match-end 1)
5766 (list 'mouse-face 'highlight
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 1))
5769 t)))
5771 (defun org-outline-level ()
5772 "Compute the outline level of the heading at point.
5773 This function assumes that the cursor is at the beginning of a line matched
5774 by `outline-regexp'. Otherwise it returns garbage.
5775 If this is called at a normal headline, the level is the number of stars.
5776 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5777 (save-excursion
5778 (looking-at org-outline-regexp)
5779 (1- (- (match-end 0) (match-beginning 0)))))
5781 (defvar org-font-lock-keywords nil)
5783 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5784 "Regular expression matching a property line.")
5786 (defvar org-font-lock-hook nil
5787 "Functions to be called for special font lock stuff.")
5789 (defvar org-font-lock-set-keywords-hook nil
5790 "Functions that can manipulate `org-font-lock-extra-keywords'.
5791 This is called after `org-font-lock-extra-keywords' is defined, but before
5792 it is installed to be used by font lock. This can be useful if something
5793 needs to be inserted at a specific position in the font-lock sequence.")
5795 (defun org-font-lock-hook (limit)
5796 (run-hook-with-args 'org-font-lock-hook limit))
5798 (defun org-set-font-lock-defaults ()
5799 (let* ((em org-fontify-emphasized-text)
5800 (lk org-activate-links)
5801 (org-font-lock-extra-keywords
5802 (list
5803 ;; Call the hook
5804 '(org-font-lock-hook)
5805 ;; Headlines
5806 `(,(if org-fontify-whole-heading-line
5807 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5808 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5809 (1 (org-get-level-face 1))
5810 (2 (org-get-level-face 2))
5811 (3 (org-get-level-face 3)))
5812 ;; Table lines
5813 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5814 (1 'org-table t))
5815 ;; Table internals
5816 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5817 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5818 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5819 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5820 ;; Drawers
5821 (list org-drawer-regexp '(0 'org-special-keyword t))
5822 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5823 ;; Properties
5824 (list org-property-re
5825 '(1 'org-special-keyword t)
5826 '(3 'org-property-value t))
5827 ;; Links
5828 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5829 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5830 (if (memq 'plain lk) '(org-activate-plain-links))
5831 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5832 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5833 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5834 (if (memq 'footnote lk) '(org-activate-footnote-links))
5835 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5836 '(org-hide-wide-columns (0 nil append))
5837 ;; TODO keyword
5838 (list (format org-heading-keyword-regexp-format
5839 org-todo-regexp)
5840 '(2 (org-get-todo-face 2) t))
5841 ;; DONE
5842 (if org-fontify-done-headline
5843 (list (format org-heading-keyword-regexp-format
5844 (concat
5845 "\\(?:"
5846 (mapconcat 'regexp-quote org-done-keywords "\\|")
5847 "\\)"))
5848 '(2 'org-headline-done t))
5849 nil)
5850 ;; Priorities
5851 '(org-font-lock-add-priority-faces)
5852 ;; Tags
5853 '(org-font-lock-add-tag-faces)
5854 ;; Special keywords
5855 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5856 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5857 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5858 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5859 ;; Emphasis
5860 (if em
5861 (if (featurep 'xemacs)
5862 '(org-do-emphasis-faces (0 nil append))
5863 '(org-do-emphasis-faces)))
5864 ;; Checkboxes
5865 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5866 1 'org-checkbox prepend)
5867 (if (cdr (assq 'checkbox org-list-automatic-rules))
5868 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5869 (0 (org-get-checkbox-statistics-face) t)))
5870 ;; Description list items
5871 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5872 1 'bold prepend)
5873 ;; ARCHIVEd headings
5874 (list (concat
5875 org-outline-regexp-bol
5876 "\\(.*:" org-archive-tag ":.*\\)")
5877 '(1 'org-archived prepend))
5878 ;; Specials
5879 '(org-do-latex-and-special-faces)
5880 '(org-fontify-entities)
5881 '(org-raise-scripts)
5882 ;; Code
5883 '(org-activate-code (1 'org-code t))
5884 ;; COMMENT
5885 (list (format org-heading-keyword-regexp-format
5886 (concat "\\("
5887 org-comment-string "\\|" org-quote-string
5888 "\\)"))
5889 '(2 'org-special-keyword t))
5890 '("^#.*" (0 'font-lock-comment-face t))
5891 ;; Blocks and meta lines
5892 '(org-fontify-meta-lines-and-blocks)
5894 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5895 (run-hooks 'org-font-lock-set-keywords-hook)
5896 ;; Now set the full font-lock-keywords
5897 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5898 (org-set-local 'font-lock-defaults
5899 '(org-font-lock-keywords t nil nil backward-paragraph))
5900 (kill-local-variable 'font-lock-keywords) nil))
5902 (defun org-toggle-pretty-entities ()
5903 "Toggle the composition display of entities as UTF8 characters."
5904 (interactive)
5905 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5906 (org-restart-font-lock)
5907 (if org-pretty-entities
5908 (message "Entities are displayed as UTF8 characters")
5909 (save-restriction
5910 (widen)
5911 (org-decompose-region (point-min) (point-max))
5912 (message "Entities are displayed plain"))))
5914 (defun org-fontify-entities (limit)
5915 "Find an entity to fontify."
5916 (let (ee)
5917 (when org-pretty-entities
5918 (catch 'match
5919 (while (re-search-forward
5920 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5921 limit t)
5922 (if (and (not (org-in-indented-comment-line))
5923 (setq ee (org-entity-get (match-string 1)))
5924 (= (length (nth 6 ee)) 1))
5925 (progn
5926 (add-text-properties
5927 (match-beginning 0) (match-end 1)
5928 (list 'font-lock-fontified t))
5929 (compose-region (match-beginning 0) (match-end 1)
5930 (nth 6 ee) nil)
5931 (backward-char 1)
5932 (throw 'match t))))
5933 nil))))
5935 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5936 "Fontify string S like in Org-mode."
5937 (with-temp-buffer
5938 (insert s)
5939 (let ((org-odd-levels-only odd-levels))
5940 (org-mode)
5941 (font-lock-fontify-buffer)
5942 (buffer-string))))
5944 (defvar org-m nil)
5945 (defvar org-l nil)
5946 (defvar org-f nil)
5947 (defun org-get-level-face (n)
5948 "Get the right face for match N in font-lock matching of headlines."
5949 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5950 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5951 (if org-cycle-level-faces
5952 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5953 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5954 (cond
5955 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5956 ((eq n 2) org-f)
5957 (t (if org-level-color-stars-only nil org-f))))
5960 (defun org-get-todo-face (kwd)
5961 "Get the right face for a TODO keyword KWD.
5962 If KWD is a number, get the corresponding match group."
5963 (if (numberp kwd) (setq kwd (match-string kwd)))
5964 (or (org-face-from-face-or-color
5965 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5966 (and (member kwd org-done-keywords) 'org-done)
5967 'org-todo))
5969 (defun org-face-from-face-or-color (context inherit face-or-color)
5970 "Create a face list that inherits INHERIT, but sets the foreground color.
5971 When FACE-OR-COLOR is not a string, just return it."
5972 (if (stringp face-or-color)
5973 (list :inherit inherit
5974 (cdr (assoc context org-faces-easy-properties))
5975 face-or-color)
5976 face-or-color))
5978 (defun org-font-lock-add-tag-faces (limit)
5979 "Add the special tag faces."
5980 (when (and org-tag-faces org-tags-special-faces-re)
5981 (while (re-search-forward org-tags-special-faces-re limit t)
5982 (add-text-properties (match-beginning 1) (match-end 1)
5983 (list 'face (org-get-tag-face 1)
5984 'font-lock-fontified t))
5985 (backward-char 1))))
5987 (defun org-font-lock-add-priority-faces (limit)
5988 "Add the special priority faces."
5989 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5990 (add-text-properties
5991 (match-beginning 0) (match-end 0)
5992 (list 'face (or (org-face-from-face-or-color
5993 'priority 'org-special-keyword
5994 (cdr (assoc (char-after (match-beginning 1))
5995 org-priority-faces)))
5996 'org-special-keyword)
5997 'font-lock-fontified t))))
5999 (defun org-get-tag-face (kwd)
6000 "Get the right face for a TODO keyword KWD.
6001 If KWD is a number, get the corresponding match group."
6002 (if (numberp kwd) (setq kwd (match-string kwd)))
6003 (or (org-face-from-face-or-color
6004 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6005 'org-tag))
6007 (defun org-unfontify-region (beg end &optional maybe_loudly)
6008 "Remove fontification and activation overlays from links."
6009 (font-lock-default-unfontify-region beg end)
6010 (let* ((buffer-undo-list t)
6011 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6012 (inhibit-modification-hooks t)
6013 deactivate-mark buffer-file-name buffer-file-truename)
6014 (org-decompose-region beg end)
6015 (remove-text-properties beg end
6016 '(mouse-face t keymap t org-linked-text t
6017 invisible t intangible t
6018 org-no-flyspell t org-emphasis t))
6019 (org-remove-font-lock-display-properties beg end)))
6021 (defconst org-script-display '(((raise -0.3) (height 0.7))
6022 ((raise 0.3) (height 0.7))
6023 ((raise -0.5))
6024 ((raise 0.5)))
6025 "Display properties for showing superscripts and subscripts.")
6027 (defun org-remove-font-lock-display-properties (beg end)
6028 "Remove specific display properties that have been added by font lock.
6029 The will remove the raise properties that are used to show superscripts
6030 and subscripts."
6031 (let (next prop)
6032 (while (< beg end)
6033 (setq next (next-single-property-change beg 'display nil end)
6034 prop (get-text-property beg 'display))
6035 (if (member prop org-script-display)
6036 (put-text-property beg next 'display nil))
6037 (setq beg next))))
6039 (defun org-raise-scripts (limit)
6040 "Add raise properties to sub/superscripts."
6041 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6042 (if (re-search-forward
6043 (if (eq org-use-sub-superscripts t)
6044 org-match-substring-regexp
6045 org-match-substring-with-braces-regexp)
6046 limit t)
6047 (let* ((pos (point)) table-p comment-p
6048 (mpos (match-beginning 3))
6049 (emph-p (get-text-property mpos 'org-emphasis))
6050 (link-p (get-text-property mpos 'mouse-face))
6051 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6052 (goto-char (point-at-bol))
6053 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6054 comment-p (org-looking-at-p "[ \t]*#"))
6055 (goto-char pos)
6056 ;; FIXME: Should we go back one character here, for a_b^c
6057 ;; (goto-char (1- pos)) ;????????????????????
6058 (if (or comment-p emph-p link-p keyw-p)
6060 (put-text-property (match-beginning 3) (match-end 0)
6061 'display
6062 (if (equal (char-after (match-beginning 2)) ?^)
6063 (nth (if table-p 3 1) org-script-display)
6064 (nth (if table-p 2 0) org-script-display)))
6065 (add-text-properties (match-beginning 2) (match-end 2)
6066 (list 'invisible t
6067 'org-dwidth t 'org-dwidth-n 1))
6068 (if (and (eq (char-after (match-beginning 3)) ?{)
6069 (eq (char-before (match-end 3)) ?}))
6070 (progn
6071 (add-text-properties
6072 (match-beginning 3) (1+ (match-beginning 3))
6073 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6074 (add-text-properties
6075 (1- (match-end 3)) (match-end 3)
6076 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6077 t)))))
6079 ;;;; Visibility cycling, including org-goto and indirect buffer
6081 ;;; Cycling
6083 (defvar org-cycle-global-status nil)
6084 (make-variable-buffer-local 'org-cycle-global-status)
6085 (defvar org-cycle-subtree-status nil)
6086 (make-variable-buffer-local 'org-cycle-subtree-status)
6088 ;;;###autoload
6090 (defvar org-inlinetask-min-level)
6092 (defun org-cycle (&optional arg)
6093 "TAB-action and visibility cycling for Org-mode.
6095 This is the command invoked in Org-mode by the TAB key. Its main purpose
6096 is outline visibility cycling, but it also invokes other actions
6097 in special contexts.
6099 - When this function is called with a prefix argument, rotate the entire
6100 buffer through 3 states (global cycling)
6101 1. OVERVIEW: Show only top-level headlines.
6102 2. CONTENTS: Show all headlines of all levels, but no body text.
6103 3. SHOW ALL: Show everything.
6104 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6105 determined by the variable `org-startup-folded', and by any VISIBILITY
6106 properties in the buffer.
6107 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6108 including any drawers.
6110 - When inside a table, re-align the table and move to the next field.
6112 - When point is at the beginning of a headline, rotate the subtree started
6113 by this line through 3 different states (local cycling)
6114 1. FOLDED: Only the main headline is shown.
6115 2. CHILDREN: The main headline and the direct children are shown.
6116 From this state, you can move to one of the children
6117 and zoom in further.
6118 3. SUBTREE: Show the entire subtree, including body text.
6119 If there is no subtree, switch directly from CHILDREN to FOLDED.
6121 - When point is at the beginning of an empty headline and the variable
6122 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6123 of the headline by demoting and promoting it to likely levels. This
6124 speeds up creation document structure by pressing TAB once or several
6125 times right after creating a new headline.
6127 - When there is a numeric prefix, go up to a heading with level ARG, do
6128 a `show-subtree' and return to the previous cursor position. If ARG
6129 is negative, go up that many levels.
6131 - When point is not at the beginning of a headline, execute the global
6132 binding for TAB, which is re-indenting the line. See the option
6133 `org-cycle-emulate-tab' for details.
6135 - Special case: if point is at the beginning of the buffer and there is
6136 no headline in line 1, this function will act as if called with prefix arg
6137 (C-u TAB, same as S-TAB) also when called without prefix arg.
6138 But only if also the variable `org-cycle-global-at-bob' is t."
6139 (interactive "P")
6140 (org-load-modules-maybe)
6141 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6142 (and org-cycle-level-after-item/entry-creation
6143 (or (org-cycle-level)
6144 (org-cycle-item-indentation))))
6145 (let* ((limit-level
6146 (or org-cycle-max-level
6147 (and (boundp 'org-inlinetask-min-level)
6148 org-inlinetask-min-level
6149 (1- org-inlinetask-min-level))))
6150 (nstars (and limit-level
6151 (if org-odd-levels-only
6152 (and limit-level (1- (* limit-level 2)))
6153 limit-level)))
6154 (org-outline-regexp
6155 (if (not (eq major-mode 'org-mode))
6156 outline-regexp
6157 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6158 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6159 (not (looking-at org-outline-regexp))))
6160 (org-cycle-hook
6161 (if bob-special
6162 (delq 'org-optimize-window-after-visibility-change
6163 (copy-sequence org-cycle-hook))
6164 org-cycle-hook))
6165 (pos (point)))
6167 (if (or bob-special (equal arg '(4)))
6168 ;; special case: use global cycling
6169 (setq arg t))
6171 (cond
6173 ((equal arg '(16))
6174 (setq last-command 'dummy)
6175 (org-set-startup-visibility)
6176 (message "Startup visibility, plus VISIBILITY properties"))
6178 ((equal arg '(64))
6179 (show-all)
6180 (message "Entire buffer visible, including drawers"))
6182 ;; Table: enter it or move to the next field.
6183 ((org-at-table-p 'any)
6184 (if (org-at-table.el-p)
6185 (message "Use C-c ' to edit table.el tables")
6186 (if arg (org-table-edit-field t)
6187 (org-table-justify-field-maybe)
6188 (call-interactively 'org-table-next-field))))
6190 ((run-hook-with-args-until-success
6191 'org-tab-after-check-for-table-hook))
6193 ;; Global cycling: delegate to `org-cycle-internal-global'.
6194 ((eq arg t) (org-cycle-internal-global))
6196 ;; Drawers: delegate to `org-flag-drawer'.
6197 ((and org-drawers org-drawer-regexp
6198 (save-excursion
6199 (beginning-of-line 1)
6200 (looking-at org-drawer-regexp)))
6201 (org-flag-drawer ; toggle block visibility
6202 (not (get-char-property (match-end 0) 'invisible))))
6204 ;; Show-subtree, ARG levels up from here.
6205 ((integerp arg)
6206 (save-excursion
6207 (org-back-to-heading)
6208 (outline-up-heading (if (< arg 0) (- arg)
6209 (- (funcall outline-level) arg)))
6210 (org-show-subtree)))
6212 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6213 ((and (featurep 'org-inlinetask)
6214 (org-inlinetask-at-task-p)
6215 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6216 (org-inlinetask-toggle-visibility))
6218 ((org-try-cdlatex-tab))
6220 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6221 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6222 (save-excursion (beginning-of-line 1)
6223 (looking-at org-outline-regexp)))
6224 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6225 (org-cycle-internal-local))
6227 ;; From there: TAB emulation and template completion.
6228 (buffer-read-only (org-back-to-heading))
6230 ((run-hook-with-args-until-success
6231 'org-tab-after-check-for-cycling-hook))
6233 ((org-try-structure-completion))
6235 ((run-hook-with-args-until-success
6236 'org-tab-before-tab-emulation-hook))
6238 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6239 (or (not (bolp))
6240 (not (looking-at org-outline-regexp))))
6241 (call-interactively (global-key-binding "\t")))
6243 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6244 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6245 (or (and (eq org-cycle-emulate-tab 'white)
6246 (= (match-end 0) (point-at-eol)))
6247 (and (eq org-cycle-emulate-tab 'whitestart)
6248 (>= (match-end 0) pos))))
6250 (eq org-cycle-emulate-tab t))
6251 (call-interactively (global-key-binding "\t")))
6253 (t (save-excursion
6254 (org-back-to-heading)
6255 (org-cycle)))))))
6257 (defun org-cycle-internal-global ()
6258 "Do the global cycling action."
6259 (cond
6260 ((and (eq last-command this-command)
6261 (eq org-cycle-global-status 'overview))
6262 ;; We just created the overview - now do table of contents
6263 ;; This can be slow in very large buffers, so indicate action
6264 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6265 (message "CONTENTS...")
6266 (org-content)
6267 (message "CONTENTS...done")
6268 (setq org-cycle-global-status 'contents)
6269 (run-hook-with-args 'org-cycle-hook 'contents))
6271 ((and (eq last-command this-command)
6272 (eq org-cycle-global-status 'contents))
6273 ;; We just showed the table of contents - now show everything
6274 (run-hook-with-args 'org-pre-cycle-hook 'all)
6275 (show-all)
6276 (message "SHOW ALL")
6277 (setq org-cycle-global-status 'all)
6278 (run-hook-with-args 'org-cycle-hook 'all))
6281 ;; Default action: go to overview
6282 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6283 (org-overview)
6284 (message "OVERVIEW")
6285 (setq org-cycle-global-status 'overview)
6286 (run-hook-with-args 'org-cycle-hook 'overview))))
6288 (defun org-cycle-internal-local ()
6289 "Do the local cycling action."
6290 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6291 ;; First, determine end of headline (EOH), end of subtree or item
6292 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6293 (save-excursion
6294 (if (org-at-item-p)
6295 (progn
6296 (beginning-of-line)
6297 (setq struct (org-list-struct))
6298 (setq eoh (point-at-eol))
6299 (setq eos (org-list-get-item-end-before-blank (point) struct))
6300 (setq has-children (org-list-has-child-p (point) struct)))
6301 (org-back-to-heading)
6302 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6303 (setq eos (save-excursion
6304 (org-end-of-subtree t)
6305 (unless (eobp)
6306 (skip-chars-forward " \t\n"))
6307 (if (eobp) (point) (1- (point)))))
6308 (setq has-children
6309 (or (save-excursion
6310 (let ((level (funcall outline-level)))
6311 (outline-next-heading)
6312 (and (org-at-heading-p t)
6313 (> (funcall outline-level) level))))
6314 (save-excursion
6315 (org-list-search-forward (org-item-beginning-re) eos t)))))
6316 ;; Determine end invisible part of buffer (EOL)
6317 (beginning-of-line 2)
6318 ;; XEmacs doesn't have `next-single-char-property-change'
6319 (if (featurep 'xemacs)
6320 (while (and (not (eobp)) ;; this is like `next-line'
6321 (get-char-property (1- (point)) 'invisible))
6322 (beginning-of-line 2))
6323 (while (and (not (eobp)) ;; this is like `next-line'
6324 (get-char-property (1- (point)) 'invisible))
6325 (goto-char (next-single-char-property-change (point) 'invisible))
6326 (and (eolp) (beginning-of-line 2))))
6327 (setq eol (point)))
6328 ;; Find out what to do next and set `this-command'
6329 (cond
6330 ((= eos eoh)
6331 ;; Nothing is hidden behind this heading
6332 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6333 (message "EMPTY ENTRY")
6334 (setq org-cycle-subtree-status nil)
6335 (save-excursion
6336 (goto-char eos)
6337 (outline-next-heading)
6338 (if (outline-invisible-p) (org-flag-heading nil))))
6339 ((and (or (>= eol eos)
6340 (not (string-match "\\S-" (buffer-substring eol eos))))
6341 (or has-children
6342 (not (setq children-skipped
6343 org-cycle-skip-children-state-if-no-children))))
6344 ;; Entire subtree is hidden in one line: children view
6345 (run-hook-with-args 'org-pre-cycle-hook 'children)
6346 (if (org-at-item-p)
6347 (org-list-set-item-visibility (point-at-bol) struct 'children)
6348 (org-show-entry)
6349 (org-with-limited-levels (show-children))
6350 ;; FIXME: This slows down the func way too much.
6351 ;; How keep drawers hidden in subtree anyway?
6352 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6353 ;; (org-cycle-hide-drawers 'subtree))
6355 ;; Fold every list in subtree to top-level items.
6356 (when (eq org-cycle-include-plain-lists 'integrate)
6357 (save-excursion
6358 (org-back-to-heading)
6359 (while (org-list-search-forward (org-item-beginning-re) eos t)
6360 (beginning-of-line 1)
6361 (let* ((struct (org-list-struct))
6362 (prevs (org-list-prevs-alist struct))
6363 (end (org-list-get-bottom-point struct)))
6364 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6365 (org-list-get-all-items (point) struct prevs))
6366 (goto-char end))))))
6367 (message "CHILDREN")
6368 (save-excursion
6369 (goto-char eos)
6370 (outline-next-heading)
6371 (if (outline-invisible-p) (org-flag-heading nil)))
6372 (setq org-cycle-subtree-status 'children)
6373 (run-hook-with-args 'org-cycle-hook 'children))
6374 ((or children-skipped
6375 (and (eq last-command this-command)
6376 (eq org-cycle-subtree-status 'children)))
6377 ;; We just showed the children, or no children are there,
6378 ;; now show everything.
6379 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6380 (outline-flag-region eoh eos nil)
6381 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6382 (setq org-cycle-subtree-status 'subtree)
6383 (run-hook-with-args 'org-cycle-hook 'subtree))
6385 ;; Default action: hide the subtree.
6386 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6387 (outline-flag-region eoh eos t)
6388 (message "FOLDED")
6389 (setq org-cycle-subtree-status 'folded)
6390 (run-hook-with-args 'org-cycle-hook 'folded)))))
6392 ;;;###autoload
6393 (defun org-global-cycle (&optional arg)
6394 "Cycle the global visibility. For details see `org-cycle'.
6395 With \\[universal-argument] prefix arg, switch to startup visibility.
6396 With a numeric prefix, show all headlines up to that level."
6397 (interactive "P")
6398 (let ((org-cycle-include-plain-lists
6399 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6400 (cond
6401 ((integerp arg)
6402 (show-all)
6403 (hide-sublevels arg)
6404 (setq org-cycle-global-status 'contents))
6405 ((equal arg '(4))
6406 (org-set-startup-visibility)
6407 (message "Startup visibility, plus VISIBILITY properties."))
6409 (org-cycle '(4))))))
6411 (defun org-set-startup-visibility ()
6412 "Set the visibility required by startup options and properties."
6413 (cond
6414 ((eq org-startup-folded t)
6415 (org-cycle '(4)))
6416 ((eq org-startup-folded 'content)
6417 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6418 (org-cycle '(4)) (org-cycle '(4)))))
6419 (unless (eq org-startup-folded 'showeverything)
6420 (if org-hide-block-startup (org-hide-block-all))
6421 (org-set-visibility-according-to-property 'no-cleanup)
6422 (org-cycle-hide-archived-subtrees 'all)
6423 (org-cycle-hide-drawers 'all)
6424 (org-cycle-show-empty-lines t)))
6426 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6427 "Switch subtree visibilities according to :VISIBILITY: property."
6428 (interactive)
6429 (let (org-show-entry-below state)
6430 (save-excursion
6431 (goto-char (point-min))
6432 (while (re-search-forward
6433 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6434 nil t)
6435 (setq state (match-string 1))
6436 (save-excursion
6437 (org-back-to-heading t)
6438 (hide-subtree)
6439 (org-reveal)
6440 (cond
6441 ((equal state '("fold" "folded"))
6442 (hide-subtree))
6443 ((equal state "children")
6444 (org-show-hidden-entry)
6445 (show-children))
6446 ((equal state "content")
6447 (save-excursion
6448 (save-restriction
6449 (org-narrow-to-subtree)
6450 (org-content))))
6451 ((member state '("all" "showall"))
6452 (show-subtree)))))
6453 (unless no-cleanup
6454 (org-cycle-hide-archived-subtrees 'all)
6455 (org-cycle-hide-drawers 'all)
6456 (org-cycle-show-empty-lines 'all)))))
6458 ;; This function uses outline-regexp instead of the more fundamental
6459 ;; org-outline-regexp so that org-cycle-global works outside of Org
6460 ;; buffers, where outline-regexp is needed.
6461 (defun org-overview ()
6462 "Switch to overview mode, showing only top-level headlines.
6463 Really, this shows all headlines with level equal or greater than the level
6464 of the first headline in the buffer. This is important, because if the
6465 first headline is not level one, then (hide-sublevels 1) gives confusing
6466 results."
6467 (interactive)
6468 (let ((level (save-excursion
6469 (goto-char (point-min))
6470 (if (re-search-forward (concat "^" outline-regexp) nil t)
6471 (progn
6472 (goto-char (match-beginning 0))
6473 (funcall outline-level))))))
6474 (and level (hide-sublevels level))))
6476 (defun org-content (&optional arg)
6477 "Show all headlines in the buffer, like a table of contents.
6478 With numerical argument N, show content up to level N."
6479 (interactive "P")
6480 (save-excursion
6481 ;; Visit all headings and show their offspring
6482 (and (integerp arg) (org-overview))
6483 (goto-char (point-max))
6484 (catch 'exit
6485 (while (and (progn (condition-case nil
6486 (outline-previous-visible-heading 1)
6487 (error (goto-char (point-min))))
6489 (looking-at org-outline-regexp))
6490 (if (integerp arg)
6491 (show-children (1- arg))
6492 (show-branches))
6493 (if (bobp) (throw 'exit nil))))))
6496 (defun org-optimize-window-after-visibility-change (state)
6497 "Adjust the window after a change in outline visibility.
6498 This function is the default value of the hook `org-cycle-hook'."
6499 (when (get-buffer-window (current-buffer))
6500 (cond
6501 ((eq state 'content) nil)
6502 ((eq state 'all) nil)
6503 ((eq state 'folded) nil)
6504 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6505 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6507 (defun org-remove-empty-overlays-at (pos)
6508 "Remove outline overlays that do not contain non-white stuff."
6509 (mapc
6510 (lambda (o)
6511 (and (eq 'outline (overlay-get o 'invisible))
6512 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6513 (overlay-end o))))
6514 (delete-overlay o)))
6515 (overlays-at pos)))
6517 (defun org-clean-visibility-after-subtree-move ()
6518 "Fix visibility issues after moving a subtree."
6519 ;; First, find a reasonable region to look at:
6520 ;; Start two siblings above, end three below
6521 (let* ((beg (save-excursion
6522 (and (org-get-last-sibling)
6523 (org-get-last-sibling))
6524 (point)))
6525 (end (save-excursion
6526 (and (org-get-next-sibling)
6527 (org-get-next-sibling)
6528 (org-get-next-sibling))
6529 (if (org-at-heading-p)
6530 (point-at-eol)
6531 (point))))
6532 (level (looking-at "\\*+"))
6533 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6534 (save-excursion
6535 (save-restriction
6536 (narrow-to-region beg end)
6537 (when re
6538 ;; Properly fold already folded siblings
6539 (goto-char (point-min))
6540 (while (re-search-forward re nil t)
6541 (if (and (not (outline-invisible-p))
6542 (save-excursion
6543 (goto-char (point-at-eol)) (outline-invisible-p)))
6544 (hide-entry))))
6545 (org-cycle-show-empty-lines 'overview)
6546 (org-cycle-hide-drawers 'overview)))))
6548 (defun org-cycle-show-empty-lines (state)
6549 "Show empty lines above all visible headlines.
6550 The region to be covered depends on STATE when called through
6551 `org-cycle-hook'. Lisp program can use t for STATE to get the
6552 entire buffer covered. Note that an empty line is only shown if there
6553 are at least `org-cycle-separator-lines' empty lines before the headline."
6554 (when (not (= org-cycle-separator-lines 0))
6555 (save-excursion
6556 (let* ((n (abs org-cycle-separator-lines))
6557 (re (cond
6558 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6559 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6560 (t (let ((ns (number-to-string (- n 2))))
6561 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6562 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6563 beg end b e)
6564 (cond
6565 ((memq state '(overview contents t))
6566 (setq beg (point-min) end (point-max)))
6567 ((memq state '(children folded))
6568 (setq beg (point) end (progn (org-end-of-subtree t t)
6569 (beginning-of-line 2)
6570 (point)))))
6571 (when beg
6572 (goto-char beg)
6573 (while (re-search-forward re end t)
6574 (unless (get-char-property (match-end 1) 'invisible)
6575 (setq e (match-end 1))
6576 (if (< org-cycle-separator-lines 0)
6577 (setq b (save-excursion
6578 (goto-char (match-beginning 0))
6579 (org-back-over-empty-lines)
6580 (if (save-excursion
6581 (goto-char (max (point-min) (1- (point))))
6582 (org-at-heading-p))
6583 (1- (point))
6584 (point))))
6585 (setq b (match-beginning 1)))
6586 (outline-flag-region b e nil)))))))
6587 ;; Never hide empty lines at the end of the file.
6588 (save-excursion
6589 (goto-char (point-max))
6590 (outline-previous-heading)
6591 (outline-end-of-heading)
6592 (if (and (looking-at "[ \t\n]+")
6593 (= (match-end 0) (point-max)))
6594 (outline-flag-region (point) (match-end 0) nil))))
6596 (defun org-show-empty-lines-in-parent ()
6597 "Move to the parent and re-show empty lines before visible headlines."
6598 (save-excursion
6599 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6600 (org-cycle-show-empty-lines context))))
6602 (defun org-files-list ()
6603 "Return `org-agenda-files' list, plus all open org-mode files.
6604 This is useful for operations that need to scan all of a user's
6605 open and agenda-wise Org files."
6606 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6607 (dolist (buf (buffer-list))
6608 (with-current-buffer buf
6609 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6610 (let ((file (expand-file-name (buffer-file-name))))
6611 (unless (member file files)
6612 (push file files))))))
6613 files))
6615 (defsubst org-entry-beginning-position ()
6616 "Return the beginning position of the current entry."
6617 (save-excursion (outline-back-to-heading t) (point)))
6619 (defsubst org-entry-end-position ()
6620 "Return the end position of the current entry."
6621 (save-excursion (outline-next-heading) (point)))
6623 (defun org-cycle-hide-drawers (state)
6624 "Re-hide all drawers after a visibility state change."
6625 (when (and (eq major-mode 'org-mode)
6626 (not (memq state '(overview folded contents))))
6627 (save-excursion
6628 (let* ((globalp (memq state '(contents all)))
6629 (beg (if globalp (point-min) (point)))
6630 (end (if globalp (point-max)
6631 (if (eq state 'children)
6632 (save-excursion (outline-next-heading) (point))
6633 (org-end-of-subtree t)))))
6634 (goto-char beg)
6635 (while (re-search-forward org-drawer-regexp end t)
6636 (org-flag-drawer t))))))
6638 (defun org-flag-drawer (flag)
6639 (save-excursion
6640 (beginning-of-line 1)
6641 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6642 (let ((b (match-end 0)))
6643 (if (re-search-forward
6644 "^[ \t]*:END:"
6645 (save-excursion (outline-next-heading) (point)) t)
6646 (outline-flag-region b (point-at-eol) flag)
6647 (error ":END: line missing at position %s" b))))))
6649 (defun org-subtree-end-visible-p ()
6650 "Is the end of the current subtree visible?"
6651 (pos-visible-in-window-p
6652 (save-excursion (org-end-of-subtree t) (point))))
6654 (defun org-first-headline-recenter (&optional N)
6655 "Move cursor to the first headline and recenter the headline.
6656 Optional argument N means put the headline into the Nth line of the window."
6657 (goto-char (point-min))
6658 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6659 (beginning-of-line)
6660 (recenter (prefix-numeric-value N))))
6662 ;;; Saving and restoring visibility
6664 (defun org-outline-overlay-data (&optional use-markers)
6665 "Return a list of the locations of all outline overlays.
6666 These are overlays with the `invisible' property value `outline'.
6667 The return value is a list of cons cells, with start and stop
6668 positions for each overlay.
6669 If USE-MARKERS is set, return the positions as markers."
6670 (let (beg end)
6671 (save-excursion
6672 (save-restriction
6673 (widen)
6674 (delq nil
6675 (mapcar (lambda (o)
6676 (when (eq (overlay-get o 'invisible) 'outline)
6677 (setq beg (overlay-start o)
6678 end (overlay-end o))
6679 (and beg end (> end beg)
6680 (if use-markers
6681 (cons (move-marker (make-marker) beg)
6682 (move-marker (make-marker) end))
6683 (cons beg end)))))
6684 (overlays-in (point-min) (point-max))))))))
6686 (defun org-set-outline-overlay-data (data)
6687 "Create visibility overlays for all positions in DATA.
6688 DATA should have been made by `org-outline-overlay-data'."
6689 (let (o)
6690 (save-excursion
6691 (save-restriction
6692 (widen)
6693 (show-all)
6694 (mapc (lambda (c)
6695 (outline-flag-region (car c) (cdr c) t))
6696 data)))))
6698 ;;; Folding of blocks
6700 (defvar org-hide-block-overlays nil
6701 "Overlays hiding blocks.")
6702 (make-variable-buffer-local 'org-hide-block-overlays)
6704 (defun org-block-map (function &optional start end)
6705 "Call FUNCTION at the head of all source blocks in the current buffer.
6706 Optional arguments START and END can be used to limit the range."
6707 (let ((start (or start (point-min)))
6708 (end (or end (point-max))))
6709 (save-excursion
6710 (goto-char start)
6711 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6712 (save-excursion
6713 (save-match-data
6714 (goto-char (match-beginning 0))
6715 (funcall function)))))))
6717 (defun org-hide-block-toggle-all ()
6718 "Toggle the visibility of all blocks in the current buffer."
6719 (org-block-map #'org-hide-block-toggle))
6721 (defun org-hide-block-all ()
6722 "Fold all blocks in the current buffer."
6723 (interactive)
6724 (org-show-block-all)
6725 (org-block-map #'org-hide-block-toggle-maybe))
6727 (defun org-show-block-all ()
6728 "Unfold all blocks in the current buffer."
6729 (interactive)
6730 (mapc 'delete-overlay org-hide-block-overlays)
6731 (setq org-hide-block-overlays nil))
6733 (defun org-hide-block-toggle-maybe ()
6734 "Toggle visibility of block at point."
6735 (interactive)
6736 (let ((case-fold-search t))
6737 (if (save-excursion
6738 (beginning-of-line 1)
6739 (looking-at org-block-regexp))
6740 (progn (org-hide-block-toggle)
6741 t) ;; to signal that we took action
6742 nil))) ;; to signal that we did not
6744 (defun org-hide-block-toggle (&optional force)
6745 "Toggle the visibility of the current block."
6746 (interactive)
6747 (save-excursion
6748 (beginning-of-line)
6749 (if (re-search-forward org-block-regexp nil t)
6750 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6751 (end (match-end 0)) ;; end of entire body
6753 (if (memq t (mapcar (lambda (overlay)
6754 (eq (overlay-get overlay 'invisible)
6755 'org-hide-block))
6756 (overlays-at start)))
6757 (if (or (not force) (eq force 'off))
6758 (mapc (lambda (ov)
6759 (when (member ov org-hide-block-overlays)
6760 (setq org-hide-block-overlays
6761 (delq ov org-hide-block-overlays)))
6762 (when (eq (overlay-get ov 'invisible)
6763 'org-hide-block)
6764 (delete-overlay ov)))
6765 (overlays-at start)))
6766 (setq ov (make-overlay start end))
6767 (overlay-put ov 'invisible 'org-hide-block)
6768 ;; make the block accessible to isearch
6769 (overlay-put
6770 ov 'isearch-open-invisible
6771 (lambda (ov)
6772 (when (member ov org-hide-block-overlays)
6773 (setq org-hide-block-overlays
6774 (delq ov org-hide-block-overlays)))
6775 (when (eq (overlay-get ov 'invisible)
6776 'org-hide-block)
6777 (delete-overlay ov))))
6778 (push ov org-hide-block-overlays)))
6779 (error "Not looking at a source block"))))
6781 ;; org-tab-after-check-for-cycling-hook
6782 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6783 ;; Remove overlays when changing major mode
6784 (add-hook 'org-mode-hook
6785 (lambda () (org-add-hook 'change-major-mode-hook
6786 'org-show-block-all 'append 'local)))
6788 ;;; Org-goto
6790 (defvar org-goto-window-configuration nil)
6791 (defvar org-goto-marker nil)
6792 (defvar org-goto-map
6793 (let ((map (make-sparse-keymap)))
6794 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6795 (while (setq cmd (pop cmds))
6796 (substitute-key-definition cmd cmd map global-map)))
6797 (suppress-keymap map)
6798 (org-defkey map "\C-m" 'org-goto-ret)
6799 (org-defkey map [(return)] 'org-goto-ret)
6800 (org-defkey map [(left)] 'org-goto-left)
6801 (org-defkey map [(right)] 'org-goto-right)
6802 (org-defkey map [(control ?g)] 'org-goto-quit)
6803 (org-defkey map "\C-i" 'org-cycle)
6804 (org-defkey map [(tab)] 'org-cycle)
6805 (org-defkey map [(down)] 'outline-next-visible-heading)
6806 (org-defkey map [(up)] 'outline-previous-visible-heading)
6807 (if org-goto-auto-isearch
6808 (if (fboundp 'define-key-after)
6809 (define-key-after map [t] 'org-goto-local-auto-isearch)
6810 nil)
6811 (org-defkey map "q" 'org-goto-quit)
6812 (org-defkey map "n" 'outline-next-visible-heading)
6813 (org-defkey map "p" 'outline-previous-visible-heading)
6814 (org-defkey map "f" 'outline-forward-same-level)
6815 (org-defkey map "b" 'outline-backward-same-level)
6816 (org-defkey map "u" 'outline-up-heading))
6817 (org-defkey map "/" 'org-occur)
6818 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6819 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6820 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6821 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6822 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6823 map))
6825 (defconst org-goto-help
6826 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6827 RET=jump to location [Q]uit and return to previous location
6828 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6830 (defvar org-goto-start-pos) ; dynamically scoped parameter
6832 ;; FIXME: Docstring does not mention both interfaces
6833 (defun org-goto (&optional alternative-interface)
6834 "Look up a different location in the current file, keeping current visibility.
6836 When you want look-up or go to a different location in a document, the
6837 fastest way is often to fold the entire buffer and then dive into the tree.
6838 This method has the disadvantage, that the previous location will be folded,
6839 which may not be what you want.
6841 This command works around this by showing a copy of the current buffer
6842 in an indirect buffer, in overview mode. You can dive into the tree in
6843 that copy, use org-occur and incremental search to find a location.
6844 When pressing RET or `Q', the command returns to the original buffer in
6845 which the visibility is still unchanged. After RET it will also jump to
6846 the location selected in the indirect buffer and expose the headline
6847 hierarchy above."
6848 (interactive "P")
6849 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6850 (org-refile-use-outline-path t)
6851 (org-refile-target-verify-function nil)
6852 (interface
6853 (if (not alternative-interface)
6854 org-goto-interface
6855 (if (eq org-goto-interface 'outline)
6856 'outline-path-completion
6857 'outline)))
6858 (org-goto-start-pos (point))
6859 (selected-point
6860 (if (eq interface 'outline)
6861 (car (org-get-location (current-buffer) org-goto-help))
6862 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6863 (org-refile-check-position pa)
6864 (nth 3 pa)))))
6865 (if selected-point
6866 (progn
6867 (org-mark-ring-push org-goto-start-pos)
6868 (goto-char selected-point)
6869 (if (or (outline-invisible-p) (org-invisible-p2))
6870 (org-show-context 'org-goto)))
6871 (message "Quit"))))
6873 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6874 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6875 (defvar org-goto-local-auto-isearch-map) ; defined below
6877 (defun org-get-location (buf help)
6878 "Let the user select a location in the Org-mode buffer BUF.
6879 This function uses a recursive edit. It returns the selected position
6880 or nil."
6881 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6882 (isearch-hide-immediately nil)
6883 (isearch-search-fun-function
6884 (lambda () 'org-goto-local-search-headings))
6885 (org-goto-selected-point org-goto-exit-command)
6886 (pop-up-frames nil)
6887 (special-display-buffer-names nil)
6888 (special-display-regexps nil)
6889 (special-display-function nil))
6890 (save-excursion
6891 (save-window-excursion
6892 (delete-other-windows)
6893 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6894 (org-pop-to-buffer-same-window
6895 (condition-case nil
6896 (make-indirect-buffer (current-buffer) "*org-goto*")
6897 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6898 (with-output-to-temp-buffer "*Help*"
6899 (princ help))
6900 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6901 (setq buffer-read-only nil)
6902 (let ((org-startup-truncated t)
6903 (org-startup-folded nil)
6904 (org-startup-align-all-tables nil))
6905 (org-mode)
6906 (org-overview))
6907 (setq buffer-read-only t)
6908 (if (and (boundp 'org-goto-start-pos)
6909 (integer-or-marker-p org-goto-start-pos))
6910 (let ((org-show-hierarchy-above t)
6911 (org-show-siblings t)
6912 (org-show-following-heading t))
6913 (goto-char org-goto-start-pos)
6914 (and (outline-invisible-p) (org-show-context)))
6915 (goto-char (point-min)))
6916 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6917 (message "Select location and press RET")
6918 (use-local-map org-goto-map)
6919 (recursive-edit)
6921 (kill-buffer "*org-goto*")
6922 (cons org-goto-selected-point org-goto-exit-command)))
6924 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6925 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6926 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6927 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6929 (defun org-goto-local-search-headings (string bound noerror)
6930 "Search and make sure that any matches are in headlines."
6931 (catch 'return
6932 (while (if isearch-forward
6933 (search-forward string bound noerror)
6934 (search-backward string bound noerror))
6935 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6936 (and (member :headline context)
6937 (not (member :tags context))))
6938 (throw 'return (point))))))
6940 (defun org-goto-local-auto-isearch ()
6941 "Start isearch."
6942 (interactive)
6943 (goto-char (point-min))
6944 (let ((keys (this-command-keys)))
6945 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6946 (isearch-mode t)
6947 (isearch-process-search-char (string-to-char keys)))))
6949 (defun org-goto-ret (&optional arg)
6950 "Finish `org-goto' by going to the new location."
6951 (interactive "P")
6952 (setq org-goto-selected-point (point)
6953 org-goto-exit-command 'return)
6954 (throw 'exit nil))
6956 (defun org-goto-left ()
6957 "Finish `org-goto' by going to the new location."
6958 (interactive)
6959 (if (org-at-heading-p)
6960 (progn
6961 (beginning-of-line 1)
6962 (setq org-goto-selected-point (point)
6963 org-goto-exit-command 'left)
6964 (throw 'exit nil))
6965 (error "Not on a heading")))
6967 (defun org-goto-right ()
6968 "Finish `org-goto' by going to the new location."
6969 (interactive)
6970 (if (org-at-heading-p)
6971 (progn
6972 (setq org-goto-selected-point (point)
6973 org-goto-exit-command 'right)
6974 (throw 'exit nil))
6975 (error "Not on a heading")))
6977 (defun org-goto-quit ()
6978 "Finish `org-goto' without cursor motion."
6979 (interactive)
6980 (setq org-goto-selected-point nil)
6981 (setq org-goto-exit-command 'quit)
6982 (throw 'exit nil))
6984 ;;; Indirect buffer display of subtrees
6986 (defvar org-indirect-dedicated-frame nil
6987 "This is the frame being used for indirect tree display.")
6988 (defvar org-last-indirect-buffer nil)
6990 (defun org-tree-to-indirect-buffer (&optional arg)
6991 "Create indirect buffer and narrow it to current subtree.
6992 With numerical prefix ARG, go up to this level and then take that tree.
6993 If ARG is negative, go up that many levels.
6994 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6995 indirect buffer previously made with this command, to avoid proliferation of
6996 indirect buffers. However, when you call the command with a \
6997 \\[universal-argument] prefix, or
6998 when `org-indirect-buffer-display' is `new-frame', the last buffer
6999 is kept so that you can work with several indirect buffers at the same time.
7000 If `org-indirect-buffer-display' is `dedicated-frame', the \
7001 \\[universal-argument] prefix also
7002 requests that a new frame be made for the new buffer, so that the dedicated
7003 frame is not changed."
7004 (interactive "P")
7005 (let ((cbuf (current-buffer))
7006 (cwin (selected-window))
7007 (pos (point))
7008 beg end level heading ibuf)
7009 (save-excursion
7010 (org-back-to-heading t)
7011 (when (numberp arg)
7012 (setq level (org-outline-level))
7013 (if (< arg 0) (setq arg (+ level arg)))
7014 (while (> (setq level (org-outline-level)) arg)
7015 (outline-up-heading 1 t)))
7016 (setq beg (point)
7017 heading (org-get-heading))
7018 (org-end-of-subtree t t)
7019 (if (org-at-heading-p) (backward-char 1))
7020 (setq end (point)))
7021 (if (and (buffer-live-p org-last-indirect-buffer)
7022 (not (eq org-indirect-buffer-display 'new-frame))
7023 (not arg))
7024 (kill-buffer org-last-indirect-buffer))
7025 (setq ibuf (org-get-indirect-buffer cbuf)
7026 org-last-indirect-buffer ibuf)
7027 (cond
7028 ((or (eq org-indirect-buffer-display 'new-frame)
7029 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7030 (select-frame (make-frame))
7031 (delete-other-windows)
7032 (org-pop-to-buffer-same-window ibuf)
7033 (org-set-frame-title heading))
7034 ((eq org-indirect-buffer-display 'dedicated-frame)
7035 (raise-frame
7036 (select-frame (or (and org-indirect-dedicated-frame
7037 (frame-live-p org-indirect-dedicated-frame)
7038 org-indirect-dedicated-frame)
7039 (setq org-indirect-dedicated-frame (make-frame)))))
7040 (delete-other-windows)
7041 (org-pop-to-buffer-same-window ibuf)
7042 (org-set-frame-title (concat "Indirect: " heading)))
7043 ((eq org-indirect-buffer-display 'current-window)
7044 (org-pop-to-buffer-same-window ibuf))
7045 ((eq org-indirect-buffer-display 'other-window)
7046 (pop-to-buffer ibuf))
7047 (t (error "Invalid value")))
7048 (if (featurep 'xemacs)
7049 (save-excursion (org-mode) (turn-on-font-lock)))
7050 (narrow-to-region beg end)
7051 (show-all)
7052 (goto-char pos)
7053 (run-hook-with-args 'org-cycle-hook 'all)
7054 (and (window-live-p cwin) (select-window cwin))))
7056 (defun org-get-indirect-buffer (&optional buffer)
7057 (setq buffer (or buffer (current-buffer)))
7058 (let ((n 1) (base (buffer-name buffer)) bname)
7059 (while (buffer-live-p
7060 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7061 (setq n (1+ n)))
7062 (condition-case nil
7063 (make-indirect-buffer buffer bname 'clone)
7064 (error (make-indirect-buffer buffer bname)))))
7066 (defun org-set-frame-title (title)
7067 "Set the title of the current frame to the string TITLE."
7068 ;; FIXME: how to name a single frame in XEmacs???
7069 (unless (featurep 'xemacs)
7070 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7072 ;;;; Structure editing
7074 ;;; Inserting headlines
7076 (defun org-previous-line-empty-p ()
7077 (save-excursion
7078 (and (not (bobp))
7079 (or (beginning-of-line 0) t)
7080 (save-match-data
7081 (looking-at "[ \t]*$")))))
7083 (defun org-insert-heading (&optional force-heading invisible-ok)
7084 "Insert a new heading or item with same depth at point.
7085 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7086 If point is at the beginning of a headline, insert a sibling before the
7087 current headline. If point is not at the beginning, split the line,
7088 create the new headline with the text in the current line after point
7089 \(but see also the variable `org-M-RET-may-split-line').
7091 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7092 This is important for non-interactive uses of the command."
7093 (interactive "P")
7094 (if (or (= (buffer-size) 0)
7095 (and (not (save-excursion
7096 (and (ignore-errors (org-back-to-heading invisible-ok))
7097 (org-at-heading-p))))
7098 (or force-heading (not (org-in-item-p)))))
7099 (progn
7100 (insert "\n* ")
7101 (run-hooks 'org-insert-heading-hook))
7102 (when (or force-heading (not (org-insert-item)))
7103 (let* ((empty-line-p nil)
7104 (level nil)
7105 (on-heading (org-at-heading-p))
7106 (head (save-excursion
7107 (condition-case nil
7108 (progn
7109 (org-back-to-heading invisible-ok)
7110 (when (and (not on-heading)
7111 (featurep 'org-inlinetask)
7112 (integerp org-inlinetask-min-level)
7113 (>= (length (match-string 0))
7114 org-inlinetask-min-level))
7115 ;; Find a heading level before the inline task
7116 (while (and (setq level (org-up-heading-safe))
7117 (>= level org-inlinetask-min-level)))
7118 (if (org-at-heading-p)
7119 (org-back-to-heading invisible-ok)
7120 (error "This should not happen")))
7121 (setq empty-line-p (org-previous-line-empty-p))
7122 (match-string 0))
7123 (error "*"))))
7124 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7125 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7126 pos hide-previous previous-pos)
7127 (cond
7128 ((and (org-at-heading-p) (bolp)
7129 (or (bobp)
7130 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7131 ;; insert before the current line
7132 (open-line (if blank 2 1)))
7133 ((and (bolp)
7134 (not org-insert-heading-respect-content)
7135 (or (bobp)
7136 (save-excursion
7137 (backward-char 1) (not (outline-invisible-p)))))
7138 ;; insert right here
7139 nil)
7141 ;; somewhere in the line
7142 (save-excursion
7143 (setq previous-pos (point-at-bol))
7144 (end-of-line)
7145 (setq hide-previous (outline-invisible-p)))
7146 (and org-insert-heading-respect-content (org-show-subtree))
7147 (let ((split
7148 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7149 (save-excursion
7150 (let ((p (point)))
7151 (goto-char (point-at-bol))
7152 (and (looking-at org-complex-heading-regexp)
7153 (match-beginning 4)
7154 (> p (match-beginning 4)))))))
7155 tags pos)
7156 (cond
7157 (org-insert-heading-respect-content
7158 (org-end-of-subtree nil t)
7159 (when (featurep 'org-inlinetask)
7160 (while (and (not (eobp))
7161 (looking-at "\\(\\*+\\)[ \t]+")
7162 (>= (length (match-string 1))
7163 org-inlinetask-min-level))
7164 (org-end-of-subtree nil t)))
7165 (or (bolp) (newline))
7166 (or (org-previous-line-empty-p)
7167 (and blank (newline)))
7168 (open-line 1))
7169 ((org-at-heading-p)
7170 (when hide-previous
7171 (show-children)
7172 (org-show-entry))
7173 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7174 (setq tags (and (match-end 2) (match-string 2)))
7175 (and (match-end 1)
7176 (delete-region (match-beginning 1) (match-end 1)))
7177 (setq pos (point-at-bol))
7178 (or split (end-of-line 1))
7179 (delete-horizontal-space)
7180 (if (string-match "\\`\\*+\\'"
7181 (buffer-substring (point-at-bol) (point)))
7182 (insert " "))
7183 (newline (if blank 2 1))
7184 (when tags
7185 (save-excursion
7186 (goto-char pos)
7187 (end-of-line 1)
7188 (insert " " tags)
7189 (org-set-tags nil 'align))))
7191 (or split (end-of-line 1))
7192 (newline (if blank 2 1)))))))
7193 (insert head) (just-one-space)
7194 (setq pos (point))
7195 (end-of-line 1)
7196 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7197 (when (and org-insert-heading-respect-content hide-previous)
7198 (save-excursion
7199 (goto-char previous-pos)
7200 (hide-subtree)))
7201 (run-hooks 'org-insert-heading-hook)))))
7203 (defun org-get-heading (&optional no-tags no-todo)
7204 "Return the heading of the current entry, without the stars.
7205 When NO-TAGS is non-nil, don't include tags.
7206 When NO-TODO is non-nil, don't include TODO keywords."
7207 (save-excursion
7208 (org-back-to-heading t)
7209 (cond
7210 ((and no-tags no-todo)
7211 (looking-at org-complex-heading-regexp)
7212 (match-string 4))
7213 (no-tags
7214 (looking-at (concat org-outline-regexp
7215 "\\(.*?\\)"
7216 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7217 (match-string 1))
7218 (no-todo
7219 (looking-at org-todo-line-regexp)
7220 (match-string 3))
7221 (t (looking-at org-heading-regexp)
7222 (match-string 2)))))
7224 (defun org-heading-components ()
7225 "Return the components of the current heading.
7226 This is a list with the following elements:
7227 - the level as an integer
7228 - the reduced level, different if `org-odd-levels-only' is set.
7229 - the TODO keyword, or nil
7230 - the priority character, like ?A, or nil if no priority is given
7231 - the headline text itself, or the tags string if no headline text
7232 - the tags string, or nil."
7233 (save-excursion
7234 (org-back-to-heading t)
7235 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7236 (list (length (match-string 1))
7237 (org-reduced-level (length (match-string 1)))
7238 (org-match-string-no-properties 2)
7239 (and (match-end 3) (aref (match-string 3) 2))
7240 (org-match-string-no-properties 4)
7241 (org-match-string-no-properties 5)))))
7243 (defun org-get-entry ()
7244 "Get the entry text, after heading, entire subtree."
7245 (save-excursion
7246 (org-back-to-heading t)
7247 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7249 (defun org-insert-heading-after-current ()
7250 "Insert a new heading with same level as current, after current subtree."
7251 (interactive)
7252 (org-back-to-heading)
7253 (org-insert-heading)
7254 (org-move-subtree-down)
7255 (end-of-line 1))
7257 (defun org-insert-heading-respect-content ()
7258 (interactive)
7259 (let ((org-insert-heading-respect-content t))
7260 (org-insert-heading t)))
7262 (defun org-insert-todo-heading-respect-content (&optional force-state)
7263 (interactive "P")
7264 (let ((org-insert-heading-respect-content t))
7265 (org-insert-todo-heading force-state t)))
7267 (defun org-insert-todo-heading (arg &optional force-heading)
7268 "Insert a new heading with the same level and TODO state as current heading.
7269 If the heading has no TODO state, or if the state is DONE, use the first
7270 state (TODO by default). Also with prefix arg, force first state."
7271 (interactive "P")
7272 (when (or force-heading (not (org-insert-item 'checkbox)))
7273 (org-insert-heading force-heading)
7274 (save-excursion
7275 (org-back-to-heading)
7276 (outline-previous-heading)
7277 (looking-at org-todo-line-regexp))
7278 (let*
7279 ((new-mark-x
7280 (if (or arg
7281 (not (match-beginning 2))
7282 (member (match-string 2) org-done-keywords))
7283 (car org-todo-keywords-1)
7284 (match-string 2)))
7285 (new-mark
7287 (run-hook-with-args-until-success
7288 'org-todo-get-default-hook new-mark-x nil)
7289 new-mark-x)))
7290 (beginning-of-line 1)
7291 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7292 (if org-treat-insert-todo-heading-as-state-change
7293 (org-todo new-mark)
7294 (insert new-mark " "))))
7295 (when org-provide-todo-statistics
7296 (org-update-parent-todo-statistics))))
7298 (defun org-insert-subheading (arg)
7299 "Insert a new subheading and demote it.
7300 Works for outline headings and for plain lists alike."
7301 (interactive "P")
7302 (org-insert-heading arg)
7303 (cond
7304 ((org-at-heading-p) (org-do-demote))
7305 ((org-at-item-p) (org-indent-item))))
7307 (defun org-insert-todo-subheading (arg)
7308 "Insert a new subheading with TODO keyword or checkbox and demote it.
7309 Works for outline headings and for plain lists alike."
7310 (interactive "P")
7311 (org-insert-todo-heading arg)
7312 (cond
7313 ((org-at-heading-p) (org-do-demote))
7314 ((org-at-item-p) (org-indent-item))))
7316 ;;; Promotion and Demotion
7318 (defvar org-after-demote-entry-hook nil
7319 "Hook run after an entry has been demoted.
7320 The cursor will be at the beginning of the entry.
7321 When a subtree is being demoted, the hook will be called for each node.")
7323 (defvar org-after-promote-entry-hook nil
7324 "Hook run after an entry has been promoted.
7325 The cursor will be at the beginning of the entry.
7326 When a subtree is being promoted, the hook will be called for each node.")
7328 (defun org-promote-subtree ()
7329 "Promote the entire subtree.
7330 See also `org-promote'."
7331 (interactive)
7332 (save-excursion
7333 (org-with-limited-levels (org-map-tree 'org-promote)))
7334 (org-fix-position-after-promote))
7336 (defun org-demote-subtree ()
7337 "Demote the entire subtree. See `org-demote'.
7338 See also `org-promote'."
7339 (interactive)
7340 (save-excursion
7341 (org-with-limited-levels (org-map-tree 'org-demote)))
7342 (org-fix-position-after-promote))
7345 (defun org-do-promote ()
7346 "Promote the current heading higher up the tree.
7347 If the region is active in `transient-mark-mode', promote all headings
7348 in the region."
7349 (interactive)
7350 (save-excursion
7351 (if (org-region-active-p)
7352 (org-map-region 'org-promote (region-beginning) (region-end))
7353 (org-promote)))
7354 (org-fix-position-after-promote))
7356 (defun org-do-demote ()
7357 "Demote the current heading lower down the tree.
7358 If the region is active in `transient-mark-mode', demote all headings
7359 in the region."
7360 (interactive)
7361 (save-excursion
7362 (if (org-region-active-p)
7363 (org-map-region 'org-demote (region-beginning) (region-end))
7364 (org-demote)))
7365 (org-fix-position-after-promote))
7367 (defun org-fix-position-after-promote ()
7368 "Make sure that after pro/demotion cursor position is right."
7369 (let ((pos (point)))
7370 (when (save-excursion
7371 (beginning-of-line 1)
7372 (looking-at org-todo-line-regexp)
7373 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7374 (cond ((eobp) (insert " "))
7375 ((eolp) (insert " "))
7376 ((equal (char-after) ?\ ) (forward-char 1))))))
7378 (defun org-current-level ()
7379 "Return the level of the current entry, or nil if before the first headline.
7380 The level is the number of stars at the beginning of the headline."
7381 (save-excursion
7382 (org-with-limited-levels
7383 (if (ignore-errors (org-back-to-heading t))
7384 (funcall outline-level)))))
7386 (defun org-get-previous-line-level ()
7387 "Return the outline depth of the last headline before the current line.
7388 Returns 0 for the first headline in the buffer, and nil if before the
7389 first headline."
7390 (let ((current-level (org-current-level))
7391 (prev-level (when (> (line-number-at-pos) 1)
7392 (save-excursion
7393 (beginning-of-line 0)
7394 (org-current-level)))))
7395 (cond ((null current-level) nil) ; Before first headline
7396 ((null prev-level) 0) ; At first headline
7397 (prev-level))))
7399 (defun org-reduced-level (l)
7400 "Compute the effective level of a heading.
7401 This takes into account the setting of `org-odd-levels-only'."
7402 (cond
7403 ((zerop l) 0)
7404 (org-odd-levels-only (1+ (floor (/ l 2))))
7405 (t l)))
7407 (defun org-level-increment ()
7408 "Return the number of stars that will be added or removed at a
7409 time to headlines when structure editing, based on the value of
7410 `org-odd-levels-only'."
7411 (if org-odd-levels-only 2 1))
7413 (defun org-get-valid-level (level &optional change)
7414 "Rectify a level change under the influence of `org-odd-levels-only'
7415 LEVEL is a current level, CHANGE is by how much the level should be
7416 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7417 even level numbers will become the next higher odd number."
7418 (if org-odd-levels-only
7419 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7420 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7421 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7422 (max 1 (+ level (or change 0)))))
7424 (if (boundp 'define-obsolete-function-alias)
7425 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7426 (define-obsolete-function-alias 'org-get-legal-level
7427 'org-get-valid-level)
7428 (define-obsolete-function-alias 'org-get-legal-level
7429 'org-get-valid-level "23.1")))
7431 (defun org-promote ()
7432 "Promote the current heading higher up the tree.
7433 If the region is active in `transient-mark-mode', promote all headings
7434 in the region."
7435 (org-back-to-heading t)
7436 (let* ((level (save-match-data (funcall outline-level)))
7437 (after-change-functions (remove 'flyspell-after-change-function
7438 after-change-functions))
7439 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7440 (diff (abs (- level (length up-head) -1))))
7441 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7442 (replace-match up-head nil t)
7443 ;; Fixup tag positioning
7444 (and org-auto-align-tags (org-set-tags nil t))
7445 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7446 (run-hooks 'org-after-promote-entry-hook)))
7448 (defun org-demote ()
7449 "Demote the current heading lower down the tree.
7450 If the region is active in `transient-mark-mode', demote all headings
7451 in the region."
7452 (org-back-to-heading t)
7453 (let* ((level (save-match-data (funcall outline-level)))
7454 (after-change-functions (remove 'flyspell-after-change-function
7455 after-change-functions))
7456 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7457 (diff (abs (- level (length down-head) -1))))
7458 (replace-match down-head nil t)
7459 ;; Fixup tag positioning
7460 (and org-auto-align-tags (org-set-tags nil t))
7461 (if org-adapt-indentation (org-fixup-indentation diff))
7462 (run-hooks 'org-after-demote-entry-hook)))
7464 (defun org-cycle-level ()
7465 "Cycle the level of an empty headline through possible states.
7466 This goes first to child, then to parent, level, then up the hierarchy.
7467 After top level, it switches back to sibling level."
7468 (interactive)
7469 (let ((org-adapt-indentation nil))
7470 (when (org-point-at-end-of-empty-headline)
7471 (setq this-command 'org-cycle-level) ; Only needed for caching
7472 (let ((cur-level (org-current-level))
7473 (prev-level (org-get-previous-line-level)))
7474 (cond
7475 ;; If first headline in file, promote to top-level.
7476 ((= prev-level 0)
7477 (loop repeat (/ (- cur-level 1) (org-level-increment))
7478 do (org-do-promote)))
7479 ;; If same level as prev, demote one.
7480 ((= prev-level cur-level)
7481 (org-do-demote))
7482 ;; If parent is top-level, promote to top level if not already.
7483 ((= prev-level 1)
7484 (loop repeat (/ (- cur-level 1) (org-level-increment))
7485 do (org-do-promote)))
7486 ;; If top-level, return to prev-level.
7487 ((= cur-level 1)
7488 (loop repeat (/ (- prev-level 1) (org-level-increment))
7489 do (org-do-demote)))
7490 ;; If less than prev-level, promote one.
7491 ((< cur-level prev-level)
7492 (org-do-promote))
7493 ;; If deeper than prev-level, promote until higher than
7494 ;; prev-level.
7495 ((> cur-level prev-level)
7496 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7497 do (org-do-promote))))
7498 t))))
7500 (defun org-map-tree (fun)
7501 "Call FUN for every heading underneath the current one."
7502 (org-back-to-heading)
7503 (let ((level (funcall outline-level)))
7504 (save-excursion
7505 (funcall fun)
7506 (while (and (progn
7507 (outline-next-heading)
7508 (> (funcall outline-level) level))
7509 (not (eobp)))
7510 (funcall fun)))))
7512 (defun org-map-region (fun beg end)
7513 "Call FUN for every heading between BEG and END."
7514 (let ((org-ignore-region t))
7515 (save-excursion
7516 (setq end (copy-marker end))
7517 (goto-char beg)
7518 (if (and (re-search-forward org-outline-regexp-bol nil t)
7519 (< (point) end))
7520 (funcall fun))
7521 (while (and (progn
7522 (outline-next-heading)
7523 (< (point) end))
7524 (not (eobp)))
7525 (funcall fun)))))
7527 (defvar org-property-end-re) ; silence byte-compiler
7528 (defun org-fixup-indentation (diff)
7529 "Change the indentation in the current entry by DIFF.
7530 However, if any line in the current entry has no indentation, or if it
7531 would end up with no indentation after the change, nothing at all is done."
7532 (save-excursion
7533 (let ((end (save-excursion (outline-next-heading)
7534 (point-marker)))
7535 (prohibit (if (> diff 0)
7536 "^\\S-"
7537 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7538 col)
7539 (unless (save-excursion (end-of-line 1)
7540 (re-search-forward prohibit end t))
7541 (while (and (< (point) end)
7542 (re-search-forward "^[ \t]+" end t))
7543 (goto-char (match-end 0))
7544 (setq col (current-column))
7545 (if (< diff 0) (replace-match ""))
7546 (org-indent-to-column (+ diff col))))
7547 (move-marker end nil))))
7549 (defun org-convert-to-odd-levels ()
7550 "Convert an org-mode file with all levels allowed to one with odd levels.
7551 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7552 level 5 etc."
7553 (interactive)
7554 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7555 (let ((outline-level 'org-outline-level)
7556 (org-odd-levels-only nil) n)
7557 (save-excursion
7558 (goto-char (point-min))
7559 (while (re-search-forward "^\\*\\*+ " nil t)
7560 (setq n (- (length (match-string 0)) 2))
7561 (while (>= (setq n (1- n)) 0)
7562 (org-demote))
7563 (end-of-line 1))))))
7565 (defun org-convert-to-oddeven-levels ()
7566 "Convert an org-mode file with only odd levels to one with odd/even levels.
7567 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7568 file contains a section with an even level, conversion would
7569 destroy the structure of the file. An error is signaled in this
7570 case."
7571 (interactive)
7572 (goto-char (point-min))
7573 ;; First check if there are no even levels
7574 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7575 (org-show-context t)
7576 (error "Not all levels are odd in this file. Conversion not possible"))
7577 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7578 (let ((outline-regexp org-outline-regexp)
7579 (outline-level 'org-outline-level)
7580 (org-odd-levels-only nil) n)
7581 (save-excursion
7582 (goto-char (point-min))
7583 (while (re-search-forward "^\\*\\*+ " nil t)
7584 (setq n (/ (1- (length (match-string 0))) 2))
7585 (while (>= (setq n (1- n)) 0)
7586 (org-promote))
7587 (end-of-line 1))))))
7589 (defun org-tr-level (n)
7590 "Make N odd if required."
7591 (if org-odd-levels-only (1+ (/ n 2)) n))
7593 ;;; Vertical tree motion, cutting and pasting of subtrees
7595 (defun org-move-subtree-up (&optional arg)
7596 "Move the current subtree up past ARG headlines of the same level."
7597 (interactive "p")
7598 (org-move-subtree-down (- (prefix-numeric-value arg))))
7600 (defun org-move-subtree-down (&optional arg)
7601 "Move the current subtree down past ARG headlines of the same level."
7602 (interactive "p")
7603 (setq arg (prefix-numeric-value arg))
7604 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7605 'org-get-last-sibling))
7606 (ins-point (make-marker))
7607 (cnt (abs arg))
7608 (col (current-column))
7609 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7610 ;; Select the tree
7611 (org-back-to-heading)
7612 (setq beg0 (point))
7613 (save-excursion
7614 (setq ne-beg (org-back-over-empty-lines))
7615 (setq beg (point)))
7616 (save-match-data
7617 (save-excursion (outline-end-of-heading)
7618 (setq folded (outline-invisible-p)))
7619 (outline-end-of-subtree))
7620 (outline-next-heading)
7621 (setq ne-end (org-back-over-empty-lines))
7622 (setq end (point))
7623 (goto-char beg0)
7624 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7625 ;; include less whitespace
7626 (save-excursion
7627 (goto-char beg)
7628 (forward-line (- ne-beg ne-end))
7629 (setq beg (point))))
7630 ;; Find insertion point, with error handling
7631 (while (> cnt 0)
7632 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7633 (progn (goto-char beg0)
7634 (error "Cannot move past superior level or buffer limit")))
7635 (setq cnt (1- cnt)))
7636 (if (> arg 0)
7637 ;; Moving forward - still need to move over subtree
7638 (progn (org-end-of-subtree t t)
7639 (save-excursion
7640 (org-back-over-empty-lines)
7641 (or (bolp) (newline)))))
7642 (setq ne-ins (org-back-over-empty-lines))
7643 (move-marker ins-point (point))
7644 (setq txt (buffer-substring beg end))
7645 (org-save-markers-in-region beg end)
7646 (delete-region beg end)
7647 (org-remove-empty-overlays-at beg)
7648 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7649 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7650 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7651 (let ((bbb (point)))
7652 (insert-before-markers txt)
7653 (org-reinstall-markers-in-region bbb)
7654 (move-marker ins-point bbb))
7655 (or (bolp) (insert "\n"))
7656 (setq ins-end (point))
7657 (goto-char ins-point)
7658 (org-skip-whitespace)
7659 (when (and (< arg 0)
7660 (org-first-sibling-p)
7661 (> ne-ins ne-beg))
7662 ;; Move whitespace back to beginning
7663 (save-excursion
7664 (goto-char ins-end)
7665 (let ((kill-whole-line t))
7666 (kill-line (- ne-ins ne-beg)) (point)))
7667 (insert (make-string (- ne-ins ne-beg) ?\n)))
7668 (move-marker ins-point nil)
7669 (if folded
7670 (hide-subtree)
7671 (org-show-entry)
7672 (show-children)
7673 (org-cycle-hide-drawers 'children))
7674 (org-clean-visibility-after-subtree-move)
7675 ;; move back to the initial column we were at
7676 (move-to-column col)))
7678 (defvar org-subtree-clip ""
7679 "Clipboard for cut and paste of subtrees.
7680 This is actually only a copy of the kill, because we use the normal kill
7681 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7683 (defvar org-subtree-clip-folded nil
7684 "Was the last copied subtree folded?
7685 This is used to fold the tree back after pasting.")
7687 (defun org-cut-subtree (&optional n)
7688 "Cut the current subtree into the clipboard.
7689 With prefix arg N, cut this many sequential subtrees.
7690 This is a short-hand for marking the subtree and then cutting it."
7691 (interactive "p")
7692 (org-copy-subtree n 'cut))
7694 (defun org-copy-subtree (&optional n cut force-store-markers)
7695 "Cut the current subtree into the clipboard.
7696 With prefix arg N, cut this many sequential subtrees.
7697 This is a short-hand for marking the subtree and then copying it.
7698 If CUT is non-nil, actually cut the subtree.
7699 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7700 of some markers in the region, even if CUT is non-nil. This is
7701 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7702 (interactive "p")
7703 (let (beg end folded (beg0 (point)))
7704 (if (org-called-interactively-p 'any)
7705 (org-back-to-heading nil) ; take what looks like a subtree
7706 (org-back-to-heading t)) ; take what is really there
7707 (org-back-over-empty-lines)
7708 (setq beg (point))
7709 (skip-chars-forward " \t\r\n")
7710 (save-match-data
7711 (save-excursion (outline-end-of-heading)
7712 (setq folded (outline-invisible-p)))
7713 (condition-case nil
7714 (org-forward-same-level (1- n) t)
7715 (error nil))
7716 (org-end-of-subtree t t))
7717 (org-back-over-empty-lines)
7718 (setq end (point))
7719 (goto-char beg0)
7720 (when (> end beg)
7721 (setq org-subtree-clip-folded folded)
7722 (when (or cut force-store-markers)
7723 (org-save-markers-in-region beg end))
7724 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7725 (setq org-subtree-clip (current-kill 0))
7726 (message "%s: Subtree(s) with %d characters"
7727 (if cut "Cut" "Copied")
7728 (length org-subtree-clip)))))
7730 (defun org-paste-subtree (&optional level tree for-yank)
7731 "Paste the clipboard as a subtree, with modification of headline level.
7732 The entire subtree is promoted or demoted in order to match a new headline
7733 level.
7735 If the cursor is at the beginning of a headline, the same level as
7736 that headline is used to paste the tree
7738 If not, the new level is derived from the *visible* headings
7739 before and after the insertion point, and taken to be the inferior headline
7740 level of the two. So if the previous visible heading is level 3 and the
7741 next is level 4 (or vice versa), level 4 will be used for insertion.
7742 This makes sure that the subtree remains an independent subtree and does
7743 not swallow low level entries.
7745 You can also force a different level, either by using a numeric prefix
7746 argument, or by inserting the heading marker by hand. For example, if the
7747 cursor is after \"*****\", then the tree will be shifted to level 5.
7749 If optional TREE is given, use this text instead of the kill ring.
7751 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7752 move back over whitespace before inserting, and move point to the end of
7753 the inserted text when done."
7754 (interactive "P")
7755 (setq tree (or tree (and kill-ring (current-kill 0))))
7756 (unless (org-kill-is-subtree-p tree)
7757 (error "%s"
7758 (substitute-command-keys
7759 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7760 (org-with-limited-levels
7761 (let* ((visp (not (outline-invisible-p)))
7762 (txt tree)
7763 (^re_ "\\(\\*+\\)[ \t]*")
7764 (old-level (if (string-match org-outline-regexp-bol txt)
7765 (- (match-end 0) (match-beginning 0) 1)
7766 -1))
7767 (force-level (cond (level (prefix-numeric-value level))
7768 ((and (looking-at "[ \t]*$")
7769 (string-match
7770 "^\\*+$" (buffer-substring
7771 (point-at-bol) (point))))
7772 (- (match-end 1) (match-beginning 1)))
7773 ((and (bolp)
7774 (looking-at org-outline-regexp))
7775 (- (match-end 0) (point) 1))
7776 (t nil)))
7777 (previous-level (save-excursion
7778 (condition-case nil
7779 (progn
7780 (outline-previous-visible-heading 1)
7781 (if (looking-at ^re_)
7782 (- (match-end 0) (match-beginning 0) 1)
7784 (error 1))))
7785 (next-level (save-excursion
7786 (condition-case nil
7787 (progn
7788 (or (looking-at org-outline-regexp)
7789 (outline-next-visible-heading 1))
7790 (if (looking-at ^re_)
7791 (- (match-end 0) (match-beginning 0) 1)
7793 (error 1))))
7794 (new-level (or force-level (max previous-level next-level)))
7795 (shift (if (or (= old-level -1)
7796 (= new-level -1)
7797 (= old-level new-level))
7799 (- new-level old-level)))
7800 (delta (if (> shift 0) -1 1))
7801 (func (if (> shift 0) 'org-demote 'org-promote))
7802 (org-odd-levels-only nil)
7803 beg end newend)
7804 ;; Remove the forced level indicator
7805 (if force-level
7806 (delete-region (point-at-bol) (point)))
7807 ;; Paste
7808 (beginning-of-line (if (bolp) 1 2))
7809 (unless for-yank (org-back-over-empty-lines))
7810 (setq beg (point))
7811 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7812 (insert-before-markers txt)
7813 (unless (string-match "\n\\'" txt) (insert "\n"))
7814 (setq newend (point))
7815 (org-reinstall-markers-in-region beg)
7816 (setq end (point))
7817 (goto-char beg)
7818 (skip-chars-forward " \t\n\r")
7819 (setq beg (point))
7820 (if (and (outline-invisible-p) visp)
7821 (save-excursion (outline-show-heading)))
7822 ;; Shift if necessary
7823 (unless (= shift 0)
7824 (save-restriction
7825 (narrow-to-region beg end)
7826 (while (not (= shift 0))
7827 (org-map-region func (point-min) (point-max))
7828 (setq shift (+ delta shift)))
7829 (goto-char (point-min))
7830 (setq newend (point-max))))
7831 (when (or (org-called-interactively-p 'interactive) for-yank)
7832 (message "Clipboard pasted as level %d subtree" new-level))
7833 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7834 kill-ring
7835 (eq org-subtree-clip (current-kill 0))
7836 org-subtree-clip-folded)
7837 ;; The tree was folded before it was killed/copied
7838 (hide-subtree))
7839 (and for-yank (goto-char newend)))))
7841 (defun org-kill-is-subtree-p (&optional txt)
7842 "Check if the current kill is an outline subtree, or a set of trees.
7843 Returns nil if kill does not start with a headline, or if the first
7844 headline level is not the largest headline level in the tree.
7845 So this will actually accept several entries of equal levels as well,
7846 which is OK for `org-paste-subtree'.
7847 If optional TXT is given, check this string instead of the current kill."
7848 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7849 (re (org-get-limited-outline-regexp))
7850 (^re (concat "^" re))
7851 (start-level (and kill
7852 (string-match
7853 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7854 kill)
7855 (- (match-end 2) (match-beginning 2) 1)))
7856 (start (1+ (or (match-beginning 2) -1))))
7857 (if (not start-level)
7858 (progn
7859 nil) ;; does not even start with a heading
7860 (catch 'exit
7861 (while (setq start (string-match ^re kill (1+ start)))
7862 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7863 (throw 'exit nil)))
7864 t))))
7866 (defvar org-markers-to-move nil
7867 "Markers that should be moved with a cut-and-paste operation.
7868 Those markers are stored together with their positions relative to
7869 the start of the region.")
7871 (defun org-save-markers-in-region (beg end)
7872 "Check markers in region.
7873 If these markers are between BEG and END, record their position relative
7874 to BEG, so that after moving the block of text, we can put the markers back
7875 into place.
7876 This function gets called just before an entry or tree gets cut from the
7877 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7878 called immediately, to move the markers with the entries."
7879 (setq org-markers-to-move nil)
7880 (when (featurep 'org-clock)
7881 (org-clock-save-markers-for-cut-and-paste beg end))
7882 (when (featurep 'org-agenda)
7883 (org-agenda-save-markers-for-cut-and-paste beg end)))
7885 (defun org-check-and-save-marker (marker beg end)
7886 "Check if MARKER is between BEG and END.
7887 If yes, remember the marker and the distance to BEG."
7888 (when (and (marker-buffer marker)
7889 (equal (marker-buffer marker) (current-buffer)))
7890 (if (and (>= marker beg) (< marker end))
7891 (push (cons marker (- marker beg)) org-markers-to-move))))
7893 (defun org-reinstall-markers-in-region (beg)
7894 "Move all remembered markers to their position relative to BEG."
7895 (mapc (lambda (x)
7896 (move-marker (car x) (+ beg (cdr x))))
7897 org-markers-to-move)
7898 (setq org-markers-to-move nil))
7900 (defun org-narrow-to-subtree ()
7901 "Narrow buffer to the current subtree."
7902 (interactive)
7903 (save-excursion
7904 (save-match-data
7905 (org-with-limited-levels
7906 (narrow-to-region
7907 (progn (org-back-to-heading t) (point))
7908 (progn (org-end-of-subtree t t)
7909 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7910 (point)))))))
7912 (defun org-narrow-to-block ()
7913 "Narrow buffer to the current block."
7914 (interactive)
7915 (let* ((case-fold-search t)
7916 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7917 "^[ \t]*#\\+end_.*")))
7918 (if blockp
7919 (narrow-to-region (car blockp) (cdr blockp))
7920 (error "Not in a block"))))
7922 (eval-when-compile
7923 (defvar org-property-drawer-re))
7925 (defvar org-property-start-re) ;; defined below
7926 (defun org-clone-subtree-with-time-shift (n &optional shift)
7927 "Clone the task (subtree) at point N times.
7928 The clones will be inserted as siblings.
7930 In interactive use, the user will be prompted for the number of
7931 clones to be produced, and for a time SHIFT, which may be a
7932 repeater as used in time stamps, for example `+3d'.
7934 When a valid repeater is given and the entry contains any time
7935 stamps, the clones will become a sequence in time, with time
7936 stamps in the subtree shifted for each clone produced. If SHIFT
7937 is nil or the empty string, time stamps will be left alone. The
7938 ID property of the original subtree is removed.
7940 If the original subtree did contain time stamps with a repeater,
7941 the following will happen:
7942 - the repeater will be removed in each clone
7943 - an additional clone will be produced, with the current, unshifted
7944 date(s) in the entry.
7945 - the original entry will be placed *after* all the clones, with
7946 repeater intact.
7947 - the start days in the repeater in the original entry will be shifted
7948 to past the last clone.
7949 In this way you can spell out a number of instances of a repeating task,
7950 and still retain the repeater to cover future instances of the task."
7951 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7952 (let (beg end template task idprop
7953 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7954 (drawer-re org-drawer-regexp))
7955 (if (not (and (integerp n) (> n 0)))
7956 (error "Invalid number of replications %s" n))
7957 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7958 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7959 shift)))
7960 (error "Invalid shift specification %s" shift))
7961 (when doshift
7962 (setq shift-n (string-to-number (match-string 1 shift))
7963 shift-what (cdr (assoc (match-string 2 shift)
7964 '(("d" . day) ("w" . week)
7965 ("m" . month) ("y" . year))))))
7966 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7967 (setq nmin 1 nmax n)
7968 (org-back-to-heading t)
7969 (setq beg (point))
7970 (setq idprop (org-entry-get nil "ID"))
7971 (org-end-of-subtree t t)
7972 (or (bolp) (insert "\n"))
7973 (setq end (point))
7974 (setq template (buffer-substring beg end))
7975 (when (and doshift
7976 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7977 (delete-region beg end)
7978 (setq end beg)
7979 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7980 (goto-char end)
7981 (loop for n from nmin to nmax do
7982 ;; prepare clone
7983 (with-temp-buffer
7984 (insert template)
7985 (org-mode)
7986 (goto-char (point-min))
7987 (org-show-subtree)
7988 (and idprop (if org-clone-delete-id
7989 (org-entry-delete nil "ID")
7990 (org-id-get-create t)))
7991 (unless (= n 0)
7992 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7993 (kill-whole-line))
7994 (goto-char (point-min))
7995 (while (re-search-forward drawer-re nil t)
7996 (mapc (lambda (d)
7997 (org-remove-empty-drawer-at d (point))) org-drawers)))
7998 (goto-char (point-min))
7999 (when doshift
8000 (while (re-search-forward org-ts-regexp-both nil t)
8001 (org-timestamp-change (* n shift-n) shift-what))
8002 (unless (= n n-no-remove)
8003 (goto-char (point-min))
8004 (while (re-search-forward org-ts-regexp nil t)
8005 (save-excursion
8006 (goto-char (match-beginning 0))
8007 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8008 (delete-region (match-beginning 1) (match-end 1)))))))
8009 (setq task (buffer-string)))
8010 (insert task))
8011 (goto-char beg)))
8013 ;;; Outline Sorting
8015 (defun org-sort (with-case)
8016 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8017 Optional argument WITH-CASE means sort case-sensitively."
8018 (interactive "P")
8019 (cond
8020 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8021 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8023 (org-call-with-arg 'org-sort-entries with-case))))
8025 (defun org-sort-remove-invisible (s)
8026 (remove-text-properties 0 (length s) org-rm-props s)
8027 (while (string-match org-bracket-link-regexp s)
8028 (setq s (replace-match (if (match-end 2)
8029 (match-string 3 s)
8030 (match-string 1 s)) t t s)))
8033 (defvar org-priority-regexp) ; defined later in the file
8035 (defvar org-after-sorting-entries-or-items-hook nil
8036 "Hook that is run after a bunch of entries or items have been sorted.
8037 When children are sorted, the cursor is in the parent line when this
8038 hook gets called. When a region or a plain list is sorted, the cursor
8039 will be in the first entry of the sorted region/list.")
8041 (defun org-sort-entries
8042 (&optional with-case sorting-type getkey-func compare-func property)
8043 "Sort entries on a certain level of an outline tree.
8044 If there is an active region, the entries in the region are sorted.
8045 Else, if the cursor is before the first entry, sort the top-level items.
8046 Else, the children of the entry at point are sorted.
8048 Sorting can be alphabetically, numerically, by date/time as given by
8049 a time stamp, by a property or by priority.
8051 The command prompts for the sorting type unless it has been given to the
8052 function through the SORTING-TYPE argument, which needs to be a character,
8053 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8054 precise meaning of each character:
8056 n Numerically, by converting the beginning of the entry/item to a number.
8057 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8058 t By date/time, either the first active time stamp in the entry, or, if
8059 none exist, by the first inactive one.
8060 s By the scheduled date/time.
8061 d By deadline date/time.
8062 c By creation time, which is assumed to be the first inactive time stamp
8063 at the beginning of a line.
8064 p By priority according to the cookie.
8065 r By the value of a property.
8067 Capital letters will reverse the sort order.
8069 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8070 called with point at the beginning of the record. It must return either
8071 a string or a number that should serve as the sorting key for that record.
8073 Comparing entries ignores case by default. However, with an optional argument
8074 WITH-CASE, the sorting considers case as well."
8075 (interactive "P")
8076 (let ((case-func (if with-case 'identity 'downcase))
8077 start beg end stars re re2
8078 txt what tmp)
8079 ;; Find beginning and end of region to sort
8080 (cond
8081 ((org-region-active-p)
8082 ;; we will sort the region
8083 (setq end (region-end)
8084 what "region")
8085 (goto-char (region-beginning))
8086 (if (not (org-at-heading-p)) (outline-next-heading))
8087 (setq start (point)))
8088 ((or (org-at-heading-p)
8089 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8090 ;; we will sort the children of the current headline
8091 (org-back-to-heading)
8092 (setq start (point)
8093 end (progn (org-end-of-subtree t t)
8094 (or (bolp) (insert "\n"))
8095 (org-back-over-empty-lines)
8096 (point))
8097 what "children")
8098 (goto-char start)
8099 (show-subtree)
8100 (outline-next-heading))
8102 ;; we will sort the top-level entries in this file
8103 (goto-char (point-min))
8104 (or (org-at-heading-p) (outline-next-heading))
8105 (setq start (point))
8106 (goto-char (point-max))
8107 (beginning-of-line 1)
8108 (when (looking-at ".*?\\S-")
8109 ;; File ends in a non-white line
8110 (end-of-line 1)
8111 (insert "\n"))
8112 (setq end (point-max))
8113 (setq what "top-level")
8114 (goto-char start)
8115 (show-all)))
8117 (setq beg (point))
8118 (if (>= beg end) (error "Nothing to sort"))
8120 (looking-at "\\(\\*+\\)")
8121 (setq stars (match-string 1)
8122 re (concat "^" (regexp-quote stars) " +")
8123 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8124 txt (buffer-substring beg end))
8125 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8126 (if (and (not (equal stars "*")) (string-match re2 txt))
8127 (error "Region to sort contains a level above the first entry"))
8129 (unless sorting-type
8130 (message
8131 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8132 [t]ime [s]cheduled [d]eadline [c]reated
8133 A/N/T/S/D/C/P/O/F means reversed:"
8134 what)
8135 (setq sorting-type (read-char-exclusive))
8137 (and (= (downcase sorting-type) ?f)
8138 (setq getkey-func
8139 (org-icompleting-read "Sort using function: "
8140 obarray 'fboundp t nil nil))
8141 (setq getkey-func (intern getkey-func)))
8143 (and (= (downcase sorting-type) ?r)
8144 (setq property
8145 (org-icompleting-read "Property: "
8146 (mapcar 'list (org-buffer-property-keys t))
8147 nil t))))
8149 (message "Sorting entries...")
8151 (save-restriction
8152 (narrow-to-region start end)
8153 (let ((dcst (downcase sorting-type))
8154 (case-fold-search nil)
8155 (now (current-time)))
8156 (sort-subr
8157 (/= dcst sorting-type)
8158 ;; This function moves to the beginning character of the "record" to
8159 ;; be sorted.
8160 (lambda nil
8161 (if (re-search-forward re nil t)
8162 (goto-char (match-beginning 0))
8163 (goto-char (point-max))))
8164 ;; This function moves to the last character of the "record" being
8165 ;; sorted.
8166 (lambda nil
8167 (save-match-data
8168 (condition-case nil
8169 (outline-forward-same-level 1)
8170 (error
8171 (goto-char (point-max))))))
8172 ;; This function returns the value that gets sorted against.
8173 (lambda nil
8174 (cond
8175 ((= dcst ?n)
8176 (if (looking-at org-complex-heading-regexp)
8177 (string-to-number (match-string 4))
8178 nil))
8179 ((= dcst ?a)
8180 (if (looking-at org-complex-heading-regexp)
8181 (funcall case-func (match-string 4))
8182 nil))
8183 ((= dcst ?t)
8184 (let ((end (save-excursion (outline-next-heading) (point))))
8185 (if (or (re-search-forward org-ts-regexp end t)
8186 (re-search-forward org-ts-regexp-both end t))
8187 (org-time-string-to-seconds (match-string 0))
8188 (org-float-time now))))
8189 ((= dcst ?c)
8190 (let ((end (save-excursion (outline-next-heading) (point))))
8191 (if (re-search-forward
8192 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8193 end t)
8194 (org-time-string-to-seconds (match-string 0))
8195 (org-float-time now))))
8196 ((= dcst ?s)
8197 (let ((end (save-excursion (outline-next-heading) (point))))
8198 (if (re-search-forward org-scheduled-time-regexp end t)
8199 (org-time-string-to-seconds (match-string 1))
8200 (org-float-time now))))
8201 ((= dcst ?d)
8202 (let ((end (save-excursion (outline-next-heading) (point))))
8203 (if (re-search-forward org-deadline-time-regexp end t)
8204 (org-time-string-to-seconds (match-string 1))
8205 (org-float-time now))))
8206 ((= dcst ?p)
8207 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8208 (string-to-char (match-string 2))
8209 org-default-priority))
8210 ((= dcst ?r)
8211 (or (org-entry-get nil property) ""))
8212 ((= dcst ?o)
8213 (if (looking-at org-complex-heading-regexp)
8214 (- 9999 (length (member (match-string 2)
8215 org-todo-keywords-1)))))
8216 ((= dcst ?f)
8217 (if getkey-func
8218 (progn
8219 (setq tmp (funcall getkey-func))
8220 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8221 tmp)
8222 (error "Invalid key function `%s'" getkey-func)))
8223 (t (error "Invalid sorting type `%c'" sorting-type))))
8225 (cond
8226 ((= dcst ?a) 'string<)
8227 ((= dcst ?f) compare-func)
8228 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8229 (t nil)))))
8230 (run-hooks 'org-after-sorting-entries-or-items-hook)
8231 (message "Sorting entries...done")))
8233 (defun org-do-sort (table what &optional with-case sorting-type)
8234 "Sort TABLE of WHAT according to SORTING-TYPE.
8235 The user will be prompted for the SORTING-TYPE if the call to this
8236 function does not specify it. WHAT is only for the prompt, to indicate
8237 what is being sorted. The sorting key will be extracted from
8238 the car of the elements of the table.
8239 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8240 (unless sorting-type
8241 (message
8242 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8243 what)
8244 (setq sorting-type (read-char-exclusive)))
8245 (let ((dcst (downcase sorting-type))
8246 extractfun comparefun)
8247 ;; Define the appropriate functions
8248 (cond
8249 ((= dcst ?n)
8250 (setq extractfun 'string-to-number
8251 comparefun (if (= dcst sorting-type) '< '>)))
8252 ((= dcst ?a)
8253 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8254 (lambda(x) (downcase (org-sort-remove-invisible x))))
8255 comparefun (if (= dcst sorting-type)
8256 'string<
8257 (lambda (a b) (and (not (string< a b))
8258 (not (string= a b)))))))
8259 ((= dcst ?t)
8260 (setq extractfun
8261 (lambda (x)
8262 (if (or (string-match org-ts-regexp x)
8263 (string-match org-ts-regexp-both x))
8264 (org-float-time
8265 (org-time-string-to-time (match-string 0 x)))
8267 comparefun (if (= dcst sorting-type) '< '>)))
8268 (t (error "Invalid sorting type `%c'" sorting-type)))
8270 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8271 table)
8272 (lambda (a b) (funcall comparefun (car a) (car b))))))
8275 ;;; The orgstruct minor mode
8277 ;; Define a minor mode which can be used in other modes in order to
8278 ;; integrate the org-mode structure editing commands.
8280 ;; This is really a hack, because the org-mode structure commands use
8281 ;; keys which normally belong to the major mode. Here is how it
8282 ;; works: The minor mode defines all the keys necessary to operate the
8283 ;; structure commands, but wraps the commands into a function which
8284 ;; tests if the cursor is currently at a headline or a plain list
8285 ;; item. If that is the case, the structure command is used,
8286 ;; temporarily setting many Org-mode variables like regular
8287 ;; expressions for filling etc. However, when any of those keys is
8288 ;; used at a different location, function uses `key-binding' to look
8289 ;; up if the key has an associated command in another currently active
8290 ;; keymap (minor modes, major mode, global), and executes that
8291 ;; command. There might be problems if any of the keys is otherwise
8292 ;; used as a prefix key.
8294 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8295 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8296 ;; addresses this by checking explicitly for both bindings.
8298 (defvar orgstruct-mode-map (make-sparse-keymap)
8299 "Keymap for the minor `orgstruct-mode'.")
8301 (defvar org-local-vars nil
8302 "List of local variables, for use by `orgstruct-mode'.")
8304 ;;;###autoload
8305 (define-minor-mode orgstruct-mode
8306 "Toggle the minor mode `orgstruct-mode'.
8307 This mode is for using Org-mode structure commands in other
8308 modes. The following keys behave as if Org-mode were active, if
8309 the cursor is on a headline, or on a plain list item (both as
8310 defined by Org-mode).
8312 M-up Move entry/item up
8313 M-down Move entry/item down
8314 M-left Promote
8315 M-right Demote
8316 M-S-up Move entry/item up
8317 M-S-down Move entry/item down
8318 M-S-left Promote subtree
8319 M-S-right Demote subtree
8320 M-q Fill paragraph and items like in Org-mode
8321 C-c ^ Sort entries
8322 C-c - Cycle list bullet
8323 TAB Cycle item visibility
8324 M-RET Insert new heading/item
8325 S-M-RET Insert new TODO heading / Checkbox item
8326 C-c C-c Set tags / toggle checkbox"
8327 nil " OrgStruct" nil
8328 (org-load-modules-maybe)
8329 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8331 ;;;###autoload
8332 (defun turn-on-orgstruct ()
8333 "Unconditionally turn on `orgstruct-mode'."
8334 (orgstruct-mode 1))
8336 (defun orgstruct++-mode (&optional arg)
8337 "Toggle `orgstruct-mode', the enhanced version of it.
8338 In addition to setting orgstruct-mode, this also exports all indentation
8339 and autofilling variables from org-mode into the buffer. It will also
8340 recognize item context in multiline items.
8341 Note that turning off orgstruct-mode will *not* remove the
8342 indentation/paragraph settings. This can only be done by refreshing the
8343 major mode, for example with \\[normal-mode]."
8344 (interactive "P")
8345 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8346 (if (< arg 1)
8347 (orgstruct-mode -1)
8348 (orgstruct-mode 1)
8349 (let (var val)
8350 (mapc
8351 (lambda (x)
8352 (when (string-match
8353 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8354 (symbol-name (car x)))
8355 (setq var (car x) val (nth 1 x))
8356 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8357 org-local-vars)
8358 (org-set-local 'orgstruct-is-++ t))))
8360 (defvar orgstruct-is-++ nil
8361 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8362 (make-variable-buffer-local 'orgstruct-is-++)
8364 ;;;###autoload
8365 (defun turn-on-orgstruct++ ()
8366 "Unconditionally turn on `orgstruct++-mode'."
8367 (orgstruct++-mode 1))
8369 (defun orgstruct-error ()
8370 "Error when there is no default binding for a structure key."
8371 (interactive)
8372 (error "This key has no function outside structure elements"))
8374 (defun orgstruct-setup ()
8375 "Setup orgstruct keymaps."
8376 (let ((nfunc 0)
8377 (bindings
8378 (list
8379 '([(meta up)] org-metaup)
8380 '([(meta down)] org-metadown)
8381 '([(meta left)] org-metaleft)
8382 '([(meta right)] org-metaright)
8383 '([(meta shift up)] org-shiftmetaup)
8384 '([(meta shift down)] org-shiftmetadown)
8385 '([(meta shift left)] org-shiftmetaleft)
8386 '([(meta shift right)] org-shiftmetaright)
8387 '([?\e (up)] org-metaup)
8388 '([?\e (down)] org-metadown)
8389 '([?\e (left)] org-metaleft)
8390 '([?\e (right)] org-metaright)
8391 '([?\e (shift up)] org-shiftmetaup)
8392 '([?\e (shift down)] org-shiftmetadown)
8393 '([?\e (shift left)] org-shiftmetaleft)
8394 '([?\e (shift right)] org-shiftmetaright)
8395 '([(shift up)] org-shiftup)
8396 '([(shift down)] org-shiftdown)
8397 '([(shift left)] org-shiftleft)
8398 '([(shift right)] org-shiftright)
8399 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8400 '("\M-q" fill-paragraph)
8401 '("\C-c^" org-sort)
8402 '("\C-c-" org-cycle-list-bullet)))
8403 elt key fun cmd)
8404 (while (setq elt (pop bindings))
8405 (setq nfunc (1+ nfunc))
8406 (setq key (org-key (car elt))
8407 fun (nth 1 elt)
8408 cmd (orgstruct-make-binding fun nfunc key))
8409 (org-defkey orgstruct-mode-map key cmd))
8411 ;; Special treatment needed for TAB and RET
8412 (org-defkey orgstruct-mode-map [(tab)]
8413 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8414 (org-defkey orgstruct-mode-map "\C-i"
8415 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8417 (org-defkey orgstruct-mode-map "\M-\C-m"
8418 (orgstruct-make-binding 'org-insert-heading 105
8419 "\M-\C-m" [(meta return)]))
8420 (org-defkey orgstruct-mode-map [(meta return)]
8421 (orgstruct-make-binding 'org-insert-heading 106
8422 [(meta return)] "\M-\C-m"))
8424 (org-defkey orgstruct-mode-map [(shift meta return)]
8425 (orgstruct-make-binding 'org-insert-todo-heading 107
8426 [(meta return)] "\M-\C-m"))
8428 (org-defkey orgstruct-mode-map "\e\C-m"
8429 (orgstruct-make-binding 'org-insert-heading 108
8430 "\e\C-m" [?\e (return)]))
8431 (org-defkey orgstruct-mode-map [?\e (return)]
8432 (orgstruct-make-binding 'org-insert-heading 109
8433 [?\e (return)] "\e\C-m"))
8434 (org-defkey orgstruct-mode-map [?\e (shift return)]
8435 (orgstruct-make-binding 'org-insert-todo-heading 110
8436 [?\e (return)] "\e\C-m"))
8438 (unless org-local-vars
8439 (setq org-local-vars (org-get-local-variables)))
8443 (defun orgstruct-make-binding (fun n &rest keys)
8444 "Create a function for binding in the structure minor mode.
8445 FUN is the command to call inside a table. N is used to create a unique
8446 command name. KEYS are keys that should be checked in for a command
8447 to execute outside of tables."
8448 (eval
8449 (list 'defun
8450 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8451 '(arg)
8452 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8453 "Outside of structure, run the binding of `"
8454 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8455 "'.")
8456 '(interactive "p")
8457 (list 'if
8458 `(org-context-p 'headline 'item
8459 (and orgstruct-is-++
8460 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8461 'item-body))
8462 (list 'org-run-like-in-org-mode (list 'quote fun))
8463 (list 'let '(orgstruct-mode)
8464 (list 'call-interactively
8465 (append '(or)
8466 (mapcar (lambda (k)
8467 (list 'key-binding k))
8468 keys)
8469 '('orgstruct-error))))))))
8471 (defun org-context-p (&rest contexts)
8472 "Check if local context is any of CONTEXTS.
8473 Possible values in the list of contexts are `table', `headline', and `item'."
8474 (let ((pos (point)))
8475 (goto-char (point-at-bol))
8476 (prog1 (or (and (memq 'table contexts)
8477 (looking-at "[ \t]*|"))
8478 (and (memq 'headline contexts)
8479 (looking-at org-outline-regexp))
8480 (and (memq 'item contexts)
8481 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8482 (and (memq 'item-body contexts)
8483 (org-in-item-p)))
8484 (goto-char pos))))
8486 (defun org-get-local-variables ()
8487 "Return a list of all local variables in an org-mode buffer."
8488 (let (varlist)
8489 (with-current-buffer (get-buffer-create "*Org tmp*")
8490 (erase-buffer)
8491 (org-mode)
8492 (setq varlist (buffer-local-variables)))
8493 (kill-buffer "*Org tmp*")
8494 (delq nil
8495 (mapcar
8496 (lambda (x)
8497 (setq x
8498 (if (symbolp x)
8499 (list x)
8500 (list (car x) (list 'quote (cdr x)))))
8501 (if (string-match
8502 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8503 (symbol-name (car x)))
8504 x nil))
8505 varlist))))
8507 (defun org-clone-local-variables (from-buffer &optional regexp)
8508 "Clone local variables from FROM-BUFFER.
8509 Optional argument REGEXP selects variables to clone."
8510 (mapc
8511 (lambda (pair)
8512 (and (symbolp (car pair))
8513 (or (null regexp)
8514 (string-match regexp (symbol-name (car pair))))
8515 (set (make-local-variable (car pair))
8516 (cdr pair))))
8517 (buffer-local-variables from-buffer)))
8519 ;;;###autoload
8520 (defun org-run-like-in-org-mode (cmd)
8521 "Run a command, pretending that the current buffer is in Org-mode.
8522 This will temporarily bind local variables that are typically bound in
8523 Org-mode to the values they have in Org-mode, and then interactively
8524 call CMD."
8525 (org-load-modules-maybe)
8526 (unless org-local-vars
8527 (setq org-local-vars (org-get-local-variables)))
8528 (eval (list 'let org-local-vars
8529 (list 'call-interactively (list 'quote cmd)))))
8531 ;;;; Archiving
8533 (defun org-get-category (&optional pos force-refresh)
8534 "Get the category applying to position POS."
8535 (save-match-data
8536 (if force-refresh (org-refresh-category-properties))
8537 (let ((pos (or pos (point))))
8538 (or (get-text-property pos 'org-category)
8539 (progn (org-refresh-category-properties)
8540 (get-text-property pos 'org-category))))))
8542 (defun org-refresh-category-properties ()
8543 "Refresh category text properties in the buffer."
8544 (let ((def-cat (cond
8545 ((null org-category)
8546 (if buffer-file-name
8547 (file-name-sans-extension
8548 (file-name-nondirectory buffer-file-name))
8549 "???"))
8550 ((symbolp org-category) (symbol-name org-category))
8551 (t org-category)))
8552 beg end cat pos optionp)
8553 (org-unmodified
8554 (save-excursion
8555 (save-restriction
8556 (widen)
8557 (goto-char (point-min))
8558 (put-text-property (point) (point-max) 'org-category def-cat)
8559 (while (re-search-forward
8560 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8561 (setq pos (match-end 0)
8562 optionp (equal (char-after (match-beginning 0)) ?#)
8563 cat (org-trim (match-string 2)))
8564 (if optionp
8565 (setq beg (point-at-bol) end (point-max))
8566 (org-back-to-heading t)
8567 (setq beg (point) end (org-end-of-subtree t t)))
8568 (put-text-property beg end 'org-category cat)
8569 (put-text-property beg end 'org-category-position beg)
8570 (goto-char pos)))))))
8573 ;;;; Link Stuff
8575 ;;; Link abbreviations
8577 (defun org-link-expand-abbrev (link)
8578 "Apply replacements as defined in `org-link-abbrev-alist."
8579 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8580 (let* ((key (match-string 1 link))
8581 (as (or (assoc key org-link-abbrev-alist-local)
8582 (assoc key org-link-abbrev-alist)))
8583 (tag (and (match-end 2) (match-string 3 link)))
8584 rpl)
8585 (if (not as)
8586 link
8587 (setq rpl (cdr as))
8588 (cond
8589 ((symbolp rpl) (funcall rpl tag))
8590 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8591 ((string-match "%h" rpl)
8592 (replace-match (url-hexify-string (or tag "")) t t rpl))
8593 (t (concat rpl tag)))))
8594 link))
8596 ;;; Storing and inserting links
8598 (defvar org-insert-link-history nil
8599 "Minibuffer history for links inserted with `org-insert-link'.")
8601 (defvar org-stored-links nil
8602 "Contains the links stored with `org-store-link'.")
8604 (defvar org-store-link-plist nil
8605 "Plist with info about the most recently link created with `org-store-link'.")
8607 (defvar org-link-protocols nil
8608 "Link protocols added to Org-mode using `org-add-link-type'.")
8610 (defvar org-store-link-functions nil
8611 "List of functions that are called to create and store a link.
8612 Each function will be called in turn until one returns a non-nil
8613 value. Each function should check if it is responsible for creating
8614 this link (for example by looking at the major mode).
8615 If not, it must exit and return nil.
8616 If yes, it should return a non-nil value after a calling
8617 `org-store-link-props' with a list of properties and values.
8618 Special properties are:
8620 :type The link prefix, like \"http\". This must be given.
8621 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8622 This is obligatory as well.
8623 :description Optional default description for the second pair
8624 of brackets in an Org-mode link. The user can still change
8625 this when inserting this link into an Org-mode buffer.
8627 In addition to these, any additional properties can be specified
8628 and then used in remember templates.")
8630 (defun org-add-link-type (type &optional follow export)
8631 "Add TYPE to the list of `org-link-types'.
8632 Re-compute all regular expressions depending on `org-link-types'
8634 FOLLOW and EXPORT are two functions.
8636 FOLLOW should take the link path as the single argument and do whatever
8637 is necessary to follow the link, for example find a file or display
8638 a mail message.
8640 EXPORT should format the link path for export to one of the export formats.
8641 It should be a function accepting three arguments:
8643 path the path of the link, the text after the prefix (like \"http:\")
8644 desc the description of the link, if any, or a description added by
8645 org-export-normalize-links if there is none
8646 format the export format, a symbol like `html' or `latex' or `ascii'..
8648 The function may use the FORMAT information to return different values
8649 depending on the format. The return value will be put literally into
8650 the exported file. If the return value is nil, this means Org should
8651 do what it normally does with links which do not have EXPORT defined.
8653 Org-mode has a built-in default for exporting links. If you are happy with
8654 this default, there is no need to define an export function for the link
8655 type. For a simple example of an export function, see `org-bbdb.el'."
8656 (add-to-list 'org-link-types type t)
8657 (org-make-link-regexps)
8658 (if (assoc type org-link-protocols)
8659 (setcdr (assoc type org-link-protocols) (list follow export))
8660 (push (list type follow export) org-link-protocols)))
8662 (defvar org-agenda-buffer-name)
8664 ;;;###autoload
8665 (defun org-store-link (arg)
8666 "\\<org-mode-map>Store an org-link to the current location.
8667 This link is added to `org-stored-links' and can later be inserted
8668 into an org-buffer with \\[org-insert-link].
8670 For some link types, a prefix arg is interpreted:
8671 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8672 For file links, arg negates `org-context-in-file-links'."
8673 (interactive "P")
8674 (org-load-modules-maybe)
8675 (setq org-store-link-plist nil) ; reset
8676 (org-with-limited-levels
8677 (let (link cpltxt desc description search txt custom-id agenda-link)
8678 (cond
8680 ((run-hook-with-args-until-success 'org-store-link-functions)
8681 (setq link (plist-get org-store-link-plist :link)
8682 desc (or (plist-get org-store-link-plist :description) link)))
8684 ((org-src-edit-buffer-p)
8685 (let (label gc)
8686 (while (or (not label)
8687 (save-excursion
8688 (save-restriction
8689 (widen)
8690 (goto-char (point-min))
8691 (re-search-forward
8692 (regexp-quote (format org-coderef-label-format label))
8693 nil t))))
8694 (when label (message "Label exists already") (sit-for 2))
8695 (setq label (read-string "Code line label: " label)))
8696 (end-of-line 1)
8697 (setq link (format org-coderef-label-format label))
8698 (setq gc (- 79 (length link)))
8699 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8700 (insert link)
8701 (setq link (concat "(" label ")") desc nil)))
8703 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8704 ;; We are in the agenda, link to referenced location
8705 (let ((m (or (get-text-property (point) 'org-hd-marker)
8706 (get-text-property (point) 'org-marker))))
8707 (when m
8708 (org-with-point-at m
8709 (setq agenda-link
8710 (if (org-called-interactively-p 'any)
8711 (call-interactively 'org-store-link)
8712 (org-store-link nil)))))))
8714 ((eq major-mode 'calendar-mode)
8715 (let ((cd (calendar-cursor-to-date)))
8716 (setq link
8717 (format-time-string
8718 (car org-time-stamp-formats)
8719 (apply 'encode-time
8720 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8721 nil nil nil))))
8722 (org-store-link-props :type "calendar" :date cd)))
8724 ((eq major-mode 'w3-mode)
8725 (setq cpltxt (if (and (buffer-name)
8726 (not (string-match "Untitled" (buffer-name))))
8727 (buffer-name)
8728 (url-view-url t))
8729 link (org-make-link (url-view-url t)))
8730 (org-store-link-props :type "w3" :url (url-view-url t)))
8732 ((eq major-mode 'w3m-mode)
8733 (setq cpltxt (or w3m-current-title w3m-current-url)
8734 link (org-make-link w3m-current-url))
8735 (org-store-link-props :type "w3m" :url (url-view-url t)))
8737 ((setq search (run-hook-with-args-until-success
8738 'org-create-file-search-functions))
8739 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8740 "::" search))
8741 (setq cpltxt (or description link)))
8743 ((eq major-mode 'image-mode)
8744 (setq cpltxt (concat "file:"
8745 (abbreviate-file-name buffer-file-name))
8746 link (org-make-link cpltxt))
8747 (org-store-link-props :type "image" :file buffer-file-name))
8749 ((eq major-mode 'dired-mode)
8750 ;; link to the file in the current line
8751 (let ((file (dired-get-filename nil t)))
8752 (setq file (if file
8753 (abbreviate-file-name
8754 (expand-file-name (dired-get-filename nil t)))
8755 ;; otherwise, no file so use current directory.
8756 default-directory))
8757 (setq cpltxt (concat "file:" file)
8758 link (org-make-link cpltxt))))
8760 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8761 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8762 (cond
8763 ((org-in-regexp "<<\\(.*?\\)>>")
8764 (setq cpltxt
8765 (concat "file:"
8766 (abbreviate-file-name
8767 (buffer-file-name (buffer-base-buffer)))
8768 "::" (match-string 1))
8769 link (org-make-link cpltxt)))
8770 ((and (featurep 'org-id)
8771 (or (eq org-link-to-org-use-id t)
8772 (and (eq org-link-to-org-use-id 'create-if-interactive)
8773 (org-called-interactively-p 'any))
8774 (and (eq org-link-to-org-use-id
8775 'create-if-interactive-and-no-custom-id)
8776 (org-called-interactively-p 'any)
8777 (not custom-id))
8778 (and org-link-to-org-use-id
8779 (org-entry-get nil "ID"))))
8780 ;; We can make a link using the ID.
8781 (setq link (condition-case nil
8782 (prog1 (org-id-store-link)
8783 (setq desc (plist-get org-store-link-plist
8784 :description)))
8785 (error
8786 ;; probably before first headline, link to file only
8787 (concat "file:"
8788 (abbreviate-file-name
8789 (buffer-file-name (buffer-base-buffer))))))))
8791 ;; Just link to current headline
8792 (setq cpltxt (concat "file:"
8793 (abbreviate-file-name
8794 (buffer-file-name (buffer-base-buffer)))))
8795 ;; Add a context search string
8796 (when (org-xor org-context-in-file-links arg)
8797 (setq txt (cond
8798 ((org-at-heading-p) nil)
8799 ((org-region-active-p)
8800 (buffer-substring (region-beginning) (region-end)))
8801 (t nil)))
8802 (when (or (null txt) (string-match "\\S-" txt))
8803 (setq cpltxt
8804 (concat cpltxt "::"
8805 (condition-case nil
8806 (org-make-org-heading-search-string txt)
8807 (error "")))
8808 desc (or (nth 4 (ignore-errors
8809 (org-heading-components))) "NONE"))))
8810 (if (string-match "::\\'" cpltxt)
8811 (setq cpltxt (substring cpltxt 0 -2)))
8812 (setq link (org-make-link cpltxt)))))
8814 ((buffer-file-name (buffer-base-buffer))
8815 ;; Just link to this file here.
8816 (setq cpltxt (concat "file:"
8817 (abbreviate-file-name
8818 (buffer-file-name (buffer-base-buffer)))))
8819 ;; Add a context string
8820 (when (org-xor org-context-in-file-links arg)
8821 (setq txt (if (org-region-active-p)
8822 (buffer-substring (region-beginning) (region-end))
8823 (buffer-substring (point-at-bol) (point-at-eol))))
8824 ;; Only use search option if there is some text.
8825 (when (string-match "\\S-" txt)
8826 (setq cpltxt
8827 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8828 desc "NONE")))
8829 (setq link (org-make-link cpltxt)))
8831 ((org-called-interactively-p 'interactive)
8832 (error "Cannot link to a buffer which is not visiting a file"))
8834 (t (setq link nil)))
8836 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8837 (setq link (or link cpltxt)
8838 desc (or desc cpltxt))
8839 (if (equal desc "NONE") (setq desc nil))
8841 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8842 (progn
8843 (setq org-stored-links
8844 (cons (list link desc) org-stored-links))
8845 (message "Stored: %s" (or desc link))
8846 (when custom-id
8847 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8848 "::#" custom-id))
8849 (setq org-stored-links
8850 (cons (list link desc) org-stored-links))))
8851 (or agenda-link (and link (org-make-link-string link desc)))))))
8853 (defun org-store-link-props (&rest plist)
8854 "Store link properties, extract names and addresses."
8855 (let (x adr)
8856 (when (setq x (plist-get plist :from))
8857 (setq adr (mail-extract-address-components x))
8858 (setq plist (plist-put plist :fromname (car adr)))
8859 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8860 (when (setq x (plist-get plist :to))
8861 (setq adr (mail-extract-address-components x))
8862 (setq plist (plist-put plist :toname (car adr)))
8863 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8864 (let ((from (plist-get plist :from))
8865 (to (plist-get plist :to)))
8866 (when (and from to org-from-is-user-regexp)
8867 (setq plist
8868 (plist-put plist :fromto
8869 (if (string-match org-from-is-user-regexp from)
8870 (concat "to %t")
8871 (concat "from %f"))))))
8872 (setq org-store-link-plist plist))
8874 (defun org-add-link-props (&rest plist)
8875 "Add these properties to the link property list."
8876 (let (key value)
8877 (while plist
8878 (setq key (pop plist) value (pop plist))
8879 (setq org-store-link-plist
8880 (plist-put org-store-link-plist key value)))))
8882 (defun org-email-link-description (&optional fmt)
8883 "Return the description part of an email link.
8884 This takes information from `org-store-link-plist' and formats it
8885 according to FMT (default from `org-email-link-description-format')."
8886 (setq fmt (or fmt org-email-link-description-format))
8887 (let* ((p org-store-link-plist)
8888 (to (plist-get p :toaddress))
8889 (from (plist-get p :fromaddress))
8890 (table
8891 (list
8892 (cons "%c" (plist-get p :fromto))
8893 (cons "%F" (plist-get p :from))
8894 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8895 (cons "%T" (plist-get p :to))
8896 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8897 (cons "%s" (plist-get p :subject))
8898 (cons "%d" (plist-get p :date))
8899 (cons "%m" (plist-get p :message-id)))))
8900 (when (string-match "%c" fmt)
8901 ;; Check if the user wrote this message
8902 (if (and org-from-is-user-regexp from to
8903 (save-match-data (string-match org-from-is-user-regexp from)))
8904 (setq fmt (replace-match "to %t" t t fmt))
8905 (setq fmt (replace-match "from %f" t t fmt))))
8906 (org-replace-escapes fmt table)))
8908 (defun org-make-org-heading-search-string (&optional string heading)
8909 "Make search string for STRING or current headline."
8910 (interactive)
8911 (let ((s (or string (org-get-heading)))
8912 (lines org-context-in-file-links))
8913 (unless (and string (not heading))
8914 ;; We are using a headline, clean up garbage in there.
8915 (if (string-match org-todo-regexp s)
8916 (setq s (replace-match "" t t s)))
8917 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8918 (setq s (replace-match "" t t s)))
8919 (setq s (org-trim s))
8920 (if (string-match (concat "^\\(" org-quote-string "\\|"
8921 org-comment-string "\\)") s)
8922 (setq s (replace-match "" t t s)))
8923 (while (string-match org-ts-regexp s)
8924 (setq s (replace-match "" t t s))))
8925 (or string (setq s (concat "*" s))) ; Add * for headlines
8926 (when (and string (integerp lines) (> lines 0))
8927 (let ((slines (org-split-string s "\n")))
8928 (when (< lines (length slines))
8929 (setq s (mapconcat
8930 'identity
8931 (reverse (nthcdr (- (length slines) lines)
8932 (reverse slines))) "\n")))))
8933 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8935 (defun org-make-link (&rest strings)
8936 "Concatenate STRINGS."
8937 (apply 'concat strings))
8939 (defun org-make-link-string (link &optional description)
8940 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8941 (unless (string-match "\\S-" link)
8942 (error "Empty link"))
8943 (when (and description
8944 (stringp description)
8945 (not (string-match "\\S-" description)))
8946 (setq description nil))
8947 (when (stringp description)
8948 ;; Remove brackets from the description, they are fatal.
8949 (while (string-match "\\[" description)
8950 (setq description (replace-match "{" t t description)))
8951 (while (string-match "\\]" description)
8952 (setq description (replace-match "}" t t description))))
8953 (when (equal link description)
8954 ;; No description needed, it is identical
8955 (setq description nil))
8956 (when (and (not description)
8957 (not (string-match (org-image-file-name-regexp) link))
8958 (not (equal link (org-link-escape link))))
8959 (setq description (org-extract-attributes link)))
8960 (setq link
8961 (cond ((string-match (org-image-file-name-regexp) link) link)
8962 ((string-match org-link-types-re link)
8963 (concat (match-string 1 link)
8964 (org-link-escape (substring link (match-end 1)))))
8965 (t (org-link-escape link))))
8966 (concat "[[" link "]"
8967 (if description (concat "[" description "]") "")
8968 "]"))
8970 (defconst org-link-escape-chars
8971 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8972 "List of characters that should be escaped in link.
8973 This is the list that is used for internal purposes.")
8975 (defvar org-url-encoding-use-url-hexify nil)
8977 (defconst org-link-escape-chars-browser
8978 '(?\ )
8979 "List of escapes for characters that are problematic in links.
8980 This is the list that is used before handing over to the browser.")
8982 (defun org-link-escape (text &optional table merge)
8983 "Return percent escaped representation of TEXT.
8984 TEXT is a string with the text to escape.
8985 Optional argument TABLE is a list with characters that should be
8986 escaped. When nil, `org-link-escape-chars' is used.
8987 If optional argument MERGE is set, merge TABLE into
8988 `org-link-escape-chars'."
8989 (if (and org-url-encoding-use-url-hexify (not table))
8990 (url-hexify-string text)
8991 (cond
8992 ((and table merge)
8993 (mapc (lambda (defchr)
8994 (unless (member defchr table)
8995 (setq table (cons defchr table)))) org-link-escape-chars))
8996 ((null table)
8997 (setq table org-link-escape-chars)))
8998 (mapconcat
8999 (lambda (char)
9000 (if (or (member char table)
9001 (< char 32) (= char 37) (> char 126))
9002 (mapconcat (lambda (sequence-element)
9003 (format "%%%.2X" sequence-element))
9004 (or (encode-coding-char char 'utf-8)
9005 (error "Unable to percent escape character: %s"
9006 (char-to-string char))) "")
9007 (char-to-string char))) text "")))
9009 (defun org-link-unescape (str)
9010 "Unhex hexified Unicode strings as returned from the JavaScript function
9011 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9012 (unless (and (null str) (string= "" str))
9013 (let ((pos 0) (case-fold-search t) unhexed)
9014 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9015 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9016 (setq str (replace-match unhexed t t str))
9017 (setq pos (+ pos (length unhexed))))))
9018 str)
9020 (defun org-link-unescape-compound (hex)
9021 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9022 Note: this function also decodes single byte encodings like
9023 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9024 (save-match-data
9025 (let* ((bytes (cdr (split-string hex "%")))
9026 (ret "")
9027 (eat 0)
9028 (sum 0))
9029 (while bytes
9030 (let* ((val (string-to-number (pop bytes) 16))
9031 (shift-xor
9032 (if (= 0 eat)
9033 (cond
9034 ((>= val 252) (cons 6 252))
9035 ((>= val 248) (cons 5 248))
9036 ((>= val 240) (cons 4 240))
9037 ((>= val 224) (cons 3 224))
9038 ((>= val 192) (cons 2 192))
9039 (t (cons 0 0)))
9040 (cons 6 128))))
9041 (if (>= val 192) (setq eat (car shift-xor)))
9042 (setq val (logxor val (cdr shift-xor)))
9043 (setq sum (+ (lsh sum (car shift-xor)) val))
9044 (if (> eat 0) (setq eat (- eat 1)))
9045 (cond
9046 ((= 0 eat) ;multi byte
9047 (setq ret (concat ret (org-char-to-string sum)))
9048 (setq sum 0))
9049 ((not bytes) ; single byte(s)
9050 (setq ret (org-link-unescape-single-byte-sequence hex))))
9051 )) ;; end (while bytes
9052 ret )))
9054 (defun org-link-unescape-single-byte-sequence (hex)
9055 "Unhexify hex-encoded single byte character sequences."
9056 (mapconcat (lambda (byte)
9057 (char-to-string (string-to-number byte 16)))
9058 (cdr (split-string hex "%")) ""))
9060 (defun org-xor (a b)
9061 "Exclusive or."
9062 (if a (not b) b))
9064 (defun org-fixup-message-id-for-http (s)
9065 "Replace special characters in a message id, so it can be used in an http query."
9066 (when (string-match "%" s)
9067 (setq s (mapconcat (lambda (c)
9068 (if (eq c ?%)
9069 "%25"
9070 (char-to-string c)))
9071 s "")))
9072 (while (string-match "<" s)
9073 (setq s (replace-match "%3C" t t s)))
9074 (while (string-match ">" s)
9075 (setq s (replace-match "%3E" t t s)))
9076 (while (string-match "@" s)
9077 (setq s (replace-match "%40" t t s)))
9080 ;;;###autoload
9081 (defun org-insert-link-global ()
9082 "Insert a link like Org-mode does.
9083 This command can be called in any mode to insert a link in Org-mode syntax."
9084 (interactive)
9085 (org-load-modules-maybe)
9086 (org-run-like-in-org-mode 'org-insert-link))
9088 (defun org-insert-link (&optional complete-file link-location default-description)
9089 "Insert a link. At the prompt, enter the link.
9091 Completion can be used to insert any of the link protocol prefixes like
9092 http or ftp in use.
9094 The history can be used to select a link previously stored with
9095 `org-store-link'. When the empty string is entered (i.e. if you just
9096 press RET at the prompt), the link defaults to the most recently
9097 stored link. As SPC triggers completion in the minibuffer, you need to
9098 use M-SPC or C-q SPC to force the insertion of a space character.
9100 You will also be prompted for a description, and if one is given, it will
9101 be displayed in the buffer instead of the link.
9103 If there is already a link at point, this command will allow you to edit link
9104 and description parts.
9106 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9107 be selected using completion. The path to the file will be relative to the
9108 current directory if the file is in the current directory or a subdirectory.
9109 Otherwise, the link will be the absolute path as completed in the minibuffer
9110 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9111 option `org-link-file-path-type'.
9113 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9114 the current directory or below.
9116 With three \\[universal-argument] prefixes, negate the meaning of
9117 `org-keep-stored-link-after-insertion'.
9119 If `org-make-link-description-function' is non-nil, this function will be
9120 called with the link target, and the result will be the default
9121 link description.
9123 If the LINK-LOCATION parameter is non-nil, this value will be
9124 used as the link location instead of reading one interactively.
9126 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9127 be used as the default description."
9128 (interactive "P")
9129 (let* ((wcf (current-window-configuration))
9130 (region (if (org-region-active-p)
9131 (buffer-substring (region-beginning) (region-end))))
9132 (remove (and region (list (region-beginning) (region-end))))
9133 (desc region)
9134 tmphist ; byte-compile incorrectly complains about this
9135 (link link-location)
9136 entry file all-prefixes)
9137 (cond
9138 (link-location) ; specified by arg, just use it.
9139 ((org-in-regexp org-bracket-link-regexp 1)
9140 ;; We do have a link at point, and we are going to edit it.
9141 (setq remove (list (match-beginning 0) (match-end 0)))
9142 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9143 (setq link (read-string "Link: "
9144 (org-link-unescape
9145 (org-match-string-no-properties 1)))))
9146 ((or (org-in-regexp org-angle-link-re)
9147 (org-in-regexp org-plain-link-re))
9148 ;; Convert to bracket link
9149 (setq remove (list (match-beginning 0) (match-end 0))
9150 link (read-string "Link: "
9151 (org-remove-angle-brackets (match-string 0)))))
9152 ((member complete-file '((4) (16)))
9153 ;; Completing read for file names.
9154 (setq link (org-file-complete-link complete-file)))
9156 ;; Read link, with completion for stored links.
9157 (with-output-to-temp-buffer "*Org Links*"
9158 (princ "Insert a link.
9159 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9160 (when org-stored-links
9161 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9162 (princ (mapconcat
9163 (lambda (x)
9164 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9165 (reverse org-stored-links) "\n"))))
9166 (let ((cw (selected-window)))
9167 (select-window (get-buffer-window "*Org Links*" 'visible))
9168 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9169 (unless (pos-visible-in-window-p (point-max))
9170 (org-fit-window-to-buffer))
9171 (and (window-live-p cw) (select-window cw)))
9172 ;; Fake a link history, containing the stored links.
9173 (setq tmphist (append (mapcar 'car org-stored-links)
9174 org-insert-link-history))
9175 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9176 (mapcar 'car org-link-abbrev-alist)
9177 org-link-types))
9178 (unwind-protect
9179 (progn
9180 (setq link
9181 (let ((org-completion-use-ido nil)
9182 (org-completion-use-iswitchb nil))
9183 (org-completing-read
9184 "Link: "
9185 (append
9186 (mapcar (lambda (x) (list (concat x ":")))
9187 all-prefixes)
9188 (mapcar 'car org-stored-links))
9189 nil nil nil
9190 'tmphist
9191 (car (car org-stored-links)))))
9192 (if (not (string-match "\\S-" link))
9193 (error "No link selected"))
9194 (if (or (member link all-prefixes)
9195 (and (equal ":" (substring link -1))
9196 (member (substring link 0 -1) all-prefixes)
9197 (setq link (substring link 0 -1))))
9198 (setq link (org-link-try-special-completion link))))
9199 (set-window-configuration wcf)
9200 (kill-buffer "*Org Links*"))
9201 (setq entry (assoc link org-stored-links))
9202 (or entry (push link org-insert-link-history))
9203 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9204 (not org-keep-stored-link-after-insertion))
9205 (setq org-stored-links (delq (assoc link org-stored-links)
9206 org-stored-links)))
9207 (setq desc (or desc (nth 1 entry)))))
9209 (if (string-match org-plain-link-re link)
9210 ;; URL-like link, normalize the use of angular brackets.
9211 (setq link (org-make-link (org-remove-angle-brackets link))))
9213 ;; Check if we are linking to the current file with a search option
9214 ;; If yes, simplify the link by using only the search option.
9215 (when (and buffer-file-name
9216 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9217 (let* ((path (match-string 1 link))
9218 (case-fold-search nil)
9219 (search (match-string 2 link)))
9220 (save-match-data
9221 (if (equal (file-truename buffer-file-name) (file-truename path))
9222 ;; We are linking to this same file, with a search option
9223 (setq link search)))))
9225 ;; Check if we can/should use a relative path. If yes, simplify the link
9226 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9227 (let* ((type (match-string 1 link))
9228 (path (match-string 2 link))
9229 (origpath path)
9230 (case-fold-search nil))
9231 (cond
9232 ((or (eq org-link-file-path-type 'absolute)
9233 (equal complete-file '(16)))
9234 (setq path (abbreviate-file-name (expand-file-name path))))
9235 ((eq org-link-file-path-type 'noabbrev)
9236 (setq path (expand-file-name path)))
9237 ((eq org-link-file-path-type 'relative)
9238 (setq path (file-relative-name path)))
9240 (save-match-data
9241 (if (string-match (concat "^" (regexp-quote
9242 (expand-file-name
9243 (file-name-as-directory
9244 default-directory))))
9245 (expand-file-name path))
9246 ;; We are linking a file with relative path name.
9247 (setq path (substring (expand-file-name path)
9248 (match-end 0)))
9249 (setq path (abbreviate-file-name (expand-file-name path)))))))
9250 (setq link (concat type path))
9251 (if (equal desc origpath)
9252 (setq desc path))))
9254 (if org-make-link-description-function
9255 (setq desc (funcall org-make-link-description-function link desc))
9256 (if default-description (setq desc default-description)))
9258 (setq desc (read-string "Description: " desc))
9259 (unless (string-match "\\S-" desc) (setq desc nil))
9260 (if remove (apply 'delete-region remove))
9261 (insert (org-make-link-string link desc))))
9263 (defun org-link-try-special-completion (type)
9264 "If there is completion support for link type TYPE, offer it."
9265 (let ((fun (intern (concat "org-" type "-complete-link"))))
9266 (if (functionp fun)
9267 (funcall fun)
9268 (read-string "Link (no completion support): " (concat type ":")))))
9270 (defun org-file-complete-link (&optional arg)
9271 "Create a file link using completion."
9272 (let (file link)
9273 (setq file (read-file-name "File: "))
9274 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9275 (pwd1 (file-name-as-directory (abbreviate-file-name
9276 (expand-file-name ".")))))
9277 (cond
9278 ((equal arg '(16))
9279 (setq link (org-make-link
9280 "file:"
9281 (abbreviate-file-name (expand-file-name file)))))
9282 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9283 (setq link (org-make-link "file:" (match-string 1 file))))
9284 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9285 (expand-file-name file))
9286 (setq link (org-make-link
9287 "file:" (match-string 1 (expand-file-name file)))))
9288 (t (setq link (org-make-link "file:" file)))))
9289 link))
9291 (defun org-completing-read (&rest args)
9292 "Completing-read with SPACE being a normal character."
9293 (let ((enable-recursive-minibuffers t)
9294 (minibuffer-local-completion-map
9295 (copy-keymap minibuffer-local-completion-map)))
9296 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9297 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9298 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9299 (apply 'org-icompleting-read args)))
9301 (defun org-completing-read-no-i (&rest args)
9302 (let (org-completion-use-ido org-completion-use-iswitchb)
9303 (apply 'org-completing-read args)))
9305 (defun org-iswitchb-completing-read (prompt choices &rest args)
9306 "Use iswitch as a completing-read replacement to choose from choices.
9307 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9308 from."
9309 (let* ((iswitchb-use-virtual-buffers nil)
9310 (iswitchb-make-buflist-hook
9311 (lambda ()
9312 (setq iswitchb-temp-buflist choices))))
9313 (iswitchb-read-buffer prompt)))
9315 (defun org-icompleting-read (&rest args)
9316 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9317 (org-without-partial-completion
9318 (if (and org-completion-use-ido
9319 (fboundp 'ido-completing-read)
9320 (boundp 'ido-mode) ido-mode
9321 (listp (second args)))
9322 (let ((ido-enter-matching-directory nil))
9323 (apply 'ido-completing-read (concat (car args))
9324 (if (consp (car (nth 1 args)))
9325 (mapcar 'car (nth 1 args))
9326 (nth 1 args))
9327 (cddr args)))
9328 (if (and org-completion-use-iswitchb
9329 (boundp 'iswitchb-mode) iswitchb-mode
9330 (listp (second args)))
9331 (apply 'org-iswitchb-completing-read (concat (car args))
9332 (if (consp (car (nth 1 args)))
9333 (mapcar 'car (nth 1 args))
9334 (nth 1 args))
9335 (cddr args))
9336 (apply 'completing-read args)))))
9338 (defun org-extract-attributes (s)
9339 "Extract the attributes cookie from a string and set as text property."
9340 (let (a attr (start 0) key value)
9341 (save-match-data
9342 (when (string-match "{{\\([^}]+\\)}}$" s)
9343 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9344 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9345 (setq key (match-string 1 a) value (match-string 2 a)
9346 start (match-end 0)
9347 attr (plist-put attr (intern key) value))))
9348 (org-add-props s nil 'org-attr attr))
9351 (defun org-extract-attributes-from-string (tag)
9352 (let (key value attr)
9353 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9354 (setq key (match-string 1 tag) value (match-string 2 tag)
9355 tag (replace-match "" t t tag)
9356 attr (plist-put attr (intern key) value)))
9357 (cons tag attr)))
9359 (defun org-attributes-to-string (plist)
9360 "Format a property list into an HTML attribute list."
9361 (let ((s "") key value)
9362 (while plist
9363 (setq key (pop plist) value (pop plist))
9364 (and value
9365 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9368 ;;; Opening/following a link
9370 (defvar org-link-search-failed nil)
9372 (defvar org-open-link-functions nil
9373 "Hook for functions finding a plain text link.
9374 These functions must take a single argument, the link content.
9375 They will be called for links that look like [[link text][description]]
9376 when LINK TEXT does not have a protocol like \"http:\" and does not look
9377 like a filename (e.g. \"./blue.png\").
9379 These functions will be called *before* Org attempts to resolve the
9380 link by doing text searches in the current buffer - so if you want a
9381 link \"[[target]]\" to still find \"<<target>>\", your function should
9382 handle this as a special case.
9384 When the function does handle the link, it must return a non-nil value.
9385 If it decides that it is not responsible for this link, it must return
9386 nil to indicate that that Org-mode can continue with other options
9387 like exact and fuzzy text search.")
9389 (defun org-next-link ()
9390 "Move forward to the next link.
9391 If the link is in hidden text, expose it."
9392 (interactive)
9393 (when (and org-link-search-failed (eq this-command last-command))
9394 (goto-char (point-min))
9395 (message "Link search wrapped back to beginning of buffer"))
9396 (setq org-link-search-failed nil)
9397 (let* ((pos (point))
9398 (ct (org-context))
9399 (a (assoc :link ct)))
9400 (if a (goto-char (nth 2 a)))
9401 (if (re-search-forward org-any-link-re nil t)
9402 (progn
9403 (goto-char (match-beginning 0))
9404 (if (outline-invisible-p) (org-show-context)))
9405 (goto-char pos)
9406 (setq org-link-search-failed t)
9407 (error "No further link found"))))
9409 (defun org-previous-link ()
9410 "Move backward to the previous link.
9411 If the link is in hidden text, expose it."
9412 (interactive)
9413 (when (and org-link-search-failed (eq this-command last-command))
9414 (goto-char (point-max))
9415 (message "Link search wrapped back to end of buffer"))
9416 (setq org-link-search-failed nil)
9417 (let* ((pos (point))
9418 (ct (org-context))
9419 (a (assoc :link ct)))
9420 (if a (goto-char (nth 1 a)))
9421 (if (re-search-backward org-any-link-re nil t)
9422 (progn
9423 (goto-char (match-beginning 0))
9424 (if (outline-invisible-p) (org-show-context)))
9425 (goto-char pos)
9426 (setq org-link-search-failed t)
9427 (error "No further link found"))))
9429 (defun org-translate-link (s)
9430 "Translate a link string if a translation function has been defined."
9431 (if (and org-link-translation-function
9432 (fboundp org-link-translation-function)
9433 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9434 (progn
9435 (setq s (funcall org-link-translation-function
9436 (match-string 1) (match-string 2)))
9437 (concat (car s) ":" (cdr s)))
9440 (defun org-translate-link-from-planner (type path)
9441 "Translate a link from Emacs Planner syntax so that Org can follow it.
9442 This is still an experimental function, your mileage may vary."
9443 (cond
9444 ((member type '("http" "https" "news" "ftp"))
9445 ;; standard Internet links are the same.
9446 nil)
9447 ((and (equal type "irc") (string-match "^//" path))
9448 ;; Planner has two / at the beginning of an irc link, we have 1.
9449 ;; We should have zero, actually....
9450 (setq path (substring path 1)))
9451 ((and (equal type "lisp") (string-match "^/" path))
9452 ;; Planner has a slash, we do not.
9453 (setq type "elisp" path (substring path 1)))
9454 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9455 ;; A typical message link. Planner has the id after the final slash,
9456 ;; we separate it with a hash mark
9457 (setq path (concat (match-string 1 path) "#"
9458 (org-remove-angle-brackets (match-string 2 path)))))
9460 (cons type path))
9462 (defun org-find-file-at-mouse (ev)
9463 "Open file link or URL at mouse."
9464 (interactive "e")
9465 (mouse-set-point ev)
9466 (org-open-at-point 'in-emacs))
9468 (defun org-open-at-mouse (ev)
9469 "Open file link or URL at mouse.
9470 See the docstring of `org-open-file' for details."
9471 (interactive "e")
9472 (mouse-set-point ev)
9473 (if (eq major-mode 'org-agenda-mode)
9474 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9475 (org-open-at-point))
9477 (defvar org-window-config-before-follow-link nil
9478 "The window configuration before following a link.
9479 This is saved in case the need arises to restore it.")
9481 (defvar org-open-link-marker (make-marker)
9482 "Marker pointing to the location where `org-open-at-point; was called.")
9484 ;;;###autoload
9485 (defun org-open-at-point-global ()
9486 "Follow a link like Org-mode does.
9487 This command can be called in any mode to follow a link that has
9488 Org-mode syntax."
9489 (interactive)
9490 (org-run-like-in-org-mode 'org-open-at-point))
9492 ;;;###autoload
9493 (defun org-open-link-from-string (s &optional arg reference-buffer)
9494 "Open a link in the string S, as if it was in Org-mode."
9495 (interactive "sLink: \nP")
9496 (let ((reference-buffer (or reference-buffer (current-buffer))))
9497 (with-temp-buffer
9498 (let ((org-inhibit-startup (not reference-buffer)))
9499 (org-mode)
9500 (insert s)
9501 (goto-char (point-min))
9502 (when reference-buffer
9503 (setq org-link-abbrev-alist-local
9504 (with-current-buffer reference-buffer
9505 org-link-abbrev-alist-local)))
9506 (org-open-at-point arg reference-buffer)))))
9508 (defvar org-open-at-point-functions nil
9509 "Hook that is run when following a link at point.
9511 Functions in this hook must return t if they identify and follow
9512 a link at point. If they don't find anything interesting at point,
9513 they must return nil.")
9515 (defun org-open-at-point (&optional arg reference-buffer)
9516 "Open link at or after point.
9517 If there is no link at point, this function will search forward up to
9518 the end of the current line.
9519 Normally, files will be opened by an appropriate application. If the
9520 optional prefix argument ARG is non-nil, Emacs will visit the file.
9521 With a double prefix argument, try to open outside of Emacs, in the
9522 application the system uses for this file type."
9523 (interactive "P")
9524 ;; if in a code block, then open the block's results
9525 (unless (call-interactively #'org-babel-open-src-block-result)
9526 (org-load-modules-maybe)
9527 (move-marker org-open-link-marker (point))
9528 (setq org-window-config-before-follow-link (current-window-configuration))
9529 (org-remove-occur-highlights nil nil t)
9530 (cond
9531 ((and (org-at-heading-p)
9532 (not (org-in-regexp
9533 (concat org-plain-link-re "\\|"
9534 org-bracket-link-regexp "\\|"
9535 org-angle-link-re "\\|"
9536 "[ \t]:[^ \t\n]+:[ \t]*$")))
9537 (not (get-text-property (point) 'org-linked-text)))
9538 (or (org-offer-links-in-entry arg)
9539 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9540 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9541 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9542 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9543 (not (org-in-regexp org-bracket-link-regexp)))
9544 (org-footnote-action))
9546 (let (type path link line search (pos (point)))
9547 (catch 'match
9548 (save-excursion
9549 (skip-chars-forward "^]\n\r")
9550 (when (org-in-regexp org-bracket-link-regexp 1)
9551 (setq link (org-extract-attributes
9552 (org-link-unescape (org-match-string-no-properties 1))))
9553 (while (string-match " *\n *" link)
9554 (setq link (replace-match " " t t link)))
9555 (setq link (org-link-expand-abbrev link))
9556 (cond
9557 ((or (file-name-absolute-p link)
9558 (string-match "^\\.\\.?/" link))
9559 (setq type "file" path link))
9560 ((string-match org-link-re-with-space3 link)
9561 (setq type (match-string 1 link) path (match-string 2 link)))
9562 (t (setq type "thisfile" path link)))
9563 (throw 'match t)))
9565 (when (get-text-property (point) 'org-linked-text)
9566 (setq type "thisfile"
9567 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9568 (1+ (point)) (point))
9569 path (buffer-substring
9570 (or (previous-single-property-change pos 'org-linked-text)
9571 (point-min))
9572 (or (next-single-property-change pos 'org-linked-text)
9573 (point-max))))
9574 (throw 'match t))
9576 (save-excursion
9577 (when (or (org-in-regexp org-angle-link-re)
9578 (org-in-regexp org-plain-link-re))
9579 (setq type (match-string 1)
9580 path (org-link-unescape (match-string 2)))
9581 (throw 'match t)))
9582 (save-excursion
9583 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9584 (setq type "tags"
9585 path (match-string 1))
9586 (while (string-match ":" path)
9587 (setq path (replace-match "+" t t path)))
9588 (throw 'match t)))
9589 (when (org-in-regexp "<\\([^><\n]+\\)>")
9590 (setq type "tree-match"
9591 path (match-string 1))
9592 (throw 'match t)))
9593 (unless path
9594 (error "No link found"))
9596 ;; switch back to reference buffer
9597 ;; needed when if called in a temporary buffer through
9598 ;; org-open-link-from-string
9599 (with-current-buffer (or reference-buffer (current-buffer))
9601 ;; Remove any trailing spaces in path
9602 (if (string-match " +\\'" path)
9603 (setq path (replace-match "" t t path)))
9604 (if (and org-link-translation-function
9605 (fboundp org-link-translation-function))
9606 ;; Check if we need to translate the link
9607 (let ((tmp (funcall org-link-translation-function type path)))
9608 (setq type (car tmp) path (cdr tmp))))
9610 (cond
9612 ((assoc type org-link-protocols)
9613 (funcall (nth 1 (assoc type org-link-protocols)) path))
9615 ((equal type "mailto")
9616 (let ((cmd (car org-link-mailto-program))
9617 (args (cdr org-link-mailto-program)) args1
9618 (address path) (subject "") a)
9619 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9620 (setq address (match-string 1 path)
9621 subject (org-link-escape (match-string 2 path))))
9622 (while args
9623 (cond
9624 ((not (stringp (car args))) (push (pop args) args1))
9625 (t (setq a (pop args))
9626 (if (string-match "%a" a)
9627 (setq a (replace-match address t t a)))
9628 (if (string-match "%s" a)
9629 (setq a (replace-match subject t t a)))
9630 (push a args1))))
9631 (apply cmd (nreverse args1))))
9633 ((member type '("http" "https" "ftp" "news"))
9634 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9635 (org-link-escape
9636 path org-link-escape-chars-browser)
9637 path))))
9639 ((string= type "doi")
9640 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9641 (org-link-escape
9642 path org-link-escape-chars-browser)
9643 path))))
9645 ((member type '("message"))
9646 (browse-url (concat type ":" path)))
9648 ((string= type "tags")
9649 (org-tags-view arg path))
9651 ((string= type "tree-match")
9652 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9654 ((string= type "file")
9655 (if (string-match "::\\([0-9]+\\)\\'" path)
9656 (setq line (string-to-number (match-string 1 path))
9657 path (substring path 0 (match-beginning 0)))
9658 (if (string-match "::\\(.+\\)\\'" path)
9659 (setq search (match-string 1 path)
9660 path (substring path 0 (match-beginning 0)))))
9661 (if (string-match "[*?{]" (file-name-nondirectory path))
9662 (dired path)
9663 (org-open-file path arg line search)))
9665 ((string= type "shell")
9666 (let ((cmd path))
9667 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9668 (string-match org-confirm-shell-link-not-regexp cmd))
9669 (not org-confirm-shell-link-function)
9670 (funcall org-confirm-shell-link-function
9671 (format "Execute \"%s\" in shell? "
9672 (org-add-props cmd nil
9673 'face 'org-warning))))
9674 (progn
9675 (message "Executing %s" cmd)
9676 (shell-command cmd))
9677 (error "Abort"))))
9679 ((string= type "elisp")
9680 (let ((cmd path))
9681 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9682 (string-match org-confirm-elisp-link-not-regexp cmd))
9683 (not org-confirm-elisp-link-function)
9684 (funcall org-confirm-elisp-link-function
9685 (format "Execute \"%s\" as elisp? "
9686 (org-add-props cmd nil
9687 'face 'org-warning))))
9688 (message "%s => %s" cmd
9689 (if (equal (string-to-char cmd) ?\()
9690 (eval (read cmd))
9691 (call-interactively (read cmd))))
9692 (error "Abort"))))
9694 ((and (string= type "thisfile")
9695 (run-hook-with-args-until-success
9696 'org-open-link-functions path)))
9698 ((string= type "thisfile")
9699 (if arg
9700 (switch-to-buffer-other-window
9701 (org-get-buffer-for-internal-link (current-buffer)))
9702 (org-mark-ring-push))
9703 (let ((cmd `(org-link-search
9704 ,path
9705 ,(cond ((equal arg '(4)) ''occur)
9706 ((equal arg '(16)) ''org-occur)
9707 (t nil))
9708 ,pos)))
9709 (condition-case nil (let ((org-link-search-inhibit-query t))
9710 (eval cmd))
9711 (error (progn (widen) (eval cmd))))))
9714 (browse-url-at-point)))))))
9715 (move-marker org-open-link-marker nil)
9716 (run-hook-with-args 'org-follow-link-hook)))
9718 (defun org-offer-links-in-entry (&optional nth zero)
9719 "Offer links in the current entry and follow the selected link.
9720 If there is only one link, follow it immediately as well.
9721 If NTH is an integer, immediately pick the NTH link found.
9722 If ZERO is a string, check also this string for a link, and if
9723 there is one, offer it as link number zero."
9724 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9725 "\\(" org-angle-link-re "\\)\\|"
9726 "\\(" org-plain-link-re "\\)"))
9727 (cnt ?0)
9728 (in-emacs (if (integerp nth) nil nth))
9729 have-zero end links link c)
9730 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9731 (push (match-string 0 zero) links)
9732 (setq cnt (1- cnt) have-zero t))
9733 (save-excursion
9734 (org-back-to-heading t)
9735 (setq end (save-excursion (outline-next-heading) (point)))
9736 (while (re-search-forward re end t)
9737 (push (match-string 0) links))
9738 (setq links (org-uniquify (reverse links))))
9740 (cond
9741 ((null links)
9742 (message "No links"))
9743 ((equal (length links) 1)
9744 (setq link (list (car links))))
9745 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9746 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9747 (t ; we have to select a link
9748 (save-excursion
9749 (save-window-excursion
9750 (delete-other-windows)
9751 (with-output-to-temp-buffer "*Select Link*"
9752 (mapc (lambda (l)
9753 (if (not (string-match org-bracket-link-regexp l))
9754 (princ (format "[%c] %s\n" (incf cnt)
9755 (org-remove-angle-brackets l)))
9756 (if (match-end 3)
9757 (princ (format "[%c] %s (%s)\n" (incf cnt)
9758 (match-string 3 l) (match-string 1 l)))
9759 (princ (format "[%c] %s\n" (incf cnt)
9760 (match-string 1 l))))))
9761 links))
9762 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9763 (message "Select link to open, RET to open all:")
9764 (setq c (read-char-exclusive))
9765 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9766 (when (equal c ?q) (error "Abort"))
9767 (if (equal c ?\C-m)
9768 (setq link links)
9769 (setq nth (- c ?0))
9770 (if have-zero (setq nth (1+ nth)))
9771 (unless (and (integerp nth) (>= (length links) nth))
9772 (error "Invalid link selection"))
9773 (setq link (list (nth (1- nth) links))))))
9774 (if link
9775 (let ((buf (current-buffer)))
9776 (dolist (l link)
9777 (org-open-link-from-string l in-emacs buf))
9779 nil)))
9781 ;; Add special file links that specify the way of opening
9783 (org-add-link-type "file+sys" 'org-open-file-with-system)
9784 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9785 (defun org-open-file-with-system (path)
9786 "Open file at PATH using the system way of opening it."
9787 (org-open-file path 'system))
9788 (defun org-open-file-with-emacs (path)
9789 "Open file at PATH in Emacs."
9790 (org-open-file path 'emacs))
9791 (defun org-remove-file-link-modifiers ()
9792 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9793 (goto-char (point-min))
9794 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9795 (org-if-unprotected
9796 (replace-match "file:" t t))))
9797 (eval-after-load "org-exp"
9798 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9799 'org-remove-file-link-modifiers))
9801 ;;;; Time estimates
9803 (defun org-get-effort (&optional pom)
9804 "Get the effort estimate for the current entry."
9805 (org-entry-get pom org-effort-property))
9807 ;;; File search
9809 (defvar org-create-file-search-functions nil
9810 "List of functions to construct the right search string for a file link.
9811 These functions are called in turn with point at the location to
9812 which the link should point.
9814 A function in the hook should first test if it would like to
9815 handle this file type, for example by checking the `major-mode'
9816 or the file extension. If it decides not to handle this file, it
9817 should just return nil to give other functions a chance. If it
9818 does handle the file, it must return the search string to be used
9819 when following the link. The search string will be part of the
9820 file link, given after a double colon, and `org-open-at-point'
9821 will automatically search for it. If special measures must be
9822 taken to make the search successful, another function should be
9823 added to the companion hook `org-execute-file-search-functions',
9824 which see.
9826 A function in this hook may also use `setq' to set the variable
9827 `description' to provide a suggestion for the descriptive text to
9828 be used for this link when it gets inserted into an Org-mode
9829 buffer with \\[org-insert-link].")
9831 (defvar org-execute-file-search-functions nil
9832 "List of functions to execute a file search triggered by a link.
9834 Functions added to this hook must accept a single argument, the
9835 search string that was part of the file link, the part after the
9836 double colon. The function must first check if it would like to
9837 handle this search, for example by checking the `major-mode' or
9838 the file extension. If it decides not to handle this search, it
9839 should just return nil to give other functions a chance. If it
9840 does handle the search, it must return a non-nil value to keep
9841 other functions from trying.
9843 Each function can access the current prefix argument through the
9844 variable `current-prefix-argument'. Note that a single prefix is
9845 used to force opening a link in Emacs, so it may be good to only
9846 use a numeric or double prefix to guide the search function.
9848 In case this is needed, a function in this hook can also restore
9849 the window configuration before `org-open-at-point' was called using:
9851 (set-window-configuration org-window-config-before-follow-link)")
9853 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9854 (defun org-link-search (s &optional type avoid-pos stealth)
9855 "Search for a link search option.
9856 If S is surrounded by forward slashes, it is interpreted as a
9857 regular expression. In org-mode files, this will create an `org-occur'
9858 sparse tree. In ordinary files, `occur' will be used to list matches.
9859 If the current buffer is in `dired-mode', grep will be used to search
9860 in all files. If AVOID-POS is given, ignore matches near that position.
9862 When optional argument STEALTH is non-nil, do not modify
9863 visibility around point, thus ignoring
9864 `org-show-hierarchy-above', `org-show-following-heading' and
9865 `org-show-siblings' variables."
9866 (let ((case-fold-search t)
9867 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9868 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9869 (append '(("") (" ") ("\t") ("\n"))
9870 org-emphasis-alist)
9871 "\\|") "\\)"))
9872 (pos (point))
9873 (pre nil) (post nil)
9874 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9875 (cond
9876 ;; First check if there are any special search functions
9877 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9878 ;; Now try the builtin stuff
9879 ((and (equal (string-to-char s0) ?#)
9880 (> (length s0) 1)
9881 (save-excursion
9882 (goto-char (point-min))
9883 (and
9884 (re-search-forward
9885 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9886 (setq type 'dedicated
9887 pos (match-beginning 0))))
9888 ;; There is an exact target for this
9889 (goto-char pos)
9890 (org-back-to-heading t)))
9891 ((save-excursion
9892 (goto-char (point-min))
9893 (and
9894 (re-search-forward
9895 (concat "<<" (regexp-quote s0) ">>") nil t)
9896 (setq type 'dedicated
9897 pos (match-beginning 0))))
9898 ;; There is an exact target for this
9899 (goto-char pos))
9900 ((and (string-match "^(\\(.*\\))$" s0)
9901 (save-excursion
9902 (goto-char (point-min))
9903 (and
9904 (re-search-forward
9905 (concat "[^[]" (regexp-quote
9906 (format org-coderef-label-format
9907 (match-string 1 s0))))
9908 nil t)
9909 (setq type 'dedicated
9910 pos (1+ (match-beginning 0))))))
9911 ;; There is a coderef target for this
9912 (goto-char pos))
9913 ((string-match "^/\\(.*\\)/$" s)
9914 ;; A regular expression
9915 (cond
9916 ((eq major-mode 'org-mode)
9917 (org-occur (match-string 1 s)))
9918 ;;((eq major-mode 'dired-mode)
9919 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9920 (t (org-do-occur (match-string 1 s)))))
9921 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9922 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9923 (goto-char (point-min))
9924 (cond
9925 ((let (case-fold-search)
9926 (re-search-forward (format org-complex-heading-regexp-format
9927 (regexp-quote s))
9928 nil t))
9929 ;; OK, found a match
9930 (setq type 'dedicated)
9931 (goto-char (match-beginning 0)))
9932 ((and (not org-link-search-inhibit-query)
9933 (eq org-link-search-must-match-exact-headline 'query-to-create)
9934 (y-or-n-p "No match - create this as a new heading? "))
9935 (goto-char (point-max))
9936 (or (bolp) (newline))
9937 (insert "* " s "\n")
9938 (beginning-of-line 0))
9940 (goto-char pos)
9941 (error "No match"))))
9943 ;; A normal search string
9944 (when (equal (string-to-char s) ?*)
9945 ;; Anchor on headlines, post may include tags.
9946 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9947 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9948 s (substring s 1)))
9949 (remove-text-properties
9950 0 (length s)
9951 '(face nil mouse-face nil keymap nil fontified nil) s)
9952 ;; Make a series of regular expressions to find a match
9953 (setq words (org-split-string s "[ \n\r\t]+")
9955 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9956 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9957 "\\)" markers)
9958 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9959 re2a (concat "[ \t\r\n]" re2a_)
9960 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9961 re4 (concat "[^a-zA-Z_]" re4_)
9963 re1 (concat pre re2 post)
9964 re3 (concat pre (if pre re4_ re4) post)
9965 re5 (concat pre ".*" re4)
9966 re2 (concat pre re2)
9967 re2a (concat pre (if pre re2a_ re2a))
9968 re4 (concat pre (if pre re4_ re4))
9969 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9970 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9971 re5 "\\)"
9973 (cond
9974 ((eq type 'org-occur) (org-occur reall))
9975 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9976 (t (goto-char (point-min))
9977 (setq type 'fuzzy)
9978 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9979 (org-search-not-self 1 re1 nil t)
9980 (org-search-not-self 1 re2 nil t)
9981 (org-search-not-self 1 re2a nil t)
9982 (org-search-not-self 1 re3 nil t)
9983 (org-search-not-self 1 re4 nil t)
9984 (org-search-not-self 1 re5 nil t)
9986 (goto-char (match-beginning 1))
9987 (goto-char pos)
9988 (error "No match"))))))
9989 (and (eq major-mode 'org-mode)
9990 (not stealth)
9991 (org-show-context 'link-search))
9992 type))
9994 (defun org-search-not-self (group &rest args)
9995 "Execute `re-search-forward', but only accept matches that do not
9996 enclose the position of `org-open-link-marker'."
9997 (let ((m org-open-link-marker))
9998 (catch 'exit
9999 (while (apply 're-search-forward args)
10000 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10001 (goto-char (match-end group))
10002 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10003 (> (match-beginning 0) (marker-position m))
10004 (< (match-end 0) (marker-position m)))
10005 (save-match-data
10006 (or (not (org-in-regexp
10007 org-bracket-link-analytic-regexp 1))
10008 (not (match-end 4)) ; no description
10009 (and (<= (match-beginning 4) (point))
10010 (>= (match-end 4) (point))))))
10011 (throw 'exit (point))))))))
10013 (defun org-get-buffer-for-internal-link (buffer)
10014 "Return a buffer to be used for displaying the link target of internal links."
10015 (cond
10016 ((not org-display-internal-link-with-indirect-buffer)
10017 buffer)
10018 ((string-match "(Clone)$" (buffer-name buffer))
10019 (message "Buffer is already a clone, not making another one")
10020 ;; we also do not modify visibility in this case
10021 buffer)
10022 (t ; make a new indirect buffer for displaying the link
10023 (let* ((bn (buffer-name buffer))
10024 (ibn (concat bn "(Clone)"))
10025 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10026 (with-current-buffer ib (org-overview))
10027 ib))))
10029 (defun org-do-occur (regexp &optional cleanup)
10030 "Call the Emacs command `occur'.
10031 If CLEANUP is non-nil, remove the printout of the regular expression
10032 in the *Occur* buffer. This is useful if the regex is long and not useful
10033 to read."
10034 (occur regexp)
10035 (when cleanup
10036 (let ((cwin (selected-window)) win beg end)
10037 (when (setq win (get-buffer-window "*Occur*"))
10038 (select-window win))
10039 (goto-char (point-min))
10040 (when (re-search-forward "match[a-z]+" nil t)
10041 (setq beg (match-end 0))
10042 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10043 (setq end (1- (match-beginning 0)))))
10044 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10045 (goto-char (point-min))
10046 (select-window cwin))))
10048 ;;; The mark ring for links jumps
10050 (defvar org-mark-ring nil
10051 "Mark ring for positions before jumps in Org-mode.")
10052 (defvar org-mark-ring-last-goto nil
10053 "Last position in the mark ring used to go back.")
10054 ;; Fill and close the ring
10055 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10056 (loop for i from 1 to org-mark-ring-length do
10057 (push (make-marker) org-mark-ring))
10058 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10059 org-mark-ring)
10061 (defun org-mark-ring-push (&optional pos buffer)
10062 "Put the current position or POS into the mark ring and rotate it."
10063 (interactive)
10064 (setq pos (or pos (point)))
10065 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10066 (move-marker (car org-mark-ring)
10067 (or pos (point))
10068 (or buffer (current-buffer)))
10069 (message "%s"
10070 (substitute-command-keys
10071 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10073 (defun org-mark-ring-goto (&optional n)
10074 "Jump to the previous position in the mark ring.
10075 With prefix arg N, jump back that many stored positions. When
10076 called several times in succession, walk through the entire ring.
10077 Org-mode commands jumping to a different position in the current file,
10078 or to another Org-mode file, automatically push the old position
10079 onto the ring."
10080 (interactive "p")
10081 (let (p m)
10082 (if (eq last-command this-command)
10083 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10084 (setq p org-mark-ring))
10085 (setq org-mark-ring-last-goto p)
10086 (setq m (car p))
10087 (org-pop-to-buffer-same-window (marker-buffer m))
10088 (goto-char m)
10089 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10091 (defun org-remove-angle-brackets (s)
10092 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10093 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10095 (defun org-add-angle-brackets (s)
10096 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10097 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10099 (defun org-remove-double-quotes (s)
10100 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10101 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10104 ;;; Following specific links
10106 (defun org-follow-timestamp-link ()
10107 (cond
10108 ((org-at-date-range-p t)
10109 (let ((org-agenda-start-on-weekday)
10110 (t1 (match-string 1))
10111 (t2 (match-string 2)))
10112 (setq t1 (time-to-days (org-time-string-to-time t1))
10113 t2 (time-to-days (org-time-string-to-time t2)))
10114 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10115 ((org-at-timestamp-p t)
10116 (org-agenda-list nil (time-to-days (org-time-string-to-time
10117 (substring (match-string 1) 0 10)))
10119 (t (error "This should not happen"))))
10122 ;;; Following file links
10123 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10124 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10125 (declare-function mailcap-mime-info
10126 "mailcap" (string &optional request no-decode))
10127 (defvar org-wait nil)
10128 (defun org-open-file (path &optional in-emacs line search)
10129 "Open the file at PATH.
10130 First, this expands any special file name abbreviations. Then the
10131 configuration variable `org-file-apps' is checked if it contains an
10132 entry for this file type, and if yes, the corresponding command is launched.
10134 If no application is found, Emacs simply visits the file.
10136 With optional prefix argument IN-EMACS, Emacs will visit the file.
10137 With a double \\[universal-argument] \\[universal-argument] \
10138 prefix arg, Org tries to avoid opening in Emacs
10139 and to use an external application to visit the file.
10141 Optional LINE specifies a line to go to, optional SEARCH a string
10142 to search for. If LINE or SEARCH is given, the file will be
10143 opened in Emacs, unless an entry from org-file-apps that makes
10144 use of groups in a regexp matches.
10146 If you want to change the way frames are used when following a
10147 link, please customize `org-link-frame-setup'.
10149 If the file does not exist, an error is thrown."
10150 (let* ((file (if (equal path "")
10151 buffer-file-name
10152 (substitute-in-file-name (expand-file-name path))))
10153 (file-apps (append org-file-apps (org-default-apps)))
10154 (apps (org-remove-if
10155 'org-file-apps-entry-match-against-dlink-p file-apps))
10156 (apps-dlink (org-remove-if-not
10157 'org-file-apps-entry-match-against-dlink-p file-apps))
10158 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10159 (dirp (if remp nil (file-directory-p file)))
10160 (file (if (and dirp org-open-directory-means-index-dot-org)
10161 (concat (file-name-as-directory file) "index.org")
10162 file))
10163 (a-m-a-p (assq 'auto-mode apps))
10164 (dfile (downcase file))
10165 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10166 (link (cond ((and (eq line nil)
10167 (eq search nil))
10168 file)
10169 (line
10170 (concat file "::" (number-to-string line)))
10171 (search
10172 (concat file "::" search))))
10173 (dlink (downcase link))
10174 (old-buffer (current-buffer))
10175 (old-pos (point))
10176 (old-mode major-mode)
10177 ext cmd link-match-data)
10178 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10179 (setq ext (match-string 1 dfile))
10180 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10181 (setq ext (match-string 1 dfile))))
10182 (cond
10183 ((member in-emacs '((16) system))
10184 (setq cmd (cdr (assoc 'system apps))))
10185 (in-emacs (setq cmd 'emacs))
10187 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10188 (and dirp (cdr (assoc 'directory apps)))
10189 ; first, try matching against apps-dlink
10190 ; if we get a match here, store the match data for later
10191 (let ((match (assoc-default dlink apps-dlink
10192 'string-match)))
10193 (if match
10194 (progn (setq link-match-data (match-data))
10195 match)
10196 (progn (setq in-emacs (or in-emacs line search))
10197 nil))) ; if we have no match in apps-dlink,
10198 ; always open the file in emacs if line or search
10199 ; is given (for backwards compatibility)
10200 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10201 'string-match)
10202 (cdr (assoc ext apps))
10203 (cdr (assoc t apps))))))
10204 (when (eq cmd 'system)
10205 (setq cmd (cdr (assoc 'system apps))))
10206 (when (eq cmd 'default)
10207 (setq cmd (cdr (assoc t apps))))
10208 (when (eq cmd 'mailcap)
10209 (require 'mailcap)
10210 (mailcap-parse-mailcaps)
10211 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10212 (command (mailcap-mime-info mime-type)))
10213 (if (stringp command)
10214 (setq cmd command)
10215 (setq cmd 'emacs))))
10216 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10217 (not (file-exists-p file))
10218 (not org-open-non-existing-files))
10219 (error "No such file: %s" file))
10220 (cond
10221 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10222 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10223 (while (string-match "['\"]%s['\"]" cmd)
10224 (setq cmd (replace-match "%s" t t cmd)))
10225 (while (string-match "%s" cmd)
10226 (setq cmd (replace-match
10227 (save-match-data
10228 (shell-quote-argument
10229 (convert-standard-filename file)))
10230 t t cmd)))
10232 ;; Replace "%1", "%2" etc. in command with group matches from regex
10233 (save-match-data
10234 (let ((match-index 1)
10235 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10236 (set-match-data link-match-data)
10237 (while (<= match-index number-of-groups)
10238 (let ((regex (concat "%" (number-to-string match-index)))
10239 (replace-with (match-string match-index dlink)))
10240 (while (string-match regex cmd)
10241 (setq cmd (replace-match replace-with t t cmd))))
10242 (setq match-index (+ match-index 1)))))
10244 (save-window-excursion
10245 (start-process-shell-command cmd nil cmd)
10246 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10248 ((or (stringp cmd)
10249 (eq cmd 'emacs))
10250 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10251 (widen)
10252 (if line (org-goto-line line)
10253 (if search (org-link-search search))))
10254 ((consp cmd)
10255 (let ((file (convert-standard-filename file)))
10256 (save-match-data
10257 (set-match-data link-match-data)
10258 (eval cmd))))
10259 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10260 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10261 (or (not (equal old-buffer (current-buffer)))
10262 (not (equal old-pos (point))))
10263 (org-mark-ring-push old-pos old-buffer))))
10265 (defun org-file-apps-entry-match-against-dlink-p (entry)
10266 "This function returns non-nil if `entry' uses a regular
10267 expression which should be matched against the whole link by
10268 org-open-file.
10270 It assumes that is the case when the entry uses a regular
10271 expression which has at least one grouping construct and the
10272 action is either a lisp form or a command string containing
10273 '%1', i.e. using at least one subexpression match as a
10274 parameter."
10275 (let ((selector (car entry))
10276 (action (cdr entry)))
10277 (if (stringp selector)
10278 (and (> (regexp-opt-depth selector) 0)
10279 (or (and (stringp action)
10280 (string-match "%[0-9]" action))
10281 (consp action)))
10282 nil)))
10284 (defun org-default-apps ()
10285 "Return the default applications for this operating system."
10286 (cond
10287 ((eq system-type 'darwin)
10288 org-file-apps-defaults-macosx)
10289 ((eq system-type 'windows-nt)
10290 org-file-apps-defaults-windowsnt)
10291 (t org-file-apps-defaults-gnu)))
10293 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10294 "Convert extensions to regular expressions in the cars of LIST.
10295 Also, weed out any non-string entries, because the return value is used
10296 only for regexp matching.
10297 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10298 point to the symbol `emacs', indicating that the file should
10299 be opened in Emacs."
10300 (append
10301 (delq nil
10302 (mapcar (lambda (x)
10303 (if (not (stringp (car x)))
10305 (if (string-match "\\W" (car x))
10307 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10308 list))
10309 (if add-auto-mode
10310 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10312 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10313 (defun org-file-remote-p (file)
10314 "Test whether FILE specifies a location on a remote system.
10315 Return non-nil if the location is indeed remote.
10317 For example, the filename \"/user@host:/foo\" specifies a location
10318 on the system \"/user@host:\"."
10319 (cond ((fboundp 'file-remote-p)
10320 (file-remote-p file))
10321 ((fboundp 'tramp-handle-file-remote-p)
10322 (tramp-handle-file-remote-p file))
10323 ((and (boundp 'ange-ftp-name-format)
10324 (string-match (car ange-ftp-name-format) file))
10326 (t nil)))
10329 ;;;; Refiling
10331 (defun org-get-org-file ()
10332 "Read a filename, with default directory `org-directory'."
10333 (let ((default (or org-default-notes-file remember-data-file)))
10334 (read-file-name (format "File name [%s]: " default)
10335 (file-name-as-directory org-directory)
10336 default)))
10338 (defun org-notes-order-reversed-p ()
10339 "Check if the current file should receive notes in reversed order."
10340 (cond
10341 ((not org-reverse-note-order) nil)
10342 ((eq t org-reverse-note-order) t)
10343 ((not (listp org-reverse-note-order)) nil)
10344 (t (catch 'exit
10345 (let ((all org-reverse-note-order)
10346 entry)
10347 (while (setq entry (pop all))
10348 (if (string-match (car entry) buffer-file-name)
10349 (throw 'exit (cdr entry))))
10350 nil)))))
10352 (defvar org-refile-target-table nil
10353 "The list of refile targets, created by `org-refile'.")
10355 (defvar org-agenda-new-buffers nil
10356 "Buffers created to visit agenda files.")
10358 (defvar org-refile-cache nil
10359 "Cache for refile targets.")
10361 (defvar org-refile-markers nil
10362 "All the markers used for caching refile locations.")
10364 (defun org-refile-marker (pos)
10365 "Get a new refile marker, but only if caching is in use."
10366 (if (not org-refile-use-cache)
10368 (let ((m (make-marker)))
10369 (move-marker m pos)
10370 (push m org-refile-markers)
10371 m)))
10373 (defun org-refile-cache-clear ()
10374 "Clear the refile cache and disable all the markers."
10375 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10376 (setq org-refile-markers nil)
10377 (setq org-refile-cache nil)
10378 (message "Refile cache has been cleared"))
10380 (defun org-refile-cache-check-set (set)
10381 "Check if all the markers in the cache still have live buffers."
10382 (let (marker)
10383 (catch 'exit
10384 (while (and set (setq marker (nth 3 (pop set))))
10385 ;; if org-refile-use-outline-path is 'file, marker may be nil
10386 (when (and marker (null (marker-buffer marker)))
10387 (message "not found") (sit-for 3)
10388 (throw 'exit nil)))
10389 t)))
10391 (defun org-refile-cache-put (set &rest identifiers)
10392 "Push the refile targets SET into the cache, under IDENTIFIERS."
10393 (let* ((key (sha1 (prin1-to-string identifiers)))
10394 (entry (assoc key org-refile-cache)))
10395 (if entry
10396 (setcdr entry set)
10397 (push (cons key set) org-refile-cache))))
10399 (defun org-refile-cache-get (&rest identifiers)
10400 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10401 (cond
10402 ((not org-refile-cache) nil)
10403 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10405 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10406 org-refile-cache))))
10407 (and set (org-refile-cache-check-set set) set)))))
10409 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10410 "Produce a table with refile targets."
10411 (let ((case-fold-search nil)
10412 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10413 (entries (or org-refile-targets '((nil . (:level . 1)))))
10414 targets tgs txt re files f desc descre fast-path-p level pos0)
10415 (message "Getting targets...")
10416 (with-current-buffer (or default-buffer (current-buffer))
10417 (while (setq entry (pop entries))
10418 (setq files (car entry) desc (cdr entry))
10419 (setq fast-path-p nil)
10420 (cond
10421 ((null files) (setq files (list (current-buffer))))
10422 ((eq files 'org-agenda-files)
10423 (setq files (org-agenda-files 'unrestricted)))
10424 ((and (symbolp files) (fboundp files))
10425 (setq files (funcall files)))
10426 ((and (symbolp files) (boundp files))
10427 (setq files (symbol-value files))))
10428 (if (stringp files) (setq files (list files)))
10429 (cond
10430 ((eq (car desc) :tag)
10431 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10432 ((eq (car desc) :todo)
10433 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10434 ((eq (car desc) :regexp)
10435 (setq descre (cdr desc)))
10436 ((eq (car desc) :level)
10437 (setq descre (concat "^\\*\\{" (number-to-string
10438 (if org-odd-levels-only
10439 (1- (* 2 (cdr desc)))
10440 (cdr desc)))
10441 "\\}[ \t]")))
10442 ((eq (car desc) :maxlevel)
10443 (setq fast-path-p t)
10444 (setq descre (concat "^\\*\\{1," (number-to-string
10445 (if org-odd-levels-only
10446 (1- (* 2 (cdr desc)))
10447 (cdr desc)))
10448 "\\}[ \t]")))
10449 (t (error "Bad refiling target description %s" desc)))
10450 (while (setq f (pop files))
10451 (with-current-buffer
10452 (if (bufferp f) f (org-get-agenda-file-buffer f))
10454 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10455 (progn
10456 (if (bufferp f) (setq f (buffer-file-name
10457 (buffer-base-buffer f))))
10458 (setq f (and f (expand-file-name f)))
10459 (if (eq org-refile-use-outline-path 'file)
10460 (push (list (file-name-nondirectory f) f nil nil) tgs))
10461 (save-excursion
10462 (save-restriction
10463 (widen)
10464 (goto-char (point-min))
10465 (while (re-search-forward descre nil t)
10466 (goto-char (setq pos0 (point-at-bol)))
10467 (catch 'next
10468 (when org-refile-target-verify-function
10469 (save-match-data
10470 (or (funcall org-refile-target-verify-function)
10471 (throw 'next t))))
10472 (when (and (looking-at org-complex-heading-regexp)
10473 (not (member (match-string 4) excluded-entries))
10474 (match-string 4))
10475 (setq level (org-reduced-level
10476 (- (match-end 1) (match-beginning 1)))
10477 txt (org-link-display-format (match-string 4))
10478 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10479 re (format org-complex-heading-regexp-format
10480 (regexp-quote (match-string 4))))
10481 (when org-refile-use-outline-path
10482 (setq txt (mapconcat
10483 'org-protect-slash
10484 (append
10485 (if (eq org-refile-use-outline-path
10486 'file)
10487 (list (file-name-nondirectory
10488 (buffer-file-name
10489 (buffer-base-buffer))))
10490 (if (eq org-refile-use-outline-path
10491 'full-file-path)
10492 (list (buffer-file-name
10493 (buffer-base-buffer)))))
10494 (org-get-outline-path fast-path-p
10495 level txt)
10496 (list txt))
10497 "/")))
10498 (push (list txt f re (org-refile-marker (point)))
10499 tgs)))
10500 (when (= (point) pos0)
10501 ;; verification function has not moved point
10502 (goto-char (point-at-eol))))))))
10503 (when org-refile-use-cache
10504 (org-refile-cache-put tgs (buffer-file-name) descre))
10505 (setq targets (append tgs targets))
10506 ))))
10507 (message "Getting targets...done")
10508 (nreverse targets)))
10510 (defun org-protect-slash (s)
10511 (while (string-match "/" s)
10512 (setq s (replace-match "\\" t t s)))
10515 (defvar org-olpa (make-vector 20 nil))
10517 (defun org-get-outline-path (&optional fastp level heading)
10518 "Return the outline path to the current entry, as a list.
10520 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10521 routine which makes outline path derivations for an entire file,
10522 avoiding backtracing. Refile target collection makes use of that."
10523 (if fastp
10524 (progn
10525 (if (> level 19)
10526 (error "Outline path failure, more than 19 levels"))
10527 (loop for i from level upto 19 do
10528 (aset org-olpa i nil))
10529 (prog1
10530 (delq nil (append org-olpa nil))
10531 (aset org-olpa level heading)))
10532 (let (rtn case-fold-search)
10533 (save-excursion
10534 (save-restriction
10535 (widen)
10536 (while (org-up-heading-safe)
10537 (when (looking-at org-complex-heading-regexp)
10538 (push (org-match-string-no-properties 4) rtn)))
10539 rtn)))))
10541 (defun org-format-outline-path (path &optional width prefix)
10542 "Format the outline path PATH for display.
10543 Width is the maximum number of characters that is available.
10544 Prefix is a prefix to be included in the returned string,
10545 such as the file name."
10546 (setq width (or width 79))
10547 (if prefix (setq width (- width (length prefix))))
10548 (if (not path)
10549 (or prefix "")
10550 (let* ((nsteps (length path))
10551 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10552 (maxwidth (if (<= total-width width)
10553 10000 ;; everything fits
10554 ;; we need to shorten the level headings
10555 (/ (- width nsteps) nsteps)))
10556 (org-odd-levels-only nil)
10557 (n 0)
10558 (total (1+ (length prefix))))
10559 (setq maxwidth (max maxwidth 10))
10560 (concat prefix
10561 (mapconcat
10562 (lambda (h)
10563 (setq n (1+ n))
10564 (if (and (= n nsteps) (< maxwidth 10000))
10565 (setq maxwidth (- total-width total)))
10566 (if (< (length h) maxwidth)
10567 (progn (setq total (+ total (length h) 1)) h)
10568 (setq h (substring h 0 (- maxwidth 2))
10569 total (+ total maxwidth 1))
10570 (if (string-match "[ \t]+\\'" h)
10571 (setq h (substring h 0 (match-beginning 0))))
10572 (setq h (concat h "..")))
10573 (org-add-props h nil 'face
10574 (nth (% (1- n) org-n-level-faces)
10575 org-level-faces))
10577 path "/")))))
10579 (defun org-display-outline-path (&optional file current)
10580 "Display the current outline path in the echo area."
10581 (interactive "P")
10582 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10583 (case-fold-search nil)
10584 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10585 (if current (setq path (append path
10586 (save-excursion
10587 (org-back-to-heading t)
10588 (if (looking-at org-complex-heading-regexp)
10589 (list (match-string 4)))))))
10590 (message "%s"
10591 (org-format-outline-path
10592 path
10593 (1- (frame-width))
10594 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10596 (defvar org-refile-history nil
10597 "History for refiling operations.")
10599 (defvar org-after-refile-insert-hook nil
10600 "Hook run after `org-refile' has inserted its stuff at the new location.
10601 Note that this is still *before* the stuff will be removed from
10602 the *old* location.")
10604 (defvar org-capture-last-stored-marker)
10605 (defun org-refile (&optional goto default-buffer rfloc)
10606 "Move the entry or entries at point to another heading.
10607 The list of target headings is compiled using the information in
10608 `org-refile-targets', which see.
10610 At the target location, the entry is filed as a subitem of the target
10611 heading. Depending on `org-reverse-note-order', the new subitem will
10612 either be the first or the last subitem.
10614 If there is an active region, all entries in that region will be moved.
10615 However, the region must fulfill the requirement that the first heading
10616 is the first one sets the top-level of the moved text - at most siblings
10617 below it are allowed.
10619 With prefix arg GOTO, the command will only visit the target location
10620 and not actually move anything.
10622 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10623 go to the location where the last refiling operation has put the subtree.
10624 With a prefix argument of `2', refile to the running clock.
10626 RFLOC can be a refile location obtained in a different way.
10628 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10630 If you are using target caching (see `org-refile-use-cache'),
10631 You have to clear the target cache in order to find new targets.
10632 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10633 prefix argument (`C-u C-u C-u C-c C-w')."
10635 (interactive "P")
10636 (if (member goto '(0 (64)))
10637 (org-refile-cache-clear)
10638 (let* ((cbuf (current-buffer))
10639 (regionp (org-region-active-p))
10640 (region-start (and regionp (region-beginning)))
10641 (region-end (and regionp (region-end)))
10642 (region-length (and regionp (- region-end region-start)))
10643 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10644 pos it nbuf file re level reversed)
10645 (setq last-command nil)
10646 (when regionp
10647 (goto-char region-start)
10648 (or (bolp) (goto-char (point-at-bol)))
10649 (setq region-start (point))
10650 (unless (or (org-kill-is-subtree-p
10651 (buffer-substring region-start region-end))
10652 (prog1 org-refile-active-region-within-subtree
10653 (org-toggle-heading)))
10654 (error "The region is not a (sequence of) subtree(s)")))
10655 (if (equal goto '(16))
10656 (org-refile-goto-last-stored)
10657 (when (or
10658 (and (equal goto 2)
10659 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10660 (prog1
10661 (setq it (list (or org-clock-heading "running clock")
10662 (buffer-file-name
10663 (marker-buffer org-clock-hd-marker))
10665 (marker-position org-clock-hd-marker)))
10666 (setq goto nil)))
10667 (setq it (or rfloc
10668 (let (heading-text)
10669 (save-excursion
10670 (unless goto
10671 (org-back-to-heading t)
10672 (setq heading-text
10673 (nth 4 (org-heading-components))))
10674 (org-refile-get-location
10675 (cond (goto "Goto")
10676 (regionp "Refile region to")
10677 (t (concat "Refile subtree \""
10678 heading-text "\" to")))
10679 default-buffer
10680 (and (not (equal '(4) goto))
10681 org-refile-allow-creating-parent-nodes)
10682 goto))))))
10683 (setq file (nth 1 it)
10684 re (nth 2 it)
10685 pos (nth 3 it))
10686 (if (and (not goto)
10688 (equal (buffer-file-name) file)
10689 (if regionp
10690 (and (>= pos region-start)
10691 (<= pos region-end))
10692 (and (>= pos (point))
10693 (< pos (save-excursion
10694 (org-end-of-subtree t t))))))
10695 (error "Cannot refile to position inside the tree or region"))
10697 (setq nbuf (or (find-buffer-visiting file)
10698 (find-file-noselect file)))
10699 (if goto
10700 (progn
10701 (org-pop-to-buffer-same-window nbuf)
10702 (goto-char pos)
10703 (org-show-context 'org-goto))
10704 (if regionp
10705 (progn
10706 (org-kill-new (buffer-substring region-start region-end))
10707 (org-save-markers-in-region region-start region-end))
10708 (org-copy-subtree 1 nil t))
10709 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10710 (find-file-noselect file)))
10711 (setq reversed (org-notes-order-reversed-p))
10712 (save-excursion
10713 (save-restriction
10714 (widen)
10715 (if pos
10716 (progn
10717 (goto-char pos)
10718 (looking-at org-outline-regexp)
10719 (setq level (org-get-valid-level (funcall outline-level) 1))
10720 (goto-char
10721 (if reversed
10722 (or (outline-next-heading) (point-max))
10723 (or (save-excursion (org-get-next-sibling))
10724 (org-end-of-subtree t t)
10725 (point-max)))))
10726 (setq level 1)
10727 (if (not reversed)
10728 (goto-char (point-max))
10729 (goto-char (point-min))
10730 (or (outline-next-heading) (goto-char (point-max)))))
10731 (if (not (bolp)) (newline))
10732 (org-paste-subtree level)
10733 (when org-log-refile
10734 (org-add-log-setup 'refile nil nil 'findpos
10735 org-log-refile)
10736 (unless (eq org-log-refile 'note)
10737 (save-excursion (org-add-log-note))))
10738 (and org-auto-align-tags (org-set-tags nil t))
10739 (bookmark-set "org-refile-last-stored")
10740 ;; If we are refiling for capture, make sure that the
10741 ;; last-capture pointers point here
10742 (when (org-bound-and-true-p org-refile-for-capture)
10743 (bookmark-set "org-capture-last-stored-marker")
10744 (move-marker org-capture-last-stored-marker (point)))
10745 (if (fboundp 'deactivate-mark) (deactivate-mark))
10746 (run-hooks 'org-after-refile-insert-hook))))
10747 (if regionp
10748 (delete-region (point) (+ (point) region-length))
10749 (org-cut-subtree))
10750 (when (featurep 'org-inlinetask)
10751 (org-inlinetask-remove-END-maybe))
10752 (setq org-markers-to-move nil)
10753 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10755 (defun org-refile-goto-last-stored ()
10756 "Go to the location where the last refile was stored."
10757 (interactive)
10758 (bookmark-jump "org-refile-last-stored")
10759 (message "This is the location of the last refile"))
10761 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10762 no-exclude)
10763 "Prompt the user for a refile location, using PROMPT.
10764 PROMPT should not be suffixed with a colon and a space, because
10765 this function appends the default value from
10766 `org-refile-history' automatically, if that is not empty.
10767 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10768 this is used for the GOTO interface."
10769 (let ((org-refile-targets org-refile-targets)
10770 (org-refile-use-outline-path org-refile-use-outline-path)
10771 excluded-entries)
10772 (when (and (eq major-mode 'org-mode)
10773 (not org-refile-use-cache)
10774 (not no-exclude))
10775 (org-map-tree
10776 (lambda()
10777 (setq excluded-entries
10778 (append excluded-entries (list (org-get-heading t t)))))))
10779 (setq org-refile-target-table
10780 (org-refile-get-targets default-buffer excluded-entries)))
10781 (unless org-refile-target-table
10782 (error "No refile targets"))
10783 (let* ((prompt (concat prompt
10784 (and (car org-refile-history)
10785 (concat " (default " (car org-refile-history) ")"))
10786 ": "))
10787 (cbuf (current-buffer))
10788 (partial-completion-mode nil)
10789 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10790 (cfunc (if (and org-refile-use-outline-path
10791 org-outline-path-complete-in-steps)
10792 'org-olpath-completing-read
10793 'org-icompleting-read))
10794 (extra (if org-refile-use-outline-path "/" ""))
10795 (filename (and cfn (expand-file-name cfn)))
10796 (tbl (mapcar
10797 (lambda (x)
10798 (if (and (not (member org-refile-use-outline-path
10799 '(file full-file-path)))
10800 (not (equal filename (nth 1 x))))
10801 (cons (concat (car x) extra " ("
10802 (file-name-nondirectory (nth 1 x)) ")")
10803 (cdr x))
10804 (cons (concat (car x) extra) (cdr x))))
10805 org-refile-target-table))
10806 (completion-ignore-case t)
10807 pa answ parent-target child parent old-hist)
10808 (setq old-hist org-refile-history)
10809 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10810 nil 'org-refile-history (car org-refile-history)))
10811 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10812 (org-refile-check-position pa)
10813 (if pa
10814 (progn
10815 (when (or (not org-refile-history)
10816 (not (eq old-hist org-refile-history))
10817 (not (equal (car pa) (car org-refile-history))))
10818 (setq org-refile-history
10819 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10820 org-refile-history
10821 (cdr org-refile-history))))
10822 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10823 (pop org-refile-history)))
10825 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10826 (progn
10827 (setq parent (match-string 1 answ)
10828 child (match-string 2 answ))
10829 (setq parent-target (or (assoc parent tbl)
10830 (assoc (concat parent "/") tbl)))
10831 (when (and parent-target
10832 (or (eq new-nodes t)
10833 (and (eq new-nodes 'confirm)
10834 (y-or-n-p (format "Create new node \"%s\"? "
10835 child)))))
10836 (org-refile-new-child parent-target child)))
10837 (error "Invalid target location")))))
10839 (defun org-refile-check-position (refile-pointer)
10840 "Check if the refile pointer matches the readline to which it points."
10841 (let* ((file (nth 1 refile-pointer))
10842 (re (nth 2 refile-pointer))
10843 (pos (nth 3 refile-pointer))
10844 buffer)
10845 (when (org-string-nw-p re)
10846 (setq buffer (if (markerp pos)
10847 (marker-buffer pos)
10848 (or (find-buffer-visiting file)
10849 (find-file-noselect file))))
10850 (with-current-buffer buffer
10851 (save-excursion
10852 (save-restriction
10853 (widen)
10854 (goto-char pos)
10855 (beginning-of-line 1)
10856 (unless (org-looking-at-p re)
10857 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10859 (defun org-refile-new-child (parent-target child)
10860 "Use refile target PARENT-TARGET to add new CHILD below it."
10861 (unless parent-target
10862 (error "Cannot find parent for new node"))
10863 (let ((file (nth 1 parent-target))
10864 (pos (nth 3 parent-target))
10865 level)
10866 (with-current-buffer (or (find-buffer-visiting file)
10867 (find-file-noselect file))
10868 (save-excursion
10869 (save-restriction
10870 (widen)
10871 (if pos
10872 (goto-char pos)
10873 (goto-char (point-max))
10874 (if (not (bolp)) (newline)))
10875 (when (looking-at org-outline-regexp)
10876 (setq level (funcall outline-level))
10877 (org-end-of-subtree t t))
10878 (org-back-over-empty-lines)
10879 (insert "\n" (make-string
10880 (if pos (org-get-valid-level level 1) 1) ?*)
10881 " " child "\n")
10882 (beginning-of-line 0)
10883 (list (concat (car parent-target) "/" child) file "" (point)))))))
10885 (defun org-olpath-completing-read (prompt collection &rest args)
10886 "Read an outline path like a file name."
10887 (let ((thetable collection)
10888 (org-completion-use-ido nil) ; does not work with ido.
10889 (org-completion-use-iswitchb nil)) ; or iswitchb
10890 (apply
10891 'org-icompleting-read prompt
10892 (lambda (string predicate &optional flag)
10893 (let (rtn r f (l (length string)))
10894 (cond
10895 ((eq flag nil)
10896 ;; try completion
10897 (try-completion string thetable))
10898 ((eq flag t)
10899 ;; all-completions
10900 (setq rtn (all-completions string thetable predicate))
10901 (mapcar
10902 (lambda (x)
10903 (setq r (substring x l))
10904 (if (string-match " ([^)]*)$" x)
10905 (setq f (match-string 0 x))
10906 (setq f ""))
10907 (if (string-match "/" r)
10908 (concat string (substring r 0 (match-end 0)) f)
10910 rtn))
10911 ((eq flag 'lambda)
10912 ;; exact match?
10913 (assoc string thetable)))
10915 args)))
10917 ;;;; Dynamic blocks
10919 (defun org-find-dblock (name)
10920 "Find the first dynamic block with name NAME in the buffer.
10921 If not found, stay at current position and return nil."
10922 (let (pos)
10923 (save-excursion
10924 (goto-char (point-min))
10925 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10926 nil t)
10927 (match-beginning 0))))
10928 (if pos (goto-char pos))
10929 pos))
10931 (defconst org-dblock-start-re
10932 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10933 "Matches the start line of a dynamic block, with parameters.")
10935 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10936 "Matches the end of a dynamic block.")
10938 (defun org-create-dblock (plist)
10939 "Create a dynamic block section, with parameters taken from PLIST.
10940 PLIST must contain a :name entry which is used as name of the block."
10941 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10942 (end-of-line 1)
10943 (newline))
10944 (let ((col (current-column))
10945 (name (plist-get plist :name)))
10946 (insert "#+BEGIN: " name)
10947 (while plist
10948 (if (eq (car plist) :name)
10949 (setq plist (cddr plist))
10950 (insert " " (prin1-to-string (pop plist)))))
10951 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10952 (beginning-of-line -2)))
10954 (defun org-prepare-dblock ()
10955 "Prepare dynamic block for refresh.
10956 This empties the block, puts the cursor at the insert position and returns
10957 the property list including an extra property :name with the block name."
10958 (unless (looking-at org-dblock-start-re)
10959 (error "Not at a dynamic block"))
10960 (let* ((begdel (1+ (match-end 0)))
10961 (name (org-no-properties (match-string 1)))
10962 (params (append (list :name name)
10963 (read (concat "(" (match-string 3) ")")))))
10964 (save-excursion
10965 (beginning-of-line 1)
10966 (skip-chars-forward " \t")
10967 (setq params (plist-put params :indentation-column (current-column))))
10968 (unless (re-search-forward org-dblock-end-re nil t)
10969 (error "Dynamic block not terminated"))
10970 (setq params
10971 (append params
10972 (list :content (buffer-substring
10973 begdel (match-beginning 0)))))
10974 (delete-region begdel (match-beginning 0))
10975 (goto-char begdel)
10976 (open-line 1)
10977 params))
10979 (defun org-map-dblocks (&optional command)
10980 "Apply COMMAND to all dynamic blocks in the current buffer.
10981 If COMMAND is not given, use `org-update-dblock'."
10982 (let ((cmd (or command 'org-update-dblock)))
10983 (save-excursion
10984 (goto-char (point-min))
10985 (while (re-search-forward org-dblock-start-re nil t)
10986 (goto-char (match-beginning 0))
10987 (save-excursion
10988 (condition-case nil
10989 (funcall cmd)
10990 (error (message "Error during update of dynamic block"))))
10991 (unless (re-search-forward org-dblock-end-re nil t)
10992 (error "Dynamic block not terminated"))))))
10994 (defun org-dblock-update (&optional arg)
10995 "User command for updating dynamic blocks.
10996 Update the dynamic block at point. With prefix ARG, update all dynamic
10997 blocks in the buffer."
10998 (interactive "P")
10999 (if arg
11000 (org-update-all-dblocks)
11001 (or (looking-at org-dblock-start-re)
11002 (org-beginning-of-dblock))
11003 (org-update-dblock)))
11005 (defun org-update-dblock ()
11006 "Update the dynamic block at point.
11007 This means to empty the block, parse for parameters and then call
11008 the correct writing function."
11009 (interactive)
11010 (save-window-excursion
11011 (let* ((pos (point))
11012 (line (org-current-line))
11013 (params (org-prepare-dblock))
11014 (name (plist-get params :name))
11015 (indent (plist-get params :indentation-column))
11016 (cmd (intern (concat "org-dblock-write:" name))))
11017 (message "Updating dynamic block `%s' at line %d..." name line)
11018 (funcall cmd params)
11019 (message "Updating dynamic block `%s' at line %d...done" name line)
11020 (goto-char pos)
11021 (when (and indent (> indent 0))
11022 (setq indent (make-string indent ?\ ))
11023 (save-excursion
11024 (org-beginning-of-dblock)
11025 (forward-line 1)
11026 (while (not (looking-at org-dblock-end-re))
11027 (insert indent)
11028 (beginning-of-line 2))
11029 (when (looking-at org-dblock-end-re)
11030 (and (looking-at "[ \t]+")
11031 (replace-match ""))
11032 (insert indent)))))))
11034 (defun org-beginning-of-dblock ()
11035 "Find the beginning of the dynamic block at point.
11036 Error if there is no such block at point."
11037 (let ((pos (point))
11038 beg)
11039 (end-of-line 1)
11040 (if (and (re-search-backward org-dblock-start-re nil t)
11041 (setq beg (match-beginning 0))
11042 (re-search-forward org-dblock-end-re nil t)
11043 (> (match-end 0) pos))
11044 (goto-char beg)
11045 (goto-char pos)
11046 (error "Not in a dynamic block"))))
11048 (defun org-update-all-dblocks ()
11049 "Update all dynamic blocks in the buffer.
11050 This function can be used in a hook."
11051 (interactive)
11052 (when (eq major-mode 'org-mode)
11053 (org-map-dblocks 'org-update-dblock)))
11056 ;;;; Completion
11058 (defconst org-additional-option-like-keywords
11059 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11060 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11061 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11062 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11063 "BEGIN:" "END:"
11064 "ORGTBL" "TBLFM:" "TBLNAME:"
11065 "BEGIN_EXAMPLE" "END_EXAMPLE"
11066 "BEGIN_QUOTE" "END_QUOTE"
11067 "BEGIN_VERSE" "END_VERSE"
11068 "BEGIN_CENTER" "END_CENTER"
11069 "BEGIN_SRC" "END_SRC"
11070 "BEGIN_RESULT" "END_RESULT"
11071 "NAME:" "RESULTS:"
11072 "HEADER:" "HEADERS:"
11073 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11074 "CAPTION:" "LABEL:"
11075 "SETUPFILE:"
11076 "INCLUDE:"
11077 "BIND:"
11078 "MACRO:"))
11080 (defcustom org-structure-template-alist
11082 ("s" "#+begin_src ?\n\n#+end_src"
11083 "<src lang=\"?\">\n\n</src>")
11084 ("e" "#+begin_example\n?\n#+end_example"
11085 "<example>\n?\n</example>")
11086 ("q" "#+begin_quote\n?\n#+end_quote"
11087 "<quote>\n?\n</quote>")
11088 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11089 "<verse>\n?\n</verse>")
11090 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11091 "<center>\n?\n</center>")
11092 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11093 "<literal style=\"latex\">\n?\n</literal>")
11094 ("L" "#+latex: "
11095 "<literal style=\"latex\">?</literal>")
11096 ("h" "#+begin_html\n?\n#+end_html"
11097 "<literal style=\"html\">\n?\n</literal>")
11098 ("H" "#+html: "
11099 "<literal style=\"html\">?</literal>")
11100 ("a" "#+begin_ascii\n?\n#+end_ascii")
11101 ("A" "#+ascii: ")
11102 ("i" "#+index: ?"
11103 "#+index: ?")
11104 ("I" "#+include %file ?"
11105 "<include file=%file markup=\"?\">")
11107 "Structure completion elements.
11108 This is a list of abbreviation keys and values. The value gets inserted
11109 if you type `<' followed by the key and then press the completion key,
11110 usually `M-TAB'. %file will be replaced by a file name after prompting
11111 for the file using completion. The cursor will be placed at the position
11112 of the `?` in the template.
11113 There are two templates for each key, the first uses the original Org syntax,
11114 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11115 the default when the /org-mtags.el/ module has been loaded. See also the
11116 variable `org-mtags-prefer-muse-templates'.
11117 This is an experimental feature, it is undecided if it is going to stay in."
11118 :group 'org-completion
11119 :type '(repeat
11120 (string :tag "Key")
11121 (string :tag "Template")
11122 (string :tag "Muse Template")))
11124 (defun org-try-structure-completion ()
11125 "Try to complete a structure template before point.
11126 This looks for strings like \"<e\" on an otherwise empty line and
11127 expands them."
11128 (let ((l (buffer-substring (point-at-bol) (point)))
11130 (when (and (looking-at "[ \t]*$")
11131 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11132 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11133 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11134 (match-beginning 1)) a)
11135 t)))
11137 (defun org-complete-expand-structure-template (start cell)
11138 "Expand a structure template."
11139 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11140 (rpl (nth (if musep 2 1) cell))
11141 (ind ""))
11142 (delete-region start (point))
11143 (when (string-match "\\`#\\+" rpl)
11144 (cond
11145 ((bolp))
11146 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11147 (setq ind (buffer-substring (point-at-bol) (point))))
11148 (t (newline))))
11149 (setq start (point))
11150 (if (string-match "%file" rpl)
11151 (setq rpl (replace-match
11152 (concat
11153 "\""
11154 (save-match-data
11155 (abbreviate-file-name (read-file-name "Include file: ")))
11156 "\"")
11157 t t rpl)))
11158 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11159 (concat "\n" ind)))
11160 (insert rpl)
11161 (if (re-search-backward "\\?" start t) (delete-char 1))))
11163 ;;;; TODO, DEADLINE, Comments
11165 (defun org-toggle-comment ()
11166 "Change the COMMENT state of an entry."
11167 (interactive)
11168 (save-excursion
11169 (org-back-to-heading)
11170 (let (case-fold-search)
11171 (cond
11172 ((looking-at (format org-heading-keyword-regexp-format
11173 org-comment-string))
11174 (goto-char (match-end 1))
11175 (looking-at (concat " +" org-comment-string))
11176 (replace-match "" t t)
11177 (when (eolp) (insert " ")))
11178 ((looking-at org-outline-regexp)
11179 (goto-char (match-end 0))
11180 (insert org-comment-string " "))))))
11182 (defvar org-last-todo-state-is-todo nil
11183 "This is non-nil when the last TODO state change led to a TODO state.
11184 If the last change removed the TODO tag or switched to DONE, then
11185 this is nil.")
11187 (defvar org-setting-tags nil) ; dynamically skipped
11189 (defvar org-todo-setup-filter-hook nil
11190 "Hook for functions that pre-filter todo specs.
11191 Each function takes a todo spec and returns either nil or the spec
11192 transformed into canonical form." )
11194 (defvar org-todo-get-default-hook nil
11195 "Hook for functions that get a default item for todo.
11196 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11197 nil or a string to be used for the todo mark." )
11199 (defvar org-agenda-headline-snapshot-before-repeat)
11201 (defun org-current-effective-time ()
11202 "Return current time adjusted for `org-extend-today-until' variable"
11203 (let* ((ct (org-current-time))
11204 (dct (decode-time ct))
11205 (ct1
11206 (if (and org-use-effective-time
11207 (< (nth 2 dct) org-extend-today-until))
11208 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11209 ct)))
11210 ct1))
11212 (defun org-todo-yesterday (&optional arg)
11213 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11214 (interactive "P")
11215 (if (eq major-mode 'org-agenda-mode)
11216 (apply 'org-agenda-todo-yesterday arg)
11217 (let* ((hour (third (decode-time
11218 (org-current-time))))
11219 (org-extend-today-until (1+ hour)))
11220 (org-todo arg))))
11222 (defun org-todo (&optional arg)
11223 "Change the TODO state of an item.
11224 The state of an item is given by a keyword at the start of the heading,
11225 like
11226 *** TODO Write paper
11227 *** DONE Call mom
11229 The different keywords are specified in the variable `org-todo-keywords'.
11230 By default the available states are \"TODO\" and \"DONE\".
11231 So for this example: when the item starts with TODO, it is changed to DONE.
11232 When it starts with DONE, the DONE is removed. And when neither TODO nor
11233 DONE are present, add TODO at the beginning of the heading.
11235 With \\[universal-argument] prefix arg, use completion to determine the new \
11236 state.
11237 With numeric prefix arg, switch to that state.
11238 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11239 keywords (nextset).
11240 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11241 With a numeric prefix arg of 0, inhibit note taking for the change.
11243 For calling through lisp, arg is also interpreted in the following way:
11244 'none -> empty state
11245 \"\"(empty string) -> switch to empty state
11246 'done -> switch to DONE
11247 'nextset -> switch to the next set of keywords
11248 'previousset -> switch to the previous set of keywords
11249 \"WAITING\" -> switch to the specified keyword, but only if it
11250 really is a member of `org-todo-keywords'."
11251 (interactive "P")
11252 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11253 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11254 'region-start-level 'region))
11255 org-loop-over-headlines-in-active-region)
11256 (org-map-entries
11257 `(org-todo ,arg)
11258 org-loop-over-headlines-in-active-region
11259 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11260 (if (equal arg '(16)) (setq arg 'nextset))
11261 (let ((org-blocker-hook org-blocker-hook)
11262 (case-fold-search nil))
11263 (when (equal arg '(64))
11264 (setq arg nil org-blocker-hook nil))
11265 (when (and org-blocker-hook
11266 (or org-inhibit-blocking
11267 (org-entry-get nil "NOBLOCKING")))
11268 (setq org-blocker-hook nil))
11269 (save-excursion
11270 (catch 'exit
11271 (org-back-to-heading t)
11272 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11273 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11274 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11275 (let* ((match-data (match-data))
11276 (startpos (point-at-bol))
11277 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11278 (org-log-done org-log-done)
11279 (org-log-repeat org-log-repeat)
11280 (org-todo-log-states org-todo-log-states)
11281 (org-inhibit-logging
11282 (if (equal arg 0)
11283 (progn (setq arg nil) 'note) org-inhibit-logging))
11284 (this (match-string 1))
11285 (hl-pos (match-beginning 0))
11286 (head (org-get-todo-sequence-head this))
11287 (ass (assoc head org-todo-kwd-alist))
11288 (interpret (nth 1 ass))
11289 (done-word (nth 3 ass))
11290 (final-done-word (nth 4 ass))
11291 (org-last-state (or this ""))
11292 (completion-ignore-case t)
11293 (member (member this org-todo-keywords-1))
11294 (tail (cdr member))
11295 (org-state (cond
11296 ((and org-todo-key-trigger
11297 (or (and (equal arg '(4))
11298 (eq org-use-fast-todo-selection 'prefix))
11299 (and (not arg) org-use-fast-todo-selection
11300 (not (eq org-use-fast-todo-selection
11301 'prefix)))))
11302 ;; Use fast selection
11303 (org-fast-todo-selection))
11304 ((and (equal arg '(4))
11305 (or (not org-use-fast-todo-selection)
11306 (not org-todo-key-trigger)))
11307 ;; Read a state with completion
11308 (org-icompleting-read
11309 "State: " (mapcar (lambda(x) (list x))
11310 org-todo-keywords-1)
11311 nil t))
11312 ((eq arg 'right)
11313 (if this
11314 (if tail (car tail) nil)
11315 (car org-todo-keywords-1)))
11316 ((eq arg 'left)
11317 (if (equal member org-todo-keywords-1)
11319 (if this
11320 (nth (- (length org-todo-keywords-1)
11321 (length tail) 2)
11322 org-todo-keywords-1)
11323 (org-last org-todo-keywords-1))))
11324 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11325 (setq arg nil))) ; hack to fall back to cycling
11326 (arg
11327 ;; user or caller requests a specific state
11328 (cond
11329 ((equal arg "") nil)
11330 ((eq arg 'none) nil)
11331 ((eq arg 'done) (or done-word (car org-done-keywords)))
11332 ((eq arg 'nextset)
11333 (or (car (cdr (member head org-todo-heads)))
11334 (car org-todo-heads)))
11335 ((eq arg 'previousset)
11336 (let ((org-todo-heads (reverse org-todo-heads)))
11337 (or (car (cdr (member head org-todo-heads)))
11338 (car org-todo-heads))))
11339 ((car (member arg org-todo-keywords-1)))
11340 ((stringp arg)
11341 (error "State `%s' not valid in this file" arg))
11342 ((nth (1- (prefix-numeric-value arg))
11343 org-todo-keywords-1))))
11344 ((null member) (or head (car org-todo-keywords-1)))
11345 ((equal this final-done-word) nil) ;; -> make empty
11346 ((null tail) nil) ;; -> first entry
11347 ((memq interpret '(type priority))
11348 (if (eq this-command last-command)
11349 (car tail)
11350 (if (> (length tail) 0)
11351 (or done-word (car org-done-keywords))
11352 nil)))
11354 (car tail))))
11355 (org-state (or
11356 (run-hook-with-args-until-success
11357 'org-todo-get-default-hook org-state org-last-state)
11358 org-state))
11359 (next (if org-state (concat " " org-state " ") " "))
11360 (change-plist (list :type 'todo-state-change :from this :to org-state
11361 :position startpos))
11362 dolog now-done-p)
11363 (when org-blocker-hook
11364 (setq org-last-todo-state-is-todo
11365 (not (member this org-done-keywords)))
11366 (unless (save-excursion
11367 (save-match-data
11368 (org-with-wide-buffer
11369 (run-hook-with-args-until-failure
11370 'org-blocker-hook change-plist))))
11371 (if (org-called-interactively-p 'interactive)
11372 (error "TODO state change from %s to %s blocked" this org-state)
11373 ;; fail silently
11374 (message "TODO state change from %s to %s blocked" this org-state)
11375 (throw 'exit nil))))
11376 (store-match-data match-data)
11377 (replace-match next t t)
11378 (unless (pos-visible-in-window-p hl-pos)
11379 (message "TODO state changed to %s" (org-trim next)))
11380 (unless head
11381 (setq head (org-get-todo-sequence-head org-state)
11382 ass (assoc head org-todo-kwd-alist)
11383 interpret (nth 1 ass)
11384 done-word (nth 3 ass)
11385 final-done-word (nth 4 ass)))
11386 (when (memq arg '(nextset previousset))
11387 (message "Keyword-Set %d/%d: %s"
11388 (- (length org-todo-sets) -1
11389 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11390 (length org-todo-sets)
11391 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11392 (setq org-last-todo-state-is-todo
11393 (not (member org-state org-done-keywords)))
11394 (setq now-done-p (and (member org-state org-done-keywords)
11395 (not (member this org-done-keywords))))
11396 (and logging (org-local-logging logging))
11397 (when (and (or org-todo-log-states org-log-done)
11398 (not (eq org-inhibit-logging t))
11399 (not (memq arg '(nextset previousset))))
11400 ;; we need to look at recording a time and note
11401 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11402 (nth 2 (assoc this org-todo-log-states))))
11403 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11404 (setq dolog 'time))
11405 (when (and org-state
11406 (member org-state org-not-done-keywords)
11407 (not (member this org-not-done-keywords)))
11408 ;; This is now a todo state and was not one before
11409 ;; If there was a CLOSED time stamp, get rid of it.
11410 (org-add-planning-info nil nil 'closed))
11411 (when (and now-done-p org-log-done)
11412 ;; It is now done, and it was not done before
11413 (org-add-planning-info 'closed (org-current-effective-time))
11414 (if (and (not dolog) (eq 'note org-log-done))
11415 (org-add-log-setup 'done org-state this 'findpos 'note)))
11416 (when (and org-state dolog)
11417 ;; This is a non-nil state, and we need to log it
11418 (org-add-log-setup 'state org-state this 'findpos dolog)))
11419 ;; Fixup tag positioning
11420 (org-todo-trigger-tag-changes org-state)
11421 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11422 (when org-provide-todo-statistics
11423 (org-update-parent-todo-statistics))
11424 (run-hooks 'org-after-todo-state-change-hook)
11425 (if (and arg (not (member org-state org-done-keywords)))
11426 (setq head (org-get-todo-sequence-head org-state)))
11427 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11428 ;; Do we need to trigger a repeat?
11429 (when now-done-p
11430 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11431 ;; This is for the agenda, take a snapshot of the headline.
11432 (save-match-data
11433 (setq org-agenda-headline-snapshot-before-repeat
11434 (org-get-heading))))
11435 (org-auto-repeat-maybe org-state))
11436 ;; Fixup cursor location if close to the keyword
11437 (if (and (outline-on-heading-p)
11438 (not (bolp))
11439 (save-excursion (beginning-of-line 1)
11440 (looking-at org-todo-line-regexp))
11441 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11442 (progn
11443 (goto-char (or (match-end 2) (match-end 1)))
11444 (and (looking-at " ") (just-one-space))))
11445 (when org-trigger-hook
11446 (save-excursion
11447 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11449 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11450 "Block turning an entry into a TODO, using the hierarchy.
11451 This checks whether the current task should be blocked from state
11452 changes. Such blocking occurs when:
11454 1. The task has children which are not all in a completed state.
11456 2. A task has a parent with the property :ORDERED:, and there
11457 are siblings prior to the current task with incomplete
11458 status.
11460 3. The parent of the task is blocked because it has siblings that should
11461 be done first, or is child of a block grandparent TODO entry."
11463 (if (not org-enforce-todo-dependencies)
11464 t ; if locally turned off don't block
11465 (catch 'dont-block
11466 ;; If this is not a todo state change, or if this entry is already DONE,
11467 ;; do not block
11468 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11469 (member (plist-get change-plist :from)
11470 (cons 'done org-done-keywords))
11471 (member (plist-get change-plist :to)
11472 (cons 'todo org-not-done-keywords))
11473 (not (plist-get change-plist :to)))
11474 (throw 'dont-block t))
11475 ;; If this task has children, and any are undone, it's blocked
11476 (save-excursion
11477 (org-back-to-heading t)
11478 (let ((this-level (funcall outline-level)))
11479 (outline-next-heading)
11480 (let ((child-level (funcall outline-level)))
11481 (while (and (not (eobp))
11482 (> child-level this-level))
11483 ;; this todo has children, check whether they are all
11484 ;; completed
11485 (if (and (not (org-entry-is-done-p))
11486 (org-entry-is-todo-p))
11487 (throw 'dont-block nil))
11488 (outline-next-heading)
11489 (setq child-level (funcall outline-level))))))
11490 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11491 ;; any previous siblings are undone, it's blocked
11492 (save-excursion
11493 (org-back-to-heading t)
11494 (let* ((pos (point))
11495 (parent-pos (and (org-up-heading-safe) (point))))
11496 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11497 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11498 (forward-line 1)
11499 (re-search-forward org-not-done-heading-regexp pos t))
11500 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11501 ;; Search further up the hierarchy, to see if an ancestor is blocked
11502 (while t
11503 (goto-char parent-pos)
11504 (if (not (looking-at org-not-done-heading-regexp))
11505 (throw 'dont-block t)) ; do not block, parent is not a TODO
11506 (setq pos (point))
11507 (setq parent-pos (and (org-up-heading-safe) (point)))
11508 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11509 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11510 (forward-line 1)
11511 (re-search-forward org-not-done-heading-regexp pos t))
11512 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11514 (defcustom org-track-ordered-property-with-tag nil
11515 "Should the ORDERED property also be shown as a tag?
11516 The ORDERED property decides if an entry should require subtasks to be
11517 completed in sequence. Since a property is not very visible, setting
11518 this option means that toggling the ORDERED property with the command
11519 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11520 not relevant for the behavior, but it makes things more visible.
11522 Note that toggling the tag with tags commands will not change the property
11523 and therefore not influence behavior!
11525 This can be t, meaning the tag ORDERED should be used, It can also be a
11526 string to select a different tag for this task."
11527 :group 'org-todo
11528 :type '(choice
11529 (const :tag "No tracking" nil)
11530 (const :tag "Track with ORDERED tag" t)
11531 (string :tag "Use other tag")))
11533 (defun org-toggle-ordered-property ()
11534 "Toggle the ORDERED property of the current entry.
11535 For better visibility, you can track the value of this property with a tag.
11536 See variable `org-track-ordered-property-with-tag'."
11537 (interactive)
11538 (let* ((t1 org-track-ordered-property-with-tag)
11539 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11540 (save-excursion
11541 (org-back-to-heading)
11542 (if (org-entry-get nil "ORDERED")
11543 (progn
11544 (org-delete-property "ORDERED")
11545 (and tag (org-toggle-tag tag 'off))
11546 (message "Subtasks can be completed in arbitrary order"))
11547 (org-entry-put nil "ORDERED" "t")
11548 (and tag (org-toggle-tag tag 'on))
11549 (message "Subtasks must be completed in sequence")))))
11551 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11552 (defun org-block-todo-from-checkboxes (change-plist)
11553 "Block turning an entry into a TODO, using checkboxes.
11554 This checks whether the current task should be blocked from state
11555 changes because there are unchecked boxes in this entry."
11556 (if (not org-enforce-todo-checkbox-dependencies)
11557 t ; if locally turned off don't block
11558 (catch 'dont-block
11559 ;; If this is not a todo state change, or if this entry is already DONE,
11560 ;; do not block
11561 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11562 (member (plist-get change-plist :from)
11563 (cons 'done org-done-keywords))
11564 (member (plist-get change-plist :to)
11565 (cons 'todo org-not-done-keywords))
11566 (not (plist-get change-plist :to)))
11567 (throw 'dont-block t))
11568 ;; If this task has checkboxes that are not checked, it's blocked
11569 (save-excursion
11570 (org-back-to-heading t)
11571 (let ((beg (point)) end)
11572 (outline-next-heading)
11573 (setq end (point))
11574 (goto-char beg)
11575 (if (org-list-search-forward
11576 (concat (org-item-beginning-re)
11577 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11578 "\\[[- ]\\]")
11579 end t)
11580 (progn
11581 (if (boundp 'org-blocked-by-checkboxes)
11582 (setq org-blocked-by-checkboxes t))
11583 (throw 'dont-block nil)))))
11584 t))) ; do not block
11586 (defun org-entry-blocked-p ()
11587 "Is the current entry blocked?"
11588 (if (org-entry-get nil "NOBLOCKING")
11589 nil ;; Never block this entry
11590 (not
11591 (run-hook-with-args-until-failure
11592 'org-blocker-hook
11593 (list :type 'todo-state-change
11594 :position (point)
11595 :from 'todo
11596 :to 'done)))))
11598 (defun org-update-statistics-cookies (all)
11599 "Update the statistics cookie, either from TODO or from checkboxes.
11600 This should be called with the cursor in a line with a statistics cookie."
11601 (interactive "P")
11602 (if all
11603 (progn
11604 (org-update-checkbox-count 'all)
11605 (org-map-entries 'org-update-parent-todo-statistics))
11606 (if (not (org-at-heading-p))
11607 (org-update-checkbox-count)
11608 (let ((pos (move-marker (make-marker) (point)))
11609 end l1 l2)
11610 (ignore-errors (org-back-to-heading t))
11611 (if (not (org-at-heading-p))
11612 (org-update-checkbox-count)
11613 (setq l1 (org-outline-level))
11614 (setq end (save-excursion
11615 (outline-next-heading)
11616 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11617 (point)))
11618 (if (and (save-excursion
11619 (re-search-forward
11620 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11621 (not (save-excursion (re-search-forward
11622 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11623 (org-update-checkbox-count)
11624 (if (and l2 (> l2 l1))
11625 (progn
11626 (goto-char end)
11627 (org-update-parent-todo-statistics))
11628 (goto-char pos)
11629 (beginning-of-line 1)
11630 (while (re-search-forward
11631 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11632 (point-at-eol) t)
11633 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11634 (goto-char pos)
11635 (move-marker pos nil)))))
11637 (defvar org-entry-property-inherited-from) ;; defined below
11638 (defun org-update-parent-todo-statistics ()
11639 "Update any statistics cookie in the parent of the current headline.
11640 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11641 the entire subtree and this will travel up the hierarchy and update
11642 statistics everywhere."
11643 (let* ((prop (save-excursion (org-up-heading-safe)
11644 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11645 (recursive (or (not org-hierarchical-todo-statistics)
11646 (and prop (string-match "\\<recursive\\>" prop))))
11647 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11649 (first t)
11650 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11651 level ltoggle l1 new ndel
11652 (cnt-all 0) (cnt-done 0) is-percent kwd
11653 checkbox-beg ov ovs ove cookie-present)
11654 (catch 'exit
11655 (save-excursion
11656 (beginning-of-line 1)
11657 (setq ltoggle (funcall outline-level))
11658 ;; Three situations are to consider:
11660 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11661 ;; to the top-level ancestor on the headline;
11663 ;; 2. If parent has "recursive" property, repeat up to the
11664 ;; headline setting that property, taking inheritance into
11665 ;; account;
11667 ;; 3. Else, move up to direct parent and proceed only once.
11668 (while (and (setq level (org-up-heading-safe))
11669 (or recursive first)
11670 (>= (point) lim))
11671 (setq first nil cookie-present nil)
11672 (unless (and level
11673 (not (string-match
11674 "\\<checkbox\\>"
11675 (downcase (or (org-entry-get nil "COOKIE_DATA")
11676 "")))))
11677 (throw 'exit nil))
11678 (while (re-search-forward box-re (point-at-eol) t)
11679 (setq cnt-all 0 cnt-done 0 cookie-present t)
11680 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11681 (save-match-data
11682 (unless (outline-next-heading) (throw 'exit nil))
11683 (while (and (looking-at org-complex-heading-regexp)
11684 (> (setq l1 (length (match-string 1))) level))
11685 (setq kwd (and (or recursive (= l1 ltoggle))
11686 (match-string 2)))
11687 (if (or (eq org-provide-todo-statistics 'all-headlines)
11688 (and (listp org-provide-todo-statistics)
11689 (or (member kwd org-provide-todo-statistics)
11690 (member kwd org-done-keywords))))
11691 (setq cnt-all (1+ cnt-all))
11692 (if (eq org-provide-todo-statistics t)
11693 (and kwd (setq cnt-all (1+ cnt-all)))))
11694 (and (member kwd org-done-keywords)
11695 (setq cnt-done (1+ cnt-done)))
11696 (outline-next-heading)))
11697 (setq new
11698 (if is-percent
11699 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11700 (format "[%d/%d]" cnt-done cnt-all))
11701 ndel (- (match-end 0) checkbox-beg))
11702 ;; handle overlays when updating cookie from column view
11703 (when (setq ov (car (overlays-at checkbox-beg)))
11704 (setq ovs (overlay-start ov) ove (overlay-end ov))
11705 (delete-overlay ov))
11706 (goto-char checkbox-beg)
11707 (insert new)
11708 (delete-region (point) (+ (point) ndel))
11709 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11710 (when ov (move-overlay ov ovs ove)))
11711 (when cookie-present
11712 (run-hook-with-args 'org-after-todo-statistics-hook
11713 cnt-done (- cnt-all cnt-done))))))
11714 (run-hooks 'org-todo-statistics-hook)))
11716 (defvar org-after-todo-statistics-hook nil
11717 "Hook that is called after a TODO statistics cookie has been updated.
11718 Each function is called with two arguments: the number of not-done entries
11719 and the number of done entries.
11721 For example, the following function, when added to this hook, will switch
11722 an entry to DONE when all children are done, and back to TODO when new
11723 entries are set to a TODO status. Note that this hook is only called
11724 when there is a statistics cookie in the headline!
11726 (defun org-summary-todo (n-done n-not-done)
11727 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11728 (let (org-log-done org-log-states) ; turn off logging
11729 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11732 (defvar org-todo-statistics-hook nil
11733 "Hook that is run whenever Org thinks TODO statistics should be updated.
11734 This hook runs even if there is no statistics cookie present, in which case
11735 `org-after-todo-statistics-hook' would not run.")
11737 (defun org-todo-trigger-tag-changes (state)
11738 "Apply the changes defined in `org-todo-state-tags-triggers'."
11739 (let ((l org-todo-state-tags-triggers)
11740 changes)
11741 (when (or (not state) (equal state ""))
11742 (setq changes (append changes (cdr (assoc "" l)))))
11743 (when (and (stringp state) (> (length state) 0))
11744 (setq changes (append changes (cdr (assoc state l)))))
11745 (when (member state org-not-done-keywords)
11746 (setq changes (append changes (cdr (assoc 'todo l)))))
11747 (when (member state org-done-keywords)
11748 (setq changes (append changes (cdr (assoc 'done l)))))
11749 (dolist (c changes)
11750 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11752 (defun org-local-logging (value)
11753 "Get logging settings from a property VALUE."
11754 (let* (words w a)
11755 ;; directly set the variables, they are already local.
11756 (setq org-log-done nil
11757 org-log-repeat nil
11758 org-todo-log-states nil)
11759 (setq words (org-split-string value))
11760 (while (setq w (pop words))
11761 (cond
11762 ((setq a (assoc w org-startup-options))
11763 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11764 (set (nth 1 a) (nth 2 a))))
11765 ((setq a (org-extract-log-state-settings w))
11766 (and (member (car a) org-todo-keywords-1)
11767 (push a org-todo-log-states)))))))
11769 (defun org-get-todo-sequence-head (kwd)
11770 "Return the head of the TODO sequence to which KWD belongs.
11771 If KWD is not set, check if there is a text property remembering the
11772 right sequence."
11773 (let (p)
11774 (cond
11775 ((not kwd)
11776 (or (get-text-property (point-at-bol) 'org-todo-head)
11777 (progn
11778 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11779 nil (point-at-eol)))
11780 (get-text-property p 'org-todo-head))))
11781 ((not (member kwd org-todo-keywords-1))
11782 (car org-todo-keywords-1))
11783 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11785 (defun org-fast-todo-selection ()
11786 "Fast TODO keyword selection with single keys.
11787 Returns the new TODO keyword, or nil if no state change should occur."
11788 (let* ((fulltable org-todo-key-alist)
11789 (done-keywords org-done-keywords) ;; needed for the faces.
11790 (maxlen (apply 'max (mapcar
11791 (lambda (x)
11792 (if (stringp (car x)) (string-width (car x)) 0))
11793 fulltable)))
11794 (expert nil)
11795 (fwidth (+ maxlen 3 1 3))
11796 (ncol (/ (- (window-width) 4) fwidth))
11797 tg cnt e c tbl
11798 groups ingroup)
11799 (save-excursion
11800 (save-window-excursion
11801 (if expert
11802 (set-buffer (get-buffer-create " *Org todo*"))
11803 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11804 (erase-buffer)
11805 (org-set-local 'org-done-keywords done-keywords)
11806 (setq tbl fulltable cnt 0)
11807 (while (setq e (pop tbl))
11808 (cond
11809 ((equal e '(:startgroup))
11810 (push '() groups) (setq ingroup t)
11811 (when (not (= cnt 0))
11812 (setq cnt 0)
11813 (insert "\n"))
11814 (insert "{ "))
11815 ((equal e '(:endgroup))
11816 (setq ingroup nil cnt 0)
11817 (insert "}\n"))
11818 ((equal e '(:newline))
11819 (when (not (= cnt 0))
11820 (setq cnt 0)
11821 (insert "\n")
11822 (setq e (car tbl))
11823 (while (equal (car tbl) '(:newline))
11824 (insert "\n")
11825 (setq tbl (cdr tbl)))))
11827 (setq tg (car e) c (cdr e))
11828 (if ingroup (push tg (car groups)))
11829 (setq tg (org-add-props tg nil 'face
11830 (org-get-todo-face tg)))
11831 (if (and (= cnt 0) (not ingroup)) (insert " "))
11832 (insert "[" c "] " tg (make-string
11833 (- fwidth 4 (length tg)) ?\ ))
11834 (when (= (setq cnt (1+ cnt)) ncol)
11835 (insert "\n")
11836 (if ingroup (insert " "))
11837 (setq cnt 0)))))
11838 (insert "\n")
11839 (goto-char (point-min))
11840 (if (not expert) (org-fit-window-to-buffer))
11841 (message "[a-z..]:Set [SPC]:clear")
11842 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11843 (cond
11844 ((or (= c ?\C-g)
11845 (and (= c ?q) (not (rassoc c fulltable))))
11846 (setq quit-flag t))
11847 ((= c ?\ ) nil)
11848 ((setq e (rassoc c fulltable) tg (car e))
11850 (t (setq quit-flag t)))))))
11852 (defun org-entry-is-todo-p ()
11853 (member (org-get-todo-state) org-not-done-keywords))
11855 (defun org-entry-is-done-p ()
11856 (member (org-get-todo-state) org-done-keywords))
11858 (defun org-get-todo-state ()
11859 (save-excursion
11860 (org-back-to-heading t)
11861 (and (looking-at org-todo-line-regexp)
11862 (match-end 2)
11863 (match-string 2))))
11865 (defun org-at-date-range-p (&optional inactive-ok)
11866 "Is the cursor inside a date range?"
11867 (interactive)
11868 (save-excursion
11869 (catch 'exit
11870 (let ((pos (point)))
11871 (skip-chars-backward "^[<\r\n")
11872 (skip-chars-backward "<[")
11873 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11874 (>= (match-end 0) pos)
11875 (throw 'exit t))
11876 (skip-chars-backward "^<[\r\n")
11877 (skip-chars-backward "<[")
11878 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11879 (>= (match-end 0) pos)
11880 (throw 'exit t)))
11881 nil)))
11883 (defun org-get-repeat (&optional tagline)
11884 "Check if there is a deadline/schedule with repeater in this entry."
11885 (save-match-data
11886 (save-excursion
11887 (org-back-to-heading t)
11888 (and (re-search-forward (if tagline
11889 (concat tagline "\\s-*" org-repeat-re)
11890 org-repeat-re)
11891 (org-entry-end-position) t)
11892 (match-string-no-properties 1)))))
11894 (defvar org-last-changed-timestamp)
11895 (defvar org-last-inserted-timestamp)
11896 (defvar org-log-post-message)
11897 (defvar org-log-note-purpose)
11898 (defvar org-log-note-how)
11899 (defvar org-log-note-extra)
11900 (defun org-auto-repeat-maybe (done-word)
11901 "Check if the current headline contains a repeated deadline/schedule.
11902 If yes, set TODO state back to what it was and change the base date
11903 of repeating deadline/scheduled time stamps to new date.
11904 This function is run automatically after each state change to a DONE state."
11905 ;; last-state is dynamically scoped into this function
11906 (let* ((repeat (org-get-repeat))
11907 (aa (assoc org-last-state org-todo-kwd-alist))
11908 (interpret (nth 1 aa))
11909 (head (nth 2 aa))
11910 (whata '(("d" . day) ("m" . month) ("y" . year)))
11911 (msg "Entry repeats: ")
11912 (org-log-done nil)
11913 (org-todo-log-states nil)
11914 re type n what ts time to-state)
11915 (when repeat
11916 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11917 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11918 org-todo-repeat-to-state))
11919 (unless (and to-state (member to-state org-todo-keywords-1))
11920 (setq to-state (if (eq interpret 'type) org-last-state head)))
11921 (org-todo to-state)
11922 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11923 (org-entry-put nil "LAST_REPEAT" (format-time-string
11924 (org-time-stamp-format t t))))
11925 (when org-log-repeat
11926 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11927 (memq 'org-add-log-note post-command-hook))
11928 ;; OK, we are already setup for some record
11929 (if (eq org-log-repeat 'note)
11930 ;; make sure we take a note, not only a time stamp
11931 (setq org-log-note-how 'note))
11932 ;; Set up for taking a record
11933 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11934 org-last-state
11935 'findpos org-log-repeat)))
11936 (org-back-to-heading t)
11937 (org-add-planning-info nil nil 'closed)
11938 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11939 org-deadline-time-regexp "\\)\\|\\("
11940 org-ts-regexp "\\)"))
11941 (while (re-search-forward
11942 re (save-excursion (outline-next-heading) (point)) t)
11943 (setq type (if (match-end 1) org-scheduled-string
11944 (if (match-end 3) org-deadline-string "Plain:"))
11945 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11946 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11947 (setq n (string-to-number (match-string 2 ts))
11948 what (match-string 3 ts))
11949 (if (equal what "w") (setq n (* n 7) what "d"))
11950 ;; Preparation, see if we need to modify the start date for the change
11951 (when (match-end 1)
11952 (setq time (save-match-data (org-time-string-to-time ts)))
11953 (cond
11954 ((equal (match-string 1 ts) ".")
11955 ;; Shift starting date to today
11956 (org-timestamp-change
11957 (- (org-today) (time-to-days time))
11958 'day))
11959 ((equal (match-string 1 ts) "+")
11960 (let ((nshiftmax 10) (nshift 0))
11961 (while (or (= nshift 0)
11962 (<= (time-to-days time)
11963 (time-to-days (current-time))))
11964 (when (= (incf nshift) nshiftmax)
11965 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11966 (error "Abort")))
11967 (org-timestamp-change n (cdr (assoc what whata)))
11968 (org-at-timestamp-p t)
11969 (setq ts (match-string 1))
11970 (setq time (save-match-data (org-time-string-to-time ts)))))
11971 (org-timestamp-change (- n) (cdr (assoc what whata)))
11972 ;; rematch, so that we have everything in place for the real shift
11973 (org-at-timestamp-p t)
11974 (setq ts (match-string 1))
11975 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11976 (org-timestamp-change n (cdr (assoc what whata)))
11977 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11978 (setq org-log-post-message msg)
11979 (message "%s" msg))))
11981 (defun org-show-todo-tree (arg)
11982 "Make a compact tree which shows all headlines marked with TODO.
11983 The tree will show the lines where the regexp matches, and all higher
11984 headlines above the match.
11985 With a \\[universal-argument] prefix, prompt for a regexp to match.
11986 With a numeric prefix N, construct a sparse tree for the Nth element
11987 of `org-todo-keywords-1'."
11988 (interactive "P")
11989 (let ((case-fold-search nil)
11990 (kwd-re
11991 (cond ((null arg) org-not-done-regexp)
11992 ((equal arg '(4))
11993 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11994 (mapcar 'list org-todo-keywords-1))))
11995 (concat "\\("
11996 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11997 "\\)\\>")))
11998 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11999 (regexp-quote (nth (1- (prefix-numeric-value arg))
12000 org-todo-keywords-1)))
12001 (t (error "Invalid prefix argument: %s" arg)))))
12002 (message "%d TODO entries found"
12003 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12005 (defun org-deadline (&optional remove time)
12006 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12007 With argument REMOVE, remove any deadline from the item.
12008 With argument TIME, set the deadline at the corresponding date. TIME
12009 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12010 (interactive "P")
12011 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12012 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12013 'region-start-level 'region))
12014 org-loop-over-headlines-in-active-region)
12015 (org-map-entries
12016 `(org-deadline ',remove ,time)
12017 org-loop-over-headlines-in-active-region
12018 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12019 (let* ((old-date (org-entry-get nil "DEADLINE"))
12020 (repeater (and old-date
12021 (string-match
12022 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12023 old-date)
12024 (match-string 1 old-date))))
12025 (if remove
12026 (progn
12027 (when (and old-date org-log-redeadline)
12028 (org-add-log-setup 'deldeadline nil old-date 'findpos
12029 org-log-redeadline))
12030 (org-remove-timestamp-with-keyword org-deadline-string)
12031 (message "Item no longer has a deadline."))
12032 (org-add-planning-info 'deadline time 'closed)
12033 (when (and old-date org-log-redeadline
12034 (not (equal old-date
12035 (substring org-last-inserted-timestamp 1 -1))))
12036 (org-add-log-setup 'redeadline nil old-date 'findpos
12037 org-log-redeadline))
12038 (when repeater
12039 (save-excursion
12040 (org-back-to-heading t)
12041 (when (re-search-forward (concat org-deadline-string " "
12042 org-last-inserted-timestamp)
12043 (save-excursion
12044 (outline-next-heading) (point)) t)
12045 (goto-char (1- (match-end 0)))
12046 (insert " " repeater)
12047 (setq org-last-inserted-timestamp
12048 (concat (substring org-last-inserted-timestamp 0 -1)
12049 " " repeater
12050 (substring org-last-inserted-timestamp -1))))))
12051 (message "Deadline on %s" org-last-inserted-timestamp)))))
12053 (defun org-schedule (&optional remove time)
12054 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12055 With argument REMOVE, remove any scheduling date from the item.
12056 With argument TIME, scheduled at the corresponding date. TIME can
12057 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12058 (interactive "P")
12059 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12060 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12061 'region-start-level 'region))
12062 org-loop-over-headlines-in-active-region)
12063 (org-map-entries
12064 `(org-schedule ',remove ,time)
12065 org-loop-over-headlines-in-active-region
12066 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12067 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12068 (repeater (and old-date
12069 (string-match
12070 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12071 old-date)
12072 (match-string 1 old-date))))
12073 (if remove
12074 (progn
12075 (when (and old-date org-log-reschedule)
12076 (org-add-log-setup 'delschedule nil old-date 'findpos
12077 org-log-reschedule))
12078 (org-remove-timestamp-with-keyword org-scheduled-string)
12079 (message "Item is no longer scheduled."))
12080 (org-add-planning-info 'scheduled time 'closed)
12081 (when (and old-date org-log-reschedule
12082 (not (equal old-date
12083 (substring org-last-inserted-timestamp 1 -1))))
12084 (org-add-log-setup 'reschedule nil old-date 'findpos
12085 org-log-reschedule))
12086 (when repeater
12087 (save-excursion
12088 (org-back-to-heading t)
12089 (when (re-search-forward (concat org-scheduled-string " "
12090 org-last-inserted-timestamp)
12091 (save-excursion
12092 (outline-next-heading) (point)) t)
12093 (goto-char (1- (match-end 0)))
12094 (insert " " repeater)
12095 (setq org-last-inserted-timestamp
12096 (concat (substring org-last-inserted-timestamp 0 -1)
12097 " " repeater
12098 (substring org-last-inserted-timestamp -1))))))
12099 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12101 (defun org-get-scheduled-time (pom &optional inherit)
12102 "Get the scheduled time as a time tuple, of a format suitable
12103 for calling org-schedule with, or if there is no scheduling,
12104 returns nil."
12105 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12106 (when time
12107 (apply 'encode-time (org-parse-time-string time)))))
12109 (defun org-get-deadline-time (pom &optional inherit)
12110 "Get the deadline as a time tuple, of a format suitable for
12111 calling org-deadline with, or if there is no scheduling, returns
12112 nil."
12113 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12114 (when time
12115 (apply 'encode-time (org-parse-time-string time)))))
12117 (defun org-remove-timestamp-with-keyword (keyword)
12118 "Remove all time stamps with KEYWORD in the current entry."
12119 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12120 beg)
12121 (save-excursion
12122 (org-back-to-heading t)
12123 (setq beg (point))
12124 (outline-next-heading)
12125 (while (re-search-backward re beg t)
12126 (replace-match "")
12127 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12128 (equal (char-before) ?\ ))
12129 (backward-delete-char 1)
12130 (if (string-match "^[ \t]*$" (buffer-substring
12131 (point-at-bol) (point-at-eol)))
12132 (delete-region (point-at-bol)
12133 (min (point-max) (1+ (point-at-eol))))))))))
12135 (defun org-add-planning-info (what &optional time &rest remove)
12136 "Insert new timestamp with keyword in the line directly after the headline.
12137 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12138 If non is given, the user is prompted for a date.
12139 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12140 be removed."
12141 (interactive)
12142 (let (org-time-was-given org-end-time-was-given ts
12143 end default-time default-input)
12145 (catch 'exit
12146 (when (and (memq what '(scheduled deadline))
12147 (or (not time)
12148 (and (stringp time)
12149 (string-match "^[-+]+[0-9]" time))))
12150 ;; Try to get a default date/time from existing timestamp
12151 (save-excursion
12152 (org-back-to-heading t)
12153 (setq end (save-excursion (outline-next-heading) (point)))
12154 (when (re-search-forward (if (eq what 'scheduled)
12155 org-scheduled-time-regexp
12156 org-deadline-time-regexp)
12157 end t)
12158 (setq ts (match-string 1)
12159 default-time
12160 (apply 'encode-time (org-parse-time-string ts))
12161 default-input (and ts (org-get-compact-tod ts))))))
12162 (when what
12163 (setq time
12164 (if (stringp time)
12165 ;; This is a string (relative or absolute), set proper date
12166 (apply 'encode-time
12167 (org-read-date-analyze
12168 time default-time (decode-time default-time)))
12169 ;; If necessary, get the time from the user
12170 (or time (org-read-date nil 'to-time nil nil
12171 default-time default-input)))))
12173 (when (and org-insert-labeled-timestamps-at-point
12174 (member what '(scheduled deadline)))
12175 (insert
12176 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12177 (org-insert-time-stamp time org-time-was-given
12178 nil nil nil (list org-end-time-was-given))
12179 (setq what nil))
12180 (save-excursion
12181 (save-restriction
12182 (let (col list elt ts buffer-invisibility-spec)
12183 (org-back-to-heading t)
12184 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12185 (goto-char (match-end 1))
12186 (setq col (current-column))
12187 (goto-char (match-end 0))
12188 (if (eobp) (insert "\n") (forward-char 1))
12189 (when (and (not what)
12190 (not (looking-at
12191 (concat "[ \t]*"
12192 org-keyword-time-not-clock-regexp))))
12193 ;; Nothing to add, nothing to remove...... :-)
12194 (throw 'exit nil))
12195 (if (and (not (looking-at org-outline-regexp))
12196 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12197 "[^\r\n]*"))
12198 (not (equal (match-string 1) org-clock-string)))
12199 (narrow-to-region (match-beginning 0) (match-end 0))
12200 (insert-before-markers "\n")
12201 (backward-char 1)
12202 (narrow-to-region (point) (point))
12203 (and org-adapt-indentation (org-indent-to-column col)))
12204 ;; Check if we have to remove something.
12205 (setq list (cons what remove))
12206 (while list
12207 (setq elt (pop list))
12208 (when (or (and (eq elt 'scheduled)
12209 (re-search-forward org-scheduled-time-regexp nil t))
12210 (and (eq elt 'deadline)
12211 (re-search-forward org-deadline-time-regexp nil t))
12212 (and (eq elt 'closed)
12213 (re-search-forward org-closed-time-regexp nil t)))
12214 (replace-match "")
12215 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12216 (and (looking-at "[ \t]+") (replace-match ""))
12217 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12218 (when what
12219 (insert
12220 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12221 (cond ((eq what 'scheduled) org-scheduled-string)
12222 ((eq what 'deadline) org-deadline-string)
12223 ((eq what 'closed) org-closed-string))
12224 " ")
12225 (setq ts (org-insert-time-stamp
12226 time
12227 (or org-time-was-given
12228 (and (eq what 'closed) org-log-done-with-time))
12229 (eq what 'closed)
12230 nil nil (list org-end-time-was-given)))
12231 (insert
12232 (if (not (or (bolp) (eq (char-before) ?\ )
12233 (memq (char-after) '(32 10))
12234 (eobp))) " " ""))
12235 (end-of-line 1))
12236 (goto-char (point-min))
12237 (widen)
12238 (if (and (looking-at "[ \t]*\n")
12239 (equal (char-before) ?\n))
12240 (delete-region (1- (point)) (point-at-eol)))
12241 ts))))))
12243 (defvar org-log-note-marker (make-marker))
12244 (defvar org-log-note-purpose nil)
12245 (defvar org-log-note-state nil)
12246 (defvar org-log-note-previous-state nil)
12247 (defvar org-log-note-how nil)
12248 (defvar org-log-note-extra nil)
12249 (defvar org-log-note-window-configuration nil)
12250 (defvar org-log-note-return-to (make-marker))
12251 (defvar org-log-note-effective-time nil
12252 "Remembered current time so that dynamically scoped
12253 `org-extend-today-until' affects tha timestamps in state change
12254 log")
12256 (defvar org-log-post-message nil
12257 "Message to be displayed after a log note has been stored.
12258 The auto-repeater uses this.")
12260 (defun org-add-note ()
12261 "Add a note to the current entry.
12262 This is done in the same way as adding a state change note."
12263 (interactive)
12264 (org-add-log-setup 'note nil nil 'findpos nil))
12266 (defvar org-property-end-re)
12267 (defun org-add-log-setup (&optional purpose state prev-state
12268 findpos how extra)
12269 "Set up the post command hook to take a note.
12270 If this is about to TODO state change, the new state is expected in STATE.
12271 When FINDPOS is non-nil, find the correct position for the note in
12272 the current entry. If not, assume that it can be inserted at point.
12273 HOW is an indicator what kind of note should be created.
12274 EXTRA is additional text that will be inserted into the notes buffer."
12275 (let* ((org-log-into-drawer (org-log-into-drawer))
12276 (drawer (cond ((stringp org-log-into-drawer)
12277 org-log-into-drawer)
12278 (org-log-into-drawer "LOGBOOK")
12279 (t nil))))
12280 (save-restriction
12281 (save-excursion
12282 (when findpos
12283 (org-back-to-heading t)
12284 (narrow-to-region (point) (save-excursion
12285 (outline-next-heading) (point)))
12286 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12287 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12288 "[^\r\n]*\\)?"))
12289 (goto-char (match-end 0))
12290 (cond
12291 (drawer
12292 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12293 nil t)
12294 (progn
12295 (goto-char (match-end 0))
12296 (or org-log-states-order-reversed
12297 (and (re-search-forward org-property-end-re nil t)
12298 (goto-char (1- (match-beginning 0))))))
12299 (insert "\n:" drawer ":\n:END:")
12300 (beginning-of-line 0)
12301 (org-indent-line-function)
12302 (beginning-of-line 2)
12303 (org-indent-line-function)
12304 (end-of-line 0)))
12305 ((and org-log-state-notes-insert-after-drawers
12306 (save-excursion
12307 (forward-line) (looking-at org-drawer-regexp)))
12308 (forward-line)
12309 (while (looking-at org-drawer-regexp)
12310 (goto-char (match-end 0))
12311 (re-search-forward org-property-end-re (point-max) t)
12312 (forward-line))
12313 (forward-line -1)))
12314 (unless org-log-states-order-reversed
12315 (and (= (char-after) ?\n) (forward-char 1))
12316 (org-skip-over-state-notes)
12317 (skip-chars-backward " \t\n\r")))
12318 (move-marker org-log-note-marker (point))
12319 (setq org-log-note-purpose purpose
12320 org-log-note-state state
12321 org-log-note-previous-state prev-state
12322 org-log-note-how how
12323 org-log-note-extra extra
12324 org-log-note-effective-time (org-current-effective-time))
12325 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12327 (defun org-skip-over-state-notes ()
12328 "Skip past the list of State notes in an entry."
12329 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12330 (when (ignore-errors (goto-char (org-in-item-p)))
12331 (let* ((struct (org-list-struct))
12332 (prevs (org-list-prevs-alist struct)))
12333 (while (looking-at "[ \t]*- State")
12334 (goto-char (or (org-list-get-next-item (point) struct prevs)
12335 (org-list-get-item-end (point) struct)))))))
12337 (defun org-add-log-note (&optional purpose)
12338 "Pop up a window for taking a note, and add this note later at point."
12339 (remove-hook 'post-command-hook 'org-add-log-note)
12340 (setq org-log-note-window-configuration (current-window-configuration))
12341 (delete-other-windows)
12342 (move-marker org-log-note-return-to (point))
12343 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12344 (goto-char org-log-note-marker)
12345 (org-switch-to-buffer-other-window "*Org Note*")
12346 (erase-buffer)
12347 (if (memq org-log-note-how '(time state))
12348 (let (current-prefix-arg) (org-store-log-note))
12349 (let ((org-inhibit-startup t)) (org-mode))
12350 (insert (format "# Insert note for %s.
12351 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12352 (cond
12353 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12354 ((eq org-log-note-purpose 'done) "closed todo item")
12355 ((eq org-log-note-purpose 'state)
12356 (format "state change from \"%s\" to \"%s\""
12357 (or org-log-note-previous-state "")
12358 (or org-log-note-state "")))
12359 ((eq org-log-note-purpose 'reschedule)
12360 "rescheduling")
12361 ((eq org-log-note-purpose 'delschedule)
12362 "no longer scheduled")
12363 ((eq org-log-note-purpose 'redeadline)
12364 "changing deadline")
12365 ((eq org-log-note-purpose 'deldeadline)
12366 "removing deadline")
12367 ((eq org-log-note-purpose 'refile)
12368 "refiling")
12369 ((eq org-log-note-purpose 'note)
12370 "this entry")
12371 (t (error "This should not happen")))))
12372 (if org-log-note-extra (insert org-log-note-extra))
12373 (org-set-local 'org-finish-function 'org-store-log-note)
12374 (run-hooks 'org-log-buffer-setup-hook)))
12376 (defvar org-note-abort nil) ; dynamically scoped
12377 (defun org-store-log-note ()
12378 "Finish taking a log note, and insert it to where it belongs."
12379 (let ((txt (buffer-string))
12380 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12381 lines ind bul)
12382 (kill-buffer (current-buffer))
12383 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12384 (setq txt (replace-match "" t t txt)))
12385 (if (string-match "\\s-+\\'" txt)
12386 (setq txt (replace-match "" t t txt)))
12387 (setq lines (org-split-string txt "\n"))
12388 (when (and note (string-match "\\S-" note))
12389 (setq note
12390 (org-replace-escapes
12391 note
12392 (list (cons "%u" (user-login-name))
12393 (cons "%U" user-full-name)
12394 (cons "%t" (format-time-string
12395 (org-time-stamp-format 'long 'inactive)
12396 org-log-note-effective-time))
12397 (cons "%T" (format-time-string
12398 (org-time-stamp-format 'long nil)
12399 org-log-note-effective-time))
12400 (cons "%d" (format-time-string
12401 (org-time-stamp-format nil 'inactive)
12402 org-log-note-effective-time))
12403 (cons "%D" (format-time-string
12404 (org-time-stamp-format nil nil)
12405 org-log-note-effective-time))
12406 (cons "%s" (if org-log-note-state
12407 (concat "\"" org-log-note-state "\"")
12408 ""))
12409 (cons "%S" (if org-log-note-previous-state
12410 (concat "\"" org-log-note-previous-state "\"")
12411 "\"\"")))))
12412 (if lines (setq note (concat note " \\\\")))
12413 (push note lines))
12414 (when (or current-prefix-arg org-note-abort)
12415 (when org-log-into-drawer
12416 (org-remove-empty-drawer-at
12417 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12418 org-log-note-marker))
12419 (setq lines nil))
12420 (when lines
12421 (with-current-buffer (marker-buffer org-log-note-marker)
12422 (save-excursion
12423 (goto-char org-log-note-marker)
12424 (move-marker org-log-note-marker nil)
12425 (end-of-line 1)
12426 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12427 (setq ind (save-excursion
12428 (if (ignore-errors (goto-char (org-in-item-p)))
12429 (let ((struct (org-list-struct)))
12430 (org-list-get-ind
12431 (org-list-get-top-point struct) struct))
12432 (skip-chars-backward " \r\t\n")
12433 (cond
12434 ((and (org-at-heading-p)
12435 org-adapt-indentation)
12436 (1+ (org-current-level)))
12437 ((org-at-heading-p) 0)
12438 (t (org-get-indentation))))))
12439 (setq bul (org-list-bullet-string "-"))
12440 (org-indent-line-to ind)
12441 (insert bul (pop lines))
12442 (let ((ind-body (+ (length bul) ind)))
12443 (while lines
12444 (insert "\n")
12445 (org-indent-line-to ind-body)
12446 (insert (pop lines))))
12447 (message "Note stored")
12448 (org-back-to-heading t)
12449 (org-cycle-hide-drawers 'children)))))
12450 (set-window-configuration org-log-note-window-configuration)
12451 (with-current-buffer (marker-buffer org-log-note-return-to)
12452 (goto-char org-log-note-return-to))
12453 (move-marker org-log-note-return-to nil)
12454 (and org-log-post-message (message "%s" org-log-post-message)))
12456 (defun org-remove-empty-drawer-at (drawer pos)
12457 "Remove an empty drawer DRAWER at position POS.
12458 POS may also be a marker."
12459 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12460 (save-excursion
12461 (save-restriction
12462 (widen)
12463 (goto-char pos)
12464 (if (org-in-regexp
12465 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12466 (replace-match ""))))))
12468 (defun org-sparse-tree (&optional arg)
12469 "Create a sparse tree, prompt for the details.
12470 This command can create sparse trees. You first need to select the type
12471 of match used to create the tree:
12473 t Show all TODO entries.
12474 T Show entries with a specific TODO keyword.
12475 m Show entries selected by a tags/property match.
12476 p Enter a property name and its value (both with completion on existing
12477 names/values) and show entries with that property.
12478 r Show entries matching a regular expression (`/' can be used as well)
12479 d Show deadlines due within `org-deadline-warning-days'.
12480 b Show deadlines and scheduled items before a date.
12481 a Show deadlines and scheduled items after a date."
12482 (interactive "P")
12483 (let (ans kwd value)
12484 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range")
12485 (setq ans (read-char-exclusive))
12486 (cond
12487 ((equal ans ?d)
12488 (call-interactively 'org-check-deadlines))
12489 ((equal ans ?b)
12490 (call-interactively 'org-check-before-date))
12491 ((equal ans ?a)
12492 (call-interactively 'org-check-after-date))
12493 ((equal ans ?D)
12494 (call-interactively 'org-check-dates-range))
12495 ((equal ans ?t)
12496 (org-show-todo-tree nil))
12497 ((equal ans ?T)
12498 (org-show-todo-tree '(4)))
12499 ((member ans '(?T ?m))
12500 (call-interactively 'org-match-sparse-tree))
12501 ((member ans '(?p ?P))
12502 (setq kwd (org-icompleting-read "Property: "
12503 (mapcar 'list (org-buffer-property-keys))))
12504 (setq value (org-icompleting-read "Value: "
12505 (mapcar 'list (org-property-values kwd))))
12506 (unless (string-match "\\`{.*}\\'" value)
12507 (setq value (concat "\"" value "\"")))
12508 (org-match-sparse-tree arg (concat kwd "=" value)))
12509 ((member ans '(?r ?R ?/))
12510 (call-interactively 'org-occur))
12511 (t (error "No such sparse tree command \"%c\"" ans)))))
12513 (defvar org-occur-highlights nil
12514 "List of overlays used for occur matches.")
12515 (make-variable-buffer-local 'org-occur-highlights)
12516 (defvar org-occur-parameters nil
12517 "Parameters of the active org-occur calls.
12518 This is a list, each call to org-occur pushes as cons cell,
12519 containing the regular expression and the callback, onto the list.
12520 The list can contain several entries if `org-occur' has been called
12521 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12522 will only contain one set of parameters. When the highlights are
12523 removed (for example with `C-c C-c', or with the next edit (depending
12524 on `org-remove-highlights-with-change'), this variable is emptied
12525 as well.")
12526 (make-variable-buffer-local 'org-occur-parameters)
12528 (defun org-occur (regexp &optional keep-previous callback)
12529 "Make a compact tree which shows all matches of REGEXP.
12530 The tree will show the lines where the regexp matches, and all higher
12531 headlines above the match. It will also show the heading after the match,
12532 to make sure editing the matching entry is easy.
12533 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12534 call to `org-occur' will be kept, to allow stacking of calls to this
12535 command.
12536 If CALLBACK is non-nil, it is a function which is called to confirm
12537 that the match should indeed be shown."
12538 (interactive "sRegexp: \nP")
12539 (when (equal regexp "")
12540 (error "Regexp cannot be empty"))
12541 (unless keep-previous
12542 (org-remove-occur-highlights nil nil t))
12543 (push (cons regexp callback) org-occur-parameters)
12544 (let ((cnt 0))
12545 (save-excursion
12546 (goto-char (point-min))
12547 (if (or (not keep-previous) ; do not want to keep
12548 (not org-occur-highlights)) ; no previous matches
12549 ;; hide everything
12550 (org-overview))
12551 (while (re-search-forward regexp nil t)
12552 (when (or (not callback)
12553 (save-match-data (funcall callback)))
12554 (setq cnt (1+ cnt))
12555 (when org-highlight-sparse-tree-matches
12556 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12557 (org-show-context 'occur-tree))))
12558 (when org-remove-highlights-with-change
12559 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12560 nil 'local))
12561 (unless org-sparse-tree-open-archived-trees
12562 (org-hide-archived-subtrees (point-min) (point-max)))
12563 (run-hooks 'org-occur-hook)
12564 (if (org-called-interactively-p 'interactive)
12565 (message "%d match(es) for regexp %s" cnt regexp))
12566 cnt))
12568 (defun org-occur-next-match (&optional n reset)
12569 "Function for `next-error-function' to find sparse tree matches.
12570 N is the number of matches to move, when negative move backwards.
12571 RESET is entirely ignored - this function always goes back to the
12572 starting point when no match is found."
12573 (let* ((limit (if (< n 0) (point-min) (point-max)))
12574 (search-func (if (< n 0)
12575 'previous-single-char-property-change
12576 'next-single-char-property-change))
12577 (n (abs n))
12578 (pos (point))
12580 (catch 'exit
12581 (while (setq p1 (funcall search-func (point) 'org-type))
12582 (when (equal p1 limit)
12583 (goto-char pos)
12584 (error "No more matches"))
12585 (when (equal (get-char-property p1 'org-type) 'org-occur)
12586 (setq n (1- n))
12587 (when (= n 0)
12588 (goto-char p1)
12589 (throw 'exit (point))))
12590 (goto-char p1))
12591 (goto-char p1)
12592 (error "No more matches"))))
12594 (defun org-show-context (&optional key)
12595 "Make sure point and context are visible.
12596 How much context is shown depends upon the variables
12597 `org-show-hierarchy-above', `org-show-following-heading',
12598 `org-show-entry-below' and `org-show-siblings'."
12599 (let ((heading-p (org-at-heading-p t))
12600 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12601 (following-p (org-get-alist-option org-show-following-heading key))
12602 (entry-p (org-get-alist-option org-show-entry-below key))
12603 (siblings-p (org-get-alist-option org-show-siblings key)))
12604 (catch 'exit
12605 ;; Show heading or entry text
12606 (if (and heading-p (not entry-p))
12607 (org-flag-heading nil) ; only show the heading
12608 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12609 (org-show-hidden-entry))) ; show entire entry
12610 (when following-p
12611 ;; Show next sibling, or heading below text
12612 (save-excursion
12613 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12614 (org-flag-heading nil))))
12615 (when siblings-p (org-show-siblings))
12616 (when hierarchy-p
12617 ;; show all higher headings, possibly with siblings
12618 (save-excursion
12619 (while (and (condition-case nil
12620 (progn (org-up-heading-all 1) t)
12621 (error nil))
12622 (not (bobp)))
12623 (org-flag-heading nil)
12624 (when siblings-p (org-show-siblings))))))))
12626 (defvar org-reveal-start-hook nil
12627 "Hook run before revealing a location.")
12629 (defun org-reveal (&optional siblings)
12630 "Show current entry, hierarchy above it, and the following headline.
12631 This can be used to show a consistent set of context around locations
12632 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12633 not t for the search context.
12635 With optional argument SIBLINGS, on each level of the hierarchy all
12636 siblings are shown. This repairs the tree structure to what it would
12637 look like when opened with hierarchical calls to `org-cycle'.
12638 With double optional argument \\[universal-argument] \\[universal-argument], \
12639 go to the parent and show the
12640 entire tree."
12641 (interactive "P")
12642 (run-hooks 'org-reveal-start-hook)
12643 (let ((org-show-hierarchy-above t)
12644 (org-show-following-heading t)
12645 (org-show-siblings (if siblings t org-show-siblings)))
12646 (org-show-context nil))
12647 (when (equal siblings '(16))
12648 (save-excursion
12649 (when (org-up-heading-safe)
12650 (org-show-subtree)
12651 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12653 (defun org-highlight-new-match (beg end)
12654 "Highlight from BEG to END and mark the highlight is an occur headline."
12655 (let ((ov (make-overlay beg end)))
12656 (overlay-put ov 'face 'secondary-selection)
12657 (overlay-put ov 'org-type 'org-occur)
12658 (push ov org-occur-highlights)))
12660 (defun org-remove-occur-highlights (&optional beg end noremove)
12661 "Remove the occur highlights from the buffer.
12662 BEG and END are ignored. If NOREMOVE is nil, remove this function
12663 from the `before-change-functions' in the current buffer."
12664 (interactive)
12665 (unless org-inhibit-highlight-removal
12666 (mapc 'delete-overlay org-occur-highlights)
12667 (setq org-occur-highlights nil)
12668 (setq org-occur-parameters nil)
12669 (unless noremove
12670 (remove-hook 'before-change-functions
12671 'org-remove-occur-highlights 'local))))
12673 ;;;; Priorities
12675 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12676 "Regular expression matching the priority indicator.")
12678 (defvar org-remove-priority-next-time nil)
12680 (defun org-priority-up ()
12681 "Increase the priority of the current item."
12682 (interactive)
12683 (org-priority 'up))
12685 (defun org-priority-down ()
12686 "Decrease the priority of the current item."
12687 (interactive)
12688 (org-priority 'down))
12690 (defun org-priority (&optional action)
12691 "Change the priority of an item by ARG.
12692 ACTION can be `set', `up', `down', or a character."
12693 (interactive)
12694 (unless org-enable-priority-commands
12695 (error "Priority commands are disabled"))
12696 (setq action (or action 'set))
12697 (let (current new news have remove)
12698 (save-excursion
12699 (org-back-to-heading t)
12700 (if (looking-at org-priority-regexp)
12701 (setq current (string-to-char (match-string 2))
12702 have t))
12703 (cond
12704 ((eq action 'remove)
12705 (setq remove t new ?\ ))
12706 ((or (eq action 'set)
12707 (if (featurep 'xemacs) (characterp action) (integerp action)))
12708 (if (not (eq action 'set))
12709 (setq new action)
12710 (message "Priority %c-%c, SPC to remove: "
12711 org-highest-priority org-lowest-priority)
12712 (save-match-data
12713 (setq new (read-char-exclusive))))
12714 (if (and (= (upcase org-highest-priority) org-highest-priority)
12715 (= (upcase org-lowest-priority) org-lowest-priority))
12716 (setq new (upcase new)))
12717 (cond ((equal new ?\ ) (setq remove t))
12718 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12719 (error "Priority must be between `%c' and `%c'"
12720 org-highest-priority org-lowest-priority))))
12721 ((eq action 'up)
12722 (setq new (if have
12723 (1- current) ; normal cycling
12724 ;; last priority was empty
12725 (if (eq last-command this-command)
12726 org-lowest-priority ; wrap around empty to lowest
12727 ;; default
12728 (if org-priority-start-cycle-with-default
12729 org-default-priority
12730 (1- org-default-priority))))))
12731 ((eq action 'down)
12732 (setq new (if have
12733 (1+ current) ; normal cycling
12734 ;; last priority was empty
12735 (if (eq last-command this-command)
12736 org-highest-priority ; wrap around empty to highest
12737 ;; default
12738 (if org-priority-start-cycle-with-default
12739 org-default-priority
12740 (1+ org-default-priority))))))
12741 (t (error "Invalid action")))
12742 (if (or (< (upcase new) org-highest-priority)
12743 (> (upcase new) org-lowest-priority))
12744 (if (and (memq action '(up down))
12745 (not have) (not (eq last-command this-command)))
12746 ;; `new' is from default priority
12747 (error
12748 "The default can not be set, see `org-default-priority' why")
12749 ;; normal cycling: `new' is beyond highest/lowest priority
12750 ;; and is wrapped around to the empty priority
12751 (setq remove t)))
12752 (setq news (format "%c" new))
12753 (if have
12754 (if remove
12755 (replace-match "" t t nil 1)
12756 (replace-match news t t nil 2))
12757 (if remove
12758 (error "No priority cookie found in line")
12759 (let ((case-fold-search nil))
12760 (looking-at org-todo-line-regexp))
12761 (if (match-end 2)
12762 (progn
12763 (goto-char (match-end 2))
12764 (insert " [#" news "]"))
12765 (goto-char (match-beginning 3))
12766 (insert "[#" news "] "))))
12767 (org-preserve-lc (org-set-tags nil 'align)))
12768 (if remove
12769 (message "Priority removed")
12770 (message "Priority of current item set to %s" news))))
12772 (defun org-get-priority (s)
12773 "Find priority cookie and return priority."
12774 (if (functionp org-get-priority-function)
12775 (funcall org-get-priority-function)
12776 (save-match-data
12777 (if (not (string-match org-priority-regexp s))
12778 (* 1000 (- org-lowest-priority org-default-priority))
12779 (* 1000 (- org-lowest-priority
12780 (string-to-char (match-string 2 s))))))))
12782 ;;;; Tags
12784 (defvar org-agenda-archives-mode)
12785 (defvar org-map-continue-from nil
12786 "Position from where mapping should continue.
12787 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12789 (defvar org-scanner-tags nil
12790 "The current tag list while the tags scanner is running.")
12791 (defvar org-trust-scanner-tags nil
12792 "Should `org-get-tags-at' use the tags for the scanner.
12793 This is for internal dynamical scoping only.
12794 When this is non-nil, the function `org-get-tags-at' will return the value
12795 of `org-scanner-tags' instead of building the list by itself. This
12796 can lead to large speed-ups when the tags scanner is used in a file with
12797 many entries, and when the list of tags is retrieved, for example to
12798 obtain a list of properties. Building the tags list for each entry in such
12799 a file becomes an N^2 operation - but with this variable set, it scales
12800 as N.")
12802 (defun org-scan-tags (action matcher todo-only &optional start-level)
12803 "Scan headline tags with inheritance and produce output ACTION.
12805 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12806 or `agenda' to produce an entry list for an agenda view. It can also be
12807 a Lisp form or a function that should be called at each matched headline, in
12808 this case the return value is a list of all return values from these calls.
12810 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12811 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12812 only lines with a not-done TODO keyword are included in the output.
12813 This should be the same variable that was scoped into
12814 and set by `org-make-tags-matcher' when it constructed MATCHER.
12816 START-LEVEL can be a string with asterisks, reducing the scope to
12817 headlines matching this string."
12818 (require 'org-agenda)
12819 (let* ((re (concat "^"
12820 (if start-level
12821 ;; Get the correct level to match
12822 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12823 org-outline-regexp)
12824 " *\\(\\<\\("
12825 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12826 (org-re
12827 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12828 (props (list 'face 'default
12829 'done-face 'org-agenda-done
12830 'undone-face 'default
12831 'mouse-face 'highlight
12832 'org-not-done-regexp org-not-done-regexp
12833 'org-todo-regexp org-todo-regexp
12834 'org-complex-heading-regexp org-complex-heading-regexp
12835 'help-echo
12836 (format "mouse-2 or RET jump to org file %s"
12837 (abbreviate-file-name
12838 (or (buffer-file-name (buffer-base-buffer))
12839 (buffer-name (buffer-base-buffer)))))))
12840 (case-fold-search nil)
12841 (org-map-continue-from nil)
12842 lspos tags tags-list
12843 (tags-alist (list (cons 0 org-file-tags)))
12844 (llast 0) rtn rtn1 level category i txt
12845 todo marker entry priority)
12846 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12847 (setq action (list 'lambda nil action)))
12848 (save-excursion
12849 (goto-char (point-min))
12850 (when (eq action 'sparse-tree)
12851 (org-overview)
12852 (org-remove-occur-highlights))
12853 (while (re-search-forward re nil t)
12854 (setq org-map-continue-from nil)
12855 (catch :skip
12856 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12857 tags (if (match-end 4) (org-match-string-no-properties 4)))
12858 (goto-char (setq lspos (match-beginning 0)))
12859 (setq level (org-reduced-level (funcall outline-level))
12860 category (org-get-category))
12861 (setq i llast llast level)
12862 ;; remove tag lists from same and sublevels
12863 (while (>= i level)
12864 (when (setq entry (assoc i tags-alist))
12865 (setq tags-alist (delete entry tags-alist)))
12866 (setq i (1- i)))
12867 ;; add the next tags
12868 (when tags
12869 (setq tags (org-split-string tags ":")
12870 tags-alist
12871 (cons (cons level tags) tags-alist)))
12872 ;; compile tags for current headline
12873 (setq tags-list
12874 (if org-use-tag-inheritance
12875 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12876 tags)
12877 org-scanner-tags tags-list)
12878 (when org-use-tag-inheritance
12879 (setcdr (car tags-alist)
12880 (mapcar (lambda (x)
12881 (setq x (copy-sequence x))
12882 (org-add-prop-inherited x))
12883 (cdar tags-alist))))
12884 (when (and tags org-use-tag-inheritance
12885 (or (not (eq t org-use-tag-inheritance))
12886 org-tags-exclude-from-inheritance))
12887 ;; selective inheritance, remove uninherited ones
12888 (setcdr (car tags-alist)
12889 (org-remove-uninherited-tags (cdar tags-alist))))
12890 (when (and
12892 ;; eval matcher only when the todo condition is OK
12893 (and (or (not todo-only) (member todo org-not-done-keywords))
12894 (let ((case-fold-search t)) (eval matcher)))
12896 ;; Call the skipper, but return t if it does not skip,
12897 ;; so that the `and' form continues evaluating
12898 (progn
12899 (unless (eq action 'sparse-tree) (org-agenda-skip))
12902 ;; Check if timestamps are deselecting this entry
12903 (or (not todo-only)
12904 (and (member todo org-not-done-keywords)
12905 (or (not org-agenda-tags-todo-honor-ignore-options)
12906 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12908 ;; Extra check for the archive tag
12909 ;; FIXME: Does the skipper already do this????
12911 (not (member org-archive-tag tags-list))
12912 ;; we have an archive tag, should we use this anyway?
12913 (or (not org-agenda-skip-archived-trees)
12914 (and (eq action 'agenda) org-agenda-archives-mode))))
12916 ;; select this headline
12918 (cond
12919 ((eq action 'sparse-tree)
12920 (and org-highlight-sparse-tree-matches
12921 (org-get-heading) (match-end 0)
12922 (org-highlight-new-match
12923 (match-beginning 1) (match-end 1)))
12924 (org-show-context 'tags-tree))
12925 ((eq action 'agenda)
12926 (setq txt (org-agenda-format-item
12928 (concat
12929 (if (eq org-tags-match-list-sublevels 'indented)
12930 (make-string (1- level) ?.) "")
12931 (org-get-heading))
12932 category
12933 tags-list
12935 priority (org-get-priority txt))
12936 (goto-char lspos)
12937 (setq marker (org-agenda-new-marker))
12938 (org-add-props txt props
12939 'org-marker marker 'org-hd-marker marker 'org-category category
12940 'todo-state todo
12941 'priority priority 'type "tagsmatch")
12942 (push txt rtn))
12943 ((functionp action)
12944 (setq org-map-continue-from nil)
12945 (save-excursion
12946 (setq rtn1 (funcall action))
12947 (push rtn1 rtn)))
12948 (t (error "Invalid action")))
12950 ;; if we are to skip sublevels, jump to end of subtree
12951 (unless org-tags-match-list-sublevels
12952 (org-end-of-subtree t)
12953 (backward-char 1))))
12954 ;; Get the correct position from where to continue
12955 (if org-map-continue-from
12956 (goto-char org-map-continue-from)
12957 (and (= (point) lspos) (end-of-line 1)))))
12958 (when (and (eq action 'sparse-tree)
12959 (not org-sparse-tree-open-archived-trees))
12960 (org-hide-archived-subtrees (point-min) (point-max)))
12961 (nreverse rtn)))
12963 (defun org-remove-uninherited-tags (tags)
12964 "Remove all tags that are not inherited from the list TAGS."
12965 (cond
12966 ((eq org-use-tag-inheritance t)
12967 (if org-tags-exclude-from-inheritance
12968 (org-delete-all org-tags-exclude-from-inheritance tags)
12969 tags))
12970 ((not org-use-tag-inheritance) nil)
12971 ((stringp org-use-tag-inheritance)
12972 (delq nil (mapcar
12973 (lambda (x)
12974 (if (and (string-match org-use-tag-inheritance x)
12975 (not (member x org-tags-exclude-from-inheritance)))
12976 x nil))
12977 tags)))
12978 ((listp org-use-tag-inheritance)
12979 (delq nil (mapcar
12980 (lambda (x)
12981 (if (member x org-use-tag-inheritance) x nil))
12982 tags)))))
12984 (defun org-match-sparse-tree (&optional todo-only match)
12985 "Create a sparse tree according to tags string MATCH.
12986 MATCH can contain positive and negative selection of tags, like
12987 \"+WORK+URGENT-WITHBOSS\".
12988 If optional argument TODO-ONLY is non-nil, only select lines that are
12989 also TODO lines."
12990 (interactive "P")
12991 (org-prepare-agenda-buffers (list (current-buffer)))
12992 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12994 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12996 (defvar org-cached-props nil)
12997 (defun org-cached-entry-get (pom property)
12998 (if (or (eq t org-use-property-inheritance)
12999 (and (stringp org-use-property-inheritance)
13000 (string-match org-use-property-inheritance property))
13001 (and (listp org-use-property-inheritance)
13002 (member property org-use-property-inheritance)))
13003 ;; Caching is not possible, check it directly
13004 (org-entry-get pom property 'inherit)
13005 ;; Get all properties, so that we can do complicated checks easily
13006 (cdr (assoc property (or org-cached-props
13007 (setq org-cached-props
13008 (org-entry-properties pom)))))))
13010 (defun org-global-tags-completion-table (&optional files)
13011 "Return the list of all tags in all agenda buffer/files.
13012 Optional FILES argument is a list of files to which can be used
13013 instead of the agenda files."
13014 (save-excursion
13015 (org-uniquify
13016 (delq nil
13017 (apply 'append
13018 (mapcar
13019 (lambda (file)
13020 (set-buffer (find-file-noselect file))
13021 (append (org-get-buffer-tags)
13022 (mapcar (lambda (x) (if (stringp (car-safe x))
13023 (list (car-safe x)) nil))
13024 org-tag-alist)))
13025 (if (and files (car files))
13026 files
13027 (org-agenda-files))))))))
13029 (defun org-make-tags-matcher (match)
13030 "Create the TAGS/TODO matcher form for the selection string MATCH.
13032 The variable `todo-only' is scoped dynamically into this function; it will be
13033 set to t if the matcher restricts matching to TODO entries,
13034 otherwise will not be touched.
13036 Returns a cons of the selection string MATCH and the constructed
13037 lisp form implementing the matcher. The matcher is to be
13038 evaluated at an Org entry, with point on the headline,
13039 and returns t if the entry matches the
13040 selection string MATCH. The returned lisp form references
13041 two variables with information about the entry, which must be
13042 bound around the form's evaluation: todo, the TODO keyword at the
13043 entry (or nil of none); and tags-list, the list of all tags at the
13044 entry including inherited ones. Additionally, the category
13045 of the entry (if any) must be specified as the text property
13046 'org-category on the headline.
13048 See also `org-scan-tags'.
13050 (declare (special todo-only))
13051 (unless (boundp 'todo-only)
13052 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13053 (unless match
13054 ;; Get a new match request, with completion
13055 (let ((org-last-tags-completion-table
13056 (org-global-tags-completion-table)))
13057 (setq match (org-completing-read-no-i
13058 "Match: " 'org-tags-completion-function nil nil nil
13059 'org-tags-history))))
13061 ;; Parse the string and create a lisp form
13062 (let ((match0 match)
13063 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13064 minus tag mm
13065 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13066 orterms term orlist re-p str-p level-p level-op time-p
13067 prop-p pn pv po gv rest)
13068 (if (string-match "/+" match)
13069 ;; match contains also a todo-matching request
13070 (progn
13071 (setq tagsmatch (substring match 0 (match-beginning 0))
13072 todomatch (substring match (match-end 0)))
13073 (if (string-match "^!" todomatch)
13074 (setq todo-only t todomatch (substring todomatch 1)))
13075 (if (string-match "^\\s-*$" todomatch)
13076 (setq todomatch nil)))
13077 ;; only matching tags
13078 (setq tagsmatch match todomatch nil))
13080 ;; Make the tags matcher
13081 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13082 (setq tagsmatcher t)
13083 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13084 (while (setq term (pop orterms))
13085 (while (and (equal (substring term -1) "\\") orterms)
13086 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13087 (while (string-match re term)
13088 (setq rest (substring term (match-end 0))
13089 minus (and (match-end 1)
13090 (equal (match-string 1 term) "-"))
13091 tag (save-match-data (replace-regexp-in-string
13092 "\\\\-" "-"
13093 (match-string 2 term)))
13094 re-p (equal (string-to-char tag) ?{)
13095 level-p (match-end 4)
13096 prop-p (match-end 5)
13097 mm (cond
13098 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13099 (level-p
13100 (setq level-op (org-op-to-function (match-string 3 term)))
13101 `(,level-op level ,(string-to-number
13102 (match-string 4 term))))
13103 (prop-p
13104 (setq pn (match-string 5 term)
13105 po (match-string 6 term)
13106 pv (match-string 7 term)
13107 re-p (equal (string-to-char pv) ?{)
13108 str-p (equal (string-to-char pv) ?\")
13109 time-p (save-match-data
13110 (string-match "^\"[[<].*[]>]\"$" pv))
13111 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13112 (if time-p (setq pv (org-matcher-time pv)))
13113 (setq po (org-op-to-function po (if time-p 'time str-p)))
13114 (cond
13115 ((equal pn "CATEGORY")
13116 (setq gv '(get-text-property (point) 'org-category)))
13117 ((equal pn "TODO")
13118 (setq gv 'todo))
13120 (setq gv `(org-cached-entry-get nil ,pn))))
13121 (if re-p
13122 (if (eq po 'org<>)
13123 `(not (string-match ,pv (or ,gv "")))
13124 `(string-match ,pv (or ,gv "")))
13125 (if str-p
13126 `(,po (or ,gv "") ,pv)
13127 `(,po (string-to-number (or ,gv ""))
13128 ,(string-to-number pv) ))))
13129 (t `(member ,tag tags-list)))
13130 mm (if minus (list 'not mm) mm)
13131 term rest)
13132 (push mm tagsmatcher))
13133 (push (if (> (length tagsmatcher) 1)
13134 (cons 'and tagsmatcher)
13135 (car tagsmatcher))
13136 orlist)
13137 (setq tagsmatcher nil))
13138 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13139 (setq tagsmatcher
13140 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13141 ;; Make the todo matcher
13142 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13143 (setq todomatcher t)
13144 (setq orterms (org-split-string todomatch "|") orlist nil)
13145 (while (setq term (pop orterms))
13146 (while (string-match re term)
13147 (setq minus (and (match-end 1)
13148 (equal (match-string 1 term) "-"))
13149 kwd (match-string 2 term)
13150 re-p (equal (string-to-char kwd) ?{)
13151 term (substring term (match-end 0))
13152 mm (if re-p
13153 `(string-match ,(substring kwd 1 -1) todo)
13154 (list 'equal 'todo kwd))
13155 mm (if minus (list 'not mm) mm))
13156 (push mm todomatcher))
13157 (push (if (> (length todomatcher) 1)
13158 (cons 'and todomatcher)
13159 (car todomatcher))
13160 orlist)
13161 (setq todomatcher nil))
13162 (setq todomatcher (if (> (length orlist) 1)
13163 (cons 'or orlist) (car orlist))))
13165 ;; Return the string and lisp forms of the matcher
13166 (setq matcher (if todomatcher
13167 (list 'and tagsmatcher todomatcher)
13168 tagsmatcher))
13169 (when todo-only
13170 (setq matcher (list 'and '(member todo org-not-done-keywords)
13171 matcher)))
13172 (cons match0 matcher)))
13174 (defun org-op-to-function (op &optional stringp)
13175 "Turn an operator into the appropriate function."
13176 (setq op
13177 (cond
13178 ((equal op "<" ) '(< string< org-time<))
13179 ((equal op ">" ) '(> org-string> org-time>))
13180 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13181 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13182 ((member op '("=" "==")) '(= string= org-time=))
13183 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13184 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13186 (defun org<> (a b) (not (= a b)))
13187 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13188 (defun org-string>= (a b) (not (string< a b)))
13189 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13190 (defun org-string<> (a b) (not (string= a b)))
13191 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13192 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13193 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13194 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13195 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13196 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13197 (defun org-2ft (s)
13198 "Convert S to a floating point time.
13199 If S is already a number, just return it. If it is a string, parse
13200 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13201 (cond
13202 ((numberp s) s)
13203 ((stringp s)
13204 (condition-case nil
13205 (float-time (apply 'encode-time (org-parse-time-string s)))
13206 (error 0.)))
13207 (t 0.)))
13209 (defun org-time-today ()
13210 "Time in seconds today at 0:00.
13211 Returns the float number of seconds since the beginning of the
13212 epoch to the beginning of today (00:00)."
13213 (float-time (apply 'encode-time
13214 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13216 (defun org-matcher-time (s)
13217 "Interpret a time comparison value."
13218 (save-match-data
13219 (cond
13220 ((string= s "<now>") (float-time))
13221 ((string= s "<today>") (org-time-today))
13222 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13223 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13224 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13225 (+ (org-time-today)
13226 (* (string-to-number (match-string 1 s))
13227 (cdr (assoc (match-string 2 s)
13228 '(("d" . 86400.0) ("w" . 604800.0)
13229 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13230 (t (org-2ft s)))))
13232 (defun org-match-any-p (re list)
13233 "Does re match any element of list?"
13234 (setq list (mapcar (lambda (x) (string-match re x)) list))
13235 (delq nil list))
13237 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13238 (defvar org-tags-overlay (make-overlay 1 1))
13239 (org-detach-overlay org-tags-overlay)
13241 (defun org-get-local-tags-at (&optional pos)
13242 "Get a list of tags defined in the current headline."
13243 (org-get-tags-at pos 'local))
13245 (defun org-get-local-tags ()
13246 "Get a list of tags defined in the current headline."
13247 (org-get-tags-at nil 'local))
13249 (defun org-get-tags-at (&optional pos local)
13250 "Get a list of all headline tags applicable at POS.
13251 POS defaults to point. If tags are inherited, the list contains
13252 the targets in the same sequence as the headlines appear, i.e.
13253 the tags of the current headline come last.
13254 When LOCAL is non-nil, only return tags from the current headline,
13255 ignore inherited ones."
13256 (interactive)
13257 (if (and org-trust-scanner-tags
13258 (or (not pos) (equal pos (point)))
13259 (not local))
13260 org-scanner-tags
13261 (let (tags ltags lastpos parent)
13262 (save-excursion
13263 (save-restriction
13264 (widen)
13265 (goto-char (or pos (point)))
13266 (save-match-data
13267 (catch 'done
13268 (condition-case nil
13269 (progn
13270 (org-back-to-heading t)
13271 (while (not (equal lastpos (point)))
13272 (setq lastpos (point))
13273 (when (looking-at
13274 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13275 (setq ltags (org-split-string
13276 (org-match-string-no-properties 1) ":"))
13277 (when parent
13278 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13279 (setq tags (append
13280 (if parent
13281 (org-remove-uninherited-tags ltags)
13282 ltags)
13283 tags)))
13284 (or org-use-tag-inheritance (throw 'done t))
13285 (if local (throw 'done t))
13286 (or (org-up-heading-safe) (error nil))
13287 (setq parent t)))
13288 (error nil)))))
13289 (if local
13290 tags
13291 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13293 (defun org-add-prop-inherited (s)
13294 (add-text-properties 0 (length s) '(inherited t) s)
13297 (defun org-toggle-tag (tag &optional onoff)
13298 "Toggle the tag TAG for the current line.
13299 If ONOFF is `on' or `off', don't toggle but set to this state."
13300 (let (res current)
13301 (save-excursion
13302 (org-back-to-heading t)
13303 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13304 (point-at-eol) t)
13305 (progn
13306 (setq current (match-string 1))
13307 (replace-match ""))
13308 (setq current ""))
13309 (setq current (nreverse (org-split-string current ":")))
13310 (cond
13311 ((eq onoff 'on)
13312 (setq res t)
13313 (or (member tag current) (push tag current)))
13314 ((eq onoff 'off)
13315 (or (not (member tag current)) (setq current (delete tag current))))
13316 (t (if (member tag current)
13317 (setq current (delete tag current))
13318 (setq res t)
13319 (push tag current))))
13320 (end-of-line 1)
13321 (if current
13322 (progn
13323 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13324 (org-set-tags nil t))
13325 (delete-horizontal-space))
13326 (run-hooks 'org-after-tags-change-hook))
13327 res))
13329 (defun org-align-tags-here (to-col)
13330 ;; Assumes that this is a headline
13331 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13332 (beginning-of-line 1)
13333 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13334 (< pos (match-beginning 2)))
13335 (progn
13336 (setq tags-l (- (match-end 2) (match-beginning 2)))
13337 (goto-char (match-beginning 1))
13338 (insert " ")
13339 (delete-region (point) (1+ (match-beginning 2)))
13340 (setq ncol (max (current-column)
13341 (1+ col)
13342 (if (> to-col 0)
13343 to-col
13344 (- (abs to-col) tags-l))))
13345 (setq p (point))
13346 (insert (make-string (- ncol (current-column)) ?\ ))
13347 (setq ncol (current-column))
13348 (when indent-tabs-mode (tabify p (point-at-eol)))
13349 (org-move-to-column (min ncol col) t))
13350 (goto-char pos))))
13352 (defun org-set-tags-command (&optional arg just-align)
13353 "Call the set-tags command for the current entry."
13354 (interactive "P")
13355 (if (org-at-heading-p)
13356 (org-set-tags arg just-align)
13357 (save-excursion
13358 (org-back-to-heading t)
13359 (org-set-tags arg just-align))))
13361 (defun org-set-tags-to (data)
13362 "Set the tags of the current entry to DATA, replacing the current tags.
13363 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13364 If DATA is nil or the empty string, any tags will be removed."
13365 (interactive "sTags: ")
13366 (setq data
13367 (cond
13368 ((eq data nil) "")
13369 ((equal data "") "")
13370 ((stringp data)
13371 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13372 ":"))
13373 ((listp data)
13374 (concat ":" (mapconcat 'identity data ":") ":"))
13375 (t nil)))
13376 (when data
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (when (looking-at org-complex-heading-regexp)
13380 (if (match-end 5)
13381 (progn
13382 (goto-char (match-beginning 5))
13383 (insert data)
13384 (delete-region (point) (point-at-eol))
13385 (org-set-tags nil 'align))
13386 (goto-char (point-at-eol))
13387 (insert " " data)
13388 (org-set-tags nil 'align)))
13389 (beginning-of-line 1)
13390 (if (looking-at ".*?\\([ \t]+\\)$")
13391 (delete-region (match-beginning 1) (match-end 1))))))
13393 (defun org-align-all-tags ()
13394 "Align the tags i all headings."
13395 (interactive)
13396 (save-excursion
13397 (or (ignore-errors (org-back-to-heading t))
13398 (outline-next-heading))
13399 (if (org-at-heading-p)
13400 (org-set-tags t)
13401 (message "No headings"))))
13403 (defvar org-indent-indentation-per-level)
13404 (defun org-set-tags (&optional arg just-align)
13405 "Set the tags for the current headline.
13406 With prefix ARG, realign all tags in headings in the current buffer."
13407 (interactive "P")
13408 (let* ((re org-outline-regexp-bol)
13409 (current (org-get-tags-string))
13410 (col (current-column))
13411 (org-setting-tags t)
13412 table current-tags inherited-tags ; computed below when needed
13413 tags p0 c0 c1 rpl di tc level)
13414 (if arg
13415 (save-excursion
13416 (goto-char (point-min))
13417 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13418 (while (re-search-forward re nil t)
13419 (org-set-tags nil t)
13420 (end-of-line 1)))
13421 (message "All tags realigned to column %d" org-tags-column))
13422 (if just-align
13423 (setq tags current)
13424 ;; Get a new set of tags from the user
13425 (save-excursion
13426 (setq table (append org-tag-persistent-alist
13427 (or org-tag-alist (org-get-buffer-tags))
13428 (and
13429 org-complete-tags-always-offer-all-agenda-tags
13430 (org-global-tags-completion-table
13431 (org-agenda-files))))
13432 org-last-tags-completion-table table
13433 current-tags (org-split-string current ":")
13434 inherited-tags (nreverse
13435 (nthcdr (length current-tags)
13436 (nreverse (org-get-tags-at))))
13437 tags
13438 (if (or (eq t org-use-fast-tag-selection)
13439 (and org-use-fast-tag-selection
13440 (delq nil (mapcar 'cdr table))))
13441 (org-fast-tag-selection
13442 current-tags inherited-tags table
13443 (if org-fast-tag-selection-include-todo
13444 org-todo-key-alist))
13445 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13446 (org-trim
13447 (org-icompleting-read "Tags: "
13448 'org-tags-completion-function
13449 nil nil current 'org-tags-history))))))
13450 (while (string-match "[-+&]+" tags)
13451 ;; No boolean logic, just a list
13452 (setq tags (replace-match ":" t t tags))))
13454 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13456 (if org-tags-sort-function
13457 (setq tags (mapconcat 'identity
13458 (sort (org-split-string
13459 tags (org-re "[^[:alnum:]_@#%]+"))
13460 org-tags-sort-function) ":")))
13462 (if (string-match "\\`[\t ]*\\'" tags)
13463 (setq tags "")
13464 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13465 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13467 ;; Insert new tags at the correct column
13468 (beginning-of-line 1)
13469 (setq level (or (and (looking-at org-outline-regexp)
13470 (- (match-end 0) (point) 1))
13472 (cond
13473 ((and (equal current "") (equal tags "")))
13474 ((re-search-forward
13475 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13476 (point-at-eol) t)
13477 (if (equal tags "")
13478 (setq rpl "")
13479 (goto-char (match-beginning 0))
13480 (setq c0 (current-column)
13481 ;; compute offset for the case of org-indent-mode active
13482 di (if org-indent-mode
13483 (* (1- org-indent-indentation-per-level) (1- level))
13485 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13486 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13487 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13488 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13489 (replace-match rpl t t)
13490 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13491 tags)
13492 (t (error "Tags alignment failed")))
13493 (org-move-to-column col)
13494 (unless just-align
13495 (run-hooks 'org-after-tags-change-hook)))))
13497 (defun org-change-tag-in-region (beg end tag off)
13498 "Add or remove TAG for each entry in the region.
13499 This works in the agenda, and also in an org-mode buffer."
13500 (interactive
13501 (list (region-beginning) (region-end)
13502 (let ((org-last-tags-completion-table
13503 (if (eq major-mode 'org-mode)
13504 (org-get-buffer-tags)
13505 (org-global-tags-completion-table))))
13506 (org-icompleting-read
13507 "Tag: " 'org-tags-completion-function nil nil nil
13508 'org-tags-history))
13509 (progn
13510 (message "[s]et or [r]emove? ")
13511 (equal (read-char-exclusive) ?r))))
13512 (if (fboundp 'deactivate-mark) (deactivate-mark))
13513 (let ((agendap (equal major-mode 'org-agenda-mode))
13514 l1 l2 m buf pos newhead (cnt 0))
13515 (goto-char end)
13516 (setq l2 (1- (org-current-line)))
13517 (goto-char beg)
13518 (setq l1 (org-current-line))
13519 (loop for l from l1 to l2 do
13520 (org-goto-line l)
13521 (setq m (get-text-property (point) 'org-hd-marker))
13522 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13523 (and agendap m))
13524 (setq buf (if agendap (marker-buffer m) (current-buffer))
13525 pos (if agendap m (point)))
13526 (with-current-buffer buf
13527 (save-excursion
13528 (save-restriction
13529 (goto-char pos)
13530 (setq cnt (1+ cnt))
13531 (org-toggle-tag tag (if off 'off 'on))
13532 (setq newhead (org-get-heading)))))
13533 (and agendap (org-agenda-change-all-lines newhead m))))
13534 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13536 (defun org-tags-completion-function (string predicate &optional flag)
13537 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13538 (confirm (lambda (x) (stringp (car x)))))
13539 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13540 (setq s1 (match-string 1 string)
13541 s2 (match-string 2 string))
13542 (setq s1 "" s2 string))
13543 (cond
13544 ((eq flag nil)
13545 ;; try completion
13546 (setq rtn (try-completion s2 ctable confirm))
13547 (if (stringp rtn)
13548 (setq rtn
13549 (concat s1 s2 (substring rtn (length s2))
13550 (if (and org-add-colon-after-tag-completion
13551 (assoc rtn ctable))
13552 ":" ""))))
13553 rtn)
13554 ((eq flag t)
13555 ;; all-completions
13556 (all-completions s2 ctable confirm)
13558 ((eq flag 'lambda)
13559 ;; exact match?
13560 (assoc s2 ctable)))
13563 (defun org-fast-tag-insert (kwd tags face &optional end)
13564 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13565 (insert (format "%-12s" (concat kwd ":"))
13566 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13567 (or end "")))
13569 (defun org-fast-tag-show-exit (flag)
13570 (save-excursion
13571 (org-goto-line 3)
13572 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13573 (replace-match ""))
13574 (when flag
13575 (end-of-line 1)
13576 (org-move-to-column (- (window-width) 19) t)
13577 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13579 (defun org-set-current-tags-overlay (current prefix)
13580 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13581 (if (featurep 'xemacs)
13582 (org-overlay-display org-tags-overlay (concat prefix s)
13583 'secondary-selection)
13584 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13585 (org-overlay-display org-tags-overlay (concat prefix s)))))
13587 (defvar org-last-tag-selection-key nil)
13588 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13589 "Fast tag selection with single keys.
13590 CURRENT is the current list of tags in the headline, INHERITED is the
13591 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13592 possibly with grouping information. TODO-TABLE is a similar table with
13593 TODO keywords, should these have keys assigned to them.
13594 If the keys are nil, a-z are automatically assigned.
13595 Returns the new tags string, or nil to not change the current settings."
13596 (let* ((fulltable (append table todo-table))
13597 (maxlen (apply 'max (mapcar
13598 (lambda (x)
13599 (if (stringp (car x)) (string-width (car x)) 0))
13600 fulltable)))
13601 (buf (current-buffer))
13602 (expert (eq org-fast-tag-selection-single-key 'expert))
13603 (buffer-tags nil)
13604 (fwidth (+ maxlen 3 1 3))
13605 (ncol (/ (- (window-width) 4) fwidth))
13606 (i-face 'org-done)
13607 (c-face 'org-todo)
13608 tg cnt e c char c1 c2 ntable tbl rtn
13609 ov-start ov-end ov-prefix
13610 (exit-after-next org-fast-tag-selection-single-key)
13611 (done-keywords org-done-keywords)
13612 groups ingroup)
13613 (save-excursion
13614 (beginning-of-line 1)
13615 (if (looking-at
13616 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13617 (setq ov-start (match-beginning 1)
13618 ov-end (match-end 1)
13619 ov-prefix "")
13620 (setq ov-start (1- (point-at-eol))
13621 ov-end (1+ ov-start))
13622 (skip-chars-forward "^\n\r")
13623 (setq ov-prefix
13624 (concat
13625 (buffer-substring (1- (point)) (point))
13626 (if (> (current-column) org-tags-column)
13628 (make-string (- org-tags-column (current-column)) ?\ ))))))
13629 (move-overlay org-tags-overlay ov-start ov-end)
13630 (save-window-excursion
13631 (if expert
13632 (set-buffer (get-buffer-create " *Org tags*"))
13633 (delete-other-windows)
13634 (split-window-vertically)
13635 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13636 (erase-buffer)
13637 (org-set-local 'org-done-keywords done-keywords)
13638 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13639 (org-fast-tag-insert "Current" current c-face "\n\n")
13640 (org-fast-tag-show-exit exit-after-next)
13641 (org-set-current-tags-overlay current ov-prefix)
13642 (setq tbl fulltable char ?a cnt 0)
13643 (while (setq e (pop tbl))
13644 (cond
13645 ((equal (car e) :startgroup)
13646 (push '() groups) (setq ingroup t)
13647 (when (not (= cnt 0))
13648 (setq cnt 0)
13649 (insert "\n"))
13650 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13651 ((equal (car e) :endgroup)
13652 (setq ingroup nil cnt 0)
13653 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13654 ((equal e '(:newline))
13655 (when (not (= cnt 0))
13656 (setq cnt 0)
13657 (insert "\n")
13658 (setq e (car tbl))
13659 (while (equal (car tbl) '(:newline))
13660 (insert "\n")
13661 (setq tbl (cdr tbl)))))
13663 (setq tg (copy-sequence (car e)) c2 nil)
13664 (if (cdr e)
13665 (setq c (cdr e))
13666 ;; automatically assign a character.
13667 (setq c1 (string-to-char
13668 (downcase (substring
13669 tg (if (= (string-to-char tg) ?@) 1 0)))))
13670 (if (or (rassoc c1 ntable) (rassoc c1 table))
13671 (while (or (rassoc char ntable) (rassoc char table))
13672 (setq char (1+ char)))
13673 (setq c2 c1))
13674 (setq c (or c2 char)))
13675 (if ingroup (push tg (car groups)))
13676 (setq tg (org-add-props tg nil 'face
13677 (cond
13678 ((not (assoc tg table))
13679 (org-get-todo-face tg))
13680 ((member tg current) c-face)
13681 ((member tg inherited) i-face)
13682 (t nil))))
13683 (if (and (= cnt 0) (not ingroup)) (insert " "))
13684 (insert "[" c "] " tg (make-string
13685 (- fwidth 4 (length tg)) ?\ ))
13686 (push (cons tg c) ntable)
13687 (when (= (setq cnt (1+ cnt)) ncol)
13688 (insert "\n")
13689 (if ingroup (insert " "))
13690 (setq cnt 0)))))
13691 (setq ntable (nreverse ntable))
13692 (insert "\n")
13693 (goto-char (point-min))
13694 (if (not expert) (org-fit-window-to-buffer))
13695 (setq rtn
13696 (catch 'exit
13697 (while t
13698 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13699 (if (not groups) "no " "")
13700 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13701 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13702 (setq org-last-tag-selection-key c)
13703 (cond
13704 ((= c ?\r) (throw 'exit t))
13705 ((= c ?!)
13706 (setq groups (not groups))
13707 (goto-char (point-min))
13708 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13709 ((= c ?\C-c)
13710 (if (not expert)
13711 (org-fast-tag-show-exit
13712 (setq exit-after-next (not exit-after-next)))
13713 (setq expert nil)
13714 (delete-other-windows)
13715 (set-window-buffer (split-window-vertically) " *Org tags*")
13716 (org-switch-to-buffer-other-window " *Org tags*")
13717 (org-fit-window-to-buffer)))
13718 ((or (= c ?\C-g)
13719 (and (= c ?q) (not (rassoc c ntable))))
13720 (org-detach-overlay org-tags-overlay)
13721 (setq quit-flag t))
13722 ((= c ?\ )
13723 (setq current nil)
13724 (if exit-after-next (setq exit-after-next 'now)))
13725 ((= c ?\t)
13726 (condition-case nil
13727 (setq tg (org-icompleting-read
13728 "Tag: "
13729 (or buffer-tags
13730 (with-current-buffer buf
13731 (org-get-buffer-tags)))))
13732 (quit (setq tg "")))
13733 (when (string-match "\\S-" tg)
13734 (add-to-list 'buffer-tags (list tg))
13735 (if (member tg current)
13736 (setq current (delete tg current))
13737 (push tg current)))
13738 (if exit-after-next (setq exit-after-next 'now)))
13739 ((setq e (rassoc c todo-table) tg (car e))
13740 (with-current-buffer buf
13741 (save-excursion (org-todo tg)))
13742 (if exit-after-next (setq exit-after-next 'now)))
13743 ((setq e (rassoc c ntable) tg (car e))
13744 (if (member tg current)
13745 (setq current (delete tg current))
13746 (loop for g in groups do
13747 (if (member tg g)
13748 (mapc (lambda (x)
13749 (setq current (delete x current)))
13750 g)))
13751 (push tg current))
13752 (if exit-after-next (setq exit-after-next 'now))))
13754 ;; Create a sorted list
13755 (setq current
13756 (sort current
13757 (lambda (a b)
13758 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13759 (if (eq exit-after-next 'now) (throw 'exit t))
13760 (goto-char (point-min))
13761 (beginning-of-line 2)
13762 (delete-region (point) (point-at-eol))
13763 (org-fast-tag-insert "Current" current c-face)
13764 (org-set-current-tags-overlay current ov-prefix)
13765 (while (re-search-forward
13766 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13767 (setq tg (match-string 1))
13768 (add-text-properties
13769 (match-beginning 1) (match-end 1)
13770 (list 'face
13771 (cond
13772 ((member tg current) c-face)
13773 ((member tg inherited) i-face)
13774 (t (get-text-property (match-beginning 1) 'face))))))
13775 (goto-char (point-min)))))
13776 (org-detach-overlay org-tags-overlay)
13777 (if rtn
13778 (mapconcat 'identity current ":")
13779 nil))))
13781 (defun org-get-tags-string ()
13782 "Get the TAGS string in the current headline."
13783 (unless (org-at-heading-p t)
13784 (error "Not on a heading"))
13785 (save-excursion
13786 (beginning-of-line 1)
13787 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13788 (org-match-string-no-properties 1)
13789 "")))
13791 (defun org-get-tags ()
13792 "Get the list of tags specified in the current headline."
13793 (org-split-string (org-get-tags-string) ":"))
13795 (defun org-get-buffer-tags ()
13796 "Get a table of all tags used in the buffer, for completion."
13797 (let (tags)
13798 (save-excursion
13799 (goto-char (point-min))
13800 (while (re-search-forward
13801 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13802 (when (equal (char-after (point-at-bol 0)) ?*)
13803 (mapc (lambda (x) (add-to-list 'tags x))
13804 (org-split-string (org-match-string-no-properties 1) ":")))))
13805 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13806 (mapcar 'list tags)))
13808 ;;;; The mapping API
13810 ;;;###autoload
13811 (defun org-map-entries (func &optional match scope &rest skip)
13812 "Call FUNC at each headline selected by MATCH in SCOPE.
13814 FUNC is a function or a lisp form. The function will be called without
13815 arguments, with the cursor positioned at the beginning of the headline.
13816 The return values of all calls to the function will be collected and
13817 returned as a list.
13819 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13820 does not need to preserve point. After evaluation, the cursor will be
13821 moved to the end of the line (presumably of the headline of the
13822 processed entry) and search continues from there. Under some
13823 circumstances, this may not produce the wanted results. For example,
13824 if you have removed (e.g. archived) the current (sub)tree it could
13825 mean that the next entry will be skipped entirely. In such cases, you
13826 can specify the position from where search should continue by making
13827 FUNC set the variable `org-map-continue-from' to the desired buffer
13828 position.
13830 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13831 Only headlines that are matched by this query will be considered during
13832 the iteration. When MATCH is nil or t, all headlines will be
13833 visited by the iteration.
13835 SCOPE determines the scope of this command. It can be any of:
13837 nil The current buffer, respecting the restriction if any
13838 tree The subtree started with the entry at point
13839 region The entries within the active region, if any
13840 region-start-level
13841 The entries within the active region, but only those at
13842 the same level than the first one.
13843 file The current buffer, without restriction
13844 file-with-archives
13845 The current buffer, and any archives associated with it
13846 agenda All agenda files
13847 agenda-with-archives
13848 All agenda files with any archive files associated with them
13849 \(file1 file2 ...)
13850 If this is a list, all files in the list will be scanned
13852 The remaining args are treated as settings for the skipping facilities of
13853 the scanner. The following items can be given here:
13855 archive skip trees with the archive tag.
13856 comment skip trees with the COMMENT keyword
13857 function or Emacs Lisp form:
13858 will be used as value for `org-agenda-skip-function', so whenever
13859 the function returns t, FUNC will not be called for that
13860 entry and search will continue from the point where the
13861 function leaves it.
13863 If your function needs to retrieve the tags including inherited tags
13864 at the *current* entry, you can use the value of the variable
13865 `org-scanner-tags' which will be much faster than getting the value
13866 with `org-get-tags-at'. If your function gets properties with
13867 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13868 to t around the call to `org-entry-properties' to get the same speedup.
13869 Note that if your function moves around to retrieve tags and properties at
13870 a *different* entry, you cannot use these techniques."
13871 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13872 (not (org-region-active-p)))
13873 (let* ((org-agenda-archives-mode nil) ; just to make sure
13874 (org-agenda-skip-archived-trees (memq 'archive skip))
13875 (org-agenda-skip-comment-trees (memq 'comment skip))
13876 (org-agenda-skip-function
13877 (car (org-delete-all '(comment archive) skip)))
13878 (org-tags-match-list-sublevels t)
13879 (start-level (eq scope 'region-start-level))
13880 matcher file res
13881 org-todo-keywords-for-agenda
13882 org-done-keywords-for-agenda
13883 org-todo-keyword-alist-for-agenda
13884 org-drawers-for-agenda
13885 org-tag-alist-for-agenda
13886 todo-only)
13888 (cond
13889 ((eq match t) (setq matcher t))
13890 ((eq match nil) (setq matcher t))
13891 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13893 (save-excursion
13894 (save-restriction
13895 (cond ((eq scope 'tree)
13896 (org-back-to-heading t)
13897 (org-narrow-to-subtree)
13898 (setq scope nil))
13899 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13900 (org-region-active-p))
13901 ;; If needed, set start-level to a string like "2"
13902 (when start-level
13903 (save-excursion
13904 (goto-char (region-beginning))
13905 (unless (org-at-heading-p) (outline-next-heading))
13906 (setq start-level (org-current-level))))
13907 (narrow-to-region (region-beginning)
13908 (save-excursion
13909 (goto-char (region-end))
13910 (unless (and (bolp) (org-at-heading-p))
13911 (outline-next-heading))
13912 (point)))
13913 (setq scope nil)))
13915 (if (not scope)
13916 (progn
13917 (org-prepare-agenda-buffers
13918 (list (buffer-file-name (current-buffer))))
13919 (setq res (org-scan-tags func matcher todo-only start-level)))
13920 ;; Get the right scope
13921 (cond
13922 ((and scope (listp scope) (symbolp (car scope)))
13923 (setq scope (eval scope)))
13924 ((eq scope 'agenda)
13925 (setq scope (org-agenda-files t)))
13926 ((eq scope 'agenda-with-archives)
13927 (setq scope (org-agenda-files t))
13928 (setq scope (org-add-archive-files scope)))
13929 ((eq scope 'file)
13930 (setq scope (list (buffer-file-name))))
13931 ((eq scope 'file-with-archives)
13932 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13933 (org-prepare-agenda-buffers scope)
13934 (while (setq file (pop scope))
13935 (with-current-buffer (org-find-base-buffer-visiting file)
13936 (save-excursion
13937 (save-restriction
13938 (widen)
13939 (goto-char (point-min))
13940 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13941 res)))
13943 ;;;; Properties
13945 ;;; Setting and retrieving properties
13947 (defconst org-special-properties
13948 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13949 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13950 "The special properties valid in Org-mode.
13952 These are properties that are not defined in the property drawer,
13953 but in some other way.")
13955 (defconst org-default-properties
13956 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13957 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13958 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13959 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13960 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13961 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13962 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13963 "Some properties that are used by Org-mode for various purposes.
13964 Being in this list makes sure that they are offered for completion.")
13966 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13967 "Regular expression matching the first line of a property drawer.")
13969 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13970 "Regular expression matching the last line of a property drawer.")
13972 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13973 "Regular expression matching the first line of a property drawer.")
13975 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13976 "Regular expression matching the first line of a property drawer.")
13978 (defconst org-property-drawer-re
13979 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13980 org-property-end-re "\\)\n?")
13981 "Matches an entire property drawer.")
13983 (defconst org-clock-drawer-re
13984 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13985 org-property-end-re "\\)\n?")
13986 "Matches an entire clock drawer.")
13988 (defsubst org-re-property (property)
13989 "Return a regexp matching PROPERTY.
13990 Match group 1 will be set to the value "
13991 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13993 (defun org-property-action ()
13994 "Do an action on properties."
13995 (interactive)
13996 (let (c)
13997 (org-at-property-p)
13998 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13999 (setq c (read-char-exclusive))
14000 (cond
14001 ((equal c ?s)
14002 (call-interactively 'org-set-property))
14003 ((equal c ?d)
14004 (call-interactively 'org-delete-property))
14005 ((equal c ?D)
14006 (call-interactively 'org-delete-property-globally))
14007 ((equal c ?c)
14008 (call-interactively 'org-compute-property-at-point))
14009 (t (error "No such property action %c" c)))))
14011 (defun org-set-effort (&optional value)
14012 "Set the effort property of the current entry.
14013 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14014 allowed value."
14015 (interactive "P")
14016 (if (equal value 0) (setq value 10))
14017 (let* ((completion-ignore-case t)
14018 (prop org-effort-property)
14019 (cur (org-entry-get nil prop))
14020 (allowed (org-property-get-allowed-values nil prop 'table))
14021 (existing (mapcar 'list (org-property-values prop)))
14023 (val (cond
14024 ((stringp value) value)
14025 ((and allowed (integerp value))
14026 (or (car (nth (1- value) allowed))
14027 (car (org-last allowed))))
14028 (allowed
14029 (message "Select 1-9,0, [RET%s]: %s"
14030 (if cur (concat "=" cur) "")
14031 (mapconcat 'car allowed " "))
14032 (setq rpl (read-char-exclusive))
14033 (if (equal rpl ?\r)
14035 (setq rpl (- rpl ?0))
14036 (if (equal rpl 0) (setq rpl 10))
14037 (if (and (> rpl 0) (<= rpl (length allowed)))
14038 (car (nth (1- rpl) allowed))
14039 (org-completing-read "Effort: " allowed nil))))
14041 (let (org-completion-use-ido org-completion-use-iswitchb)
14042 (org-completing-read
14043 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14044 (concat "[" cur "]") "")
14045 ": ")
14046 existing nil nil "" nil cur))))))
14047 (unless (equal (org-entry-get nil prop) val)
14048 (org-entry-put nil prop val))
14049 (message "%s is now %s" prop val)))
14051 (defun org-at-property-p ()
14052 "Is cursor inside a property drawer?"
14053 (save-excursion
14054 (beginning-of-line 1)
14055 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14056 (save-match-data ;; Used by calling procedures
14057 (let ((p (point))
14058 (range (unless (org-before-first-heading-p)
14059 (org-get-property-block))))
14060 (and range (<= (car range) p) (< p (cdr range))))))))
14062 (defun org-get-property-block (&optional beg end force)
14063 "Return the (beg . end) range of the body of the property drawer.
14064 BEG and END can be beginning and end of subtree, if not given
14065 they will be found.
14066 If the drawer does not exist and FORCE is non-nil, create the drawer."
14067 (catch 'exit
14068 (save-excursion
14069 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14070 (end (or end (progn (outline-next-heading) (point)))))
14071 (goto-char beg)
14072 (if (re-search-forward org-property-start-re end t)
14073 (setq beg (1+ (match-end 0)))
14074 (if force
14075 (save-excursion
14076 (org-insert-property-drawer)
14077 (setq end (progn (outline-next-heading) (point))))
14078 (throw 'exit nil))
14079 (goto-char beg)
14080 (if (re-search-forward org-property-start-re end t)
14081 (setq beg (1+ (match-end 0)))))
14082 (if (re-search-forward org-property-end-re end t)
14083 (setq end (match-beginning 0))
14084 (or force (throw 'exit nil))
14085 (goto-char beg)
14086 (setq end beg)
14087 (org-indent-line-function)
14088 (insert ":END:\n"))
14089 (cons beg end)))))
14091 (defun org-entry-properties (&optional pom which specific)
14092 "Get all properties of the entry at point-or-marker POM.
14093 This includes the TODO keyword, the tags, time strings for deadline,
14094 scheduled, and clocking, and any additional properties defined in the
14095 entry. The return value is an alist, keys may occur multiple times
14096 if the property key was used several times.
14097 POM may also be nil, in which case the current entry is used.
14098 If WHICH is nil or `all', get all properties. If WHICH is
14099 `special' or `standard', only get that subclass. If WHICH
14100 is a string only get exactly this property. SPECIFIC can be a string, the
14101 specific property we are interested in. Specifying it can speed
14102 things up because then unnecessary parsing is avoided."
14103 (setq which (or which 'all))
14104 (org-with-point-at pom
14105 (let ((clockstr (substring org-clock-string 0 -1))
14106 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14107 (case-fold-search nil)
14108 beg end range props sum-props key key1 value string clocksum)
14109 (save-excursion
14110 (when (condition-case nil
14111 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14112 (error nil))
14113 (setq beg (point))
14114 (setq sum-props (get-text-property (point) 'org-summaries))
14115 (setq clocksum (get-text-property (point) :org-clock-minutes))
14116 (outline-next-heading)
14117 (setq end (point))
14118 (when (memq which '(all special))
14119 ;; Get the special properties, like TODO and tags
14120 (goto-char beg)
14121 (when (and (or (not specific) (string= specific "TODO"))
14122 (looking-at org-todo-line-regexp) (match-end 2))
14123 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14124 (when (and (or (not specific) (string= specific "PRIORITY"))
14125 (looking-at org-priority-regexp))
14126 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14127 (when (or (not specific) (string= specific "FILE"))
14128 (push (cons "FILE" buffer-file-name) props))
14129 (when (and (or (not specific) (string= specific "TAGS"))
14130 (setq value (org-get-tags-string))
14131 (string-match "\\S-" value))
14132 (push (cons "TAGS" value) props))
14133 (when (and (or (not specific) (string= specific "ALLTAGS"))
14134 (setq value (org-get-tags-at)))
14135 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14136 ":"))
14137 props))
14138 (when (or (not specific) (string= specific "BLOCKED"))
14139 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14140 (when (or (not specific)
14141 (member specific
14142 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14143 "TIMESTAMP" "TIMESTAMP_IA")))
14144 (catch 'match
14145 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14146 (setq key (if (match-end 1)
14147 (substring (org-match-string-no-properties 1)
14148 0 -1))
14149 string (if (equal key clockstr)
14150 (org-no-properties
14151 (org-trim
14152 (buffer-substring
14153 (match-beginning 3) (goto-char
14154 (point-at-eol)))))
14155 (substring (org-match-string-no-properties 3)
14156 1 -1)))
14157 ;; Get the correct property name from the key. This is
14158 ;; necessary if the user has configured time keywords.
14159 (setq key1 (concat key ":"))
14160 (cond
14161 ((not key)
14162 (setq key
14163 (if (= (char-after (match-beginning 3)) ?\[)
14164 "TIMESTAMP_IA" "TIMESTAMP")))
14165 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14166 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14167 ((equal key1 org-closed-string) (setq key "CLOSED"))
14168 ((equal key1 org-clock-string) (setq key "CLOCK")))
14169 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14170 (progn
14171 (push (cons key string) props)
14172 ;; no need to search further if match is found
14173 (throw 'match t))
14174 (when (or (equal key "CLOCK") (not (assoc key props)))
14175 (push (cons key string) props))))))
14178 (when (memq which '(all standard))
14179 ;; Get the standard properties, like :PROP: ...
14180 (setq range (org-get-property-block beg end))
14181 (when range
14182 (goto-char (car range))
14183 (while (re-search-forward
14184 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14185 (cdr range) t)
14186 (setq key (org-match-string-no-properties 1)
14187 value (org-trim (or (org-match-string-no-properties 2) "")))
14188 (unless (member key excluded)
14189 (push (cons key (or value "")) props)))))
14190 (if clocksum
14191 (push (cons "CLOCKSUM"
14192 (org-columns-number-to-string (/ (float clocksum) 60.)
14193 'add_times))
14194 props))
14195 (unless (assoc "CATEGORY" props)
14196 (push (cons "CATEGORY" (org-get-category)) props))
14197 (append sum-props (nreverse props)))))))
14199 (defun org-entry-get (pom property &optional inherit literal-nil)
14200 "Get value of PROPERTY for entry at point-or-marker POM.
14201 If INHERIT is non-nil and the entry does not have the property,
14202 then also check higher levels of the hierarchy.
14203 If INHERIT is the symbol `selective', use inheritance only if the setting
14204 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14205 If the property is present but empty, the return value is the empty string.
14206 If the property is not present at all, nil is returned.
14208 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14209 do not interpret it as the list atom nil. This is used for inheritance
14210 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14211 (org-with-point-at pom
14212 (if (and inherit (if (eq inherit 'selective)
14213 (org-property-inherit-p property)
14215 (org-entry-get-with-inheritance property literal-nil)
14216 (if (member property org-special-properties)
14217 ;; We need a special property. Use `org-entry-properties' to
14218 ;; retrieve it, but specify the wanted property
14219 (cdr (assoc property (org-entry-properties nil 'special property)))
14220 (let ((range (unless (org-before-first-heading-p)
14221 (org-get-property-block)))
14222 (props (list (or (assoc property org-file-properties)
14223 (assoc property org-global-properties)
14224 (assoc property org-global-properties-fixed))))
14225 val)
14226 (flet ((ap (key)
14227 (when (re-search-forward
14228 (org-re-property key) (cdr range) t)
14229 (setq props
14230 (org-update-property-plist
14232 (if (match-end 1)
14233 (org-match-string-no-properties 1) "")
14234 props)))))
14235 (when (and range (goto-char (car range)))
14236 (ap property)
14237 (goto-char (car range))
14238 (while (ap (concat property "+")))
14239 (setq val (cdr (assoc property props)))
14240 (when val (if literal-nil val (org-not-nil val))))))))))
14242 (defun org-property-or-variable-value (var &optional inherit)
14243 "Check if there is a property fixing the value of VAR.
14244 If yes, return this value. If not, return the current value of the variable."
14245 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14246 (if (and prop (stringp prop) (string-match "\\S-" prop))
14247 (read prop)
14248 (symbol-value var))))
14250 (defun org-entry-delete (pom property)
14251 "Delete the property PROPERTY from entry at point-or-marker POM."
14252 (org-with-point-at pom
14253 (if (member property org-special-properties)
14254 nil ; cannot delete these properties.
14255 (let ((range (org-get-property-block)))
14256 (if (and range
14257 (goto-char (car range))
14258 (re-search-forward
14259 (org-re-property property)
14260 (cdr range) t))
14261 (progn
14262 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14264 nil)))))
14266 ;; Multi-values properties are properties that contain multiple values
14267 ;; These values are assumed to be single words, separated by whitespace.
14268 (defun org-entry-add-to-multivalued-property (pom property value)
14269 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14270 (let* ((old (org-entry-get pom property))
14271 (values (and old (org-split-string old "[ \t]"))))
14272 (setq value (org-entry-protect-space value))
14273 (unless (member value values)
14274 (setq values (cons value values))
14275 (org-entry-put pom property
14276 (mapconcat 'identity values " ")))))
14278 (defun org-entry-remove-from-multivalued-property (pom property value)
14279 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14280 (let* ((old (org-entry-get pom property))
14281 (values (and old (org-split-string old "[ \t]"))))
14282 (setq value (org-entry-protect-space value))
14283 (when (member value values)
14284 (setq values (delete value values))
14285 (org-entry-put pom property
14286 (mapconcat 'identity values " ")))))
14288 (defun org-entry-member-in-multivalued-property (pom property value)
14289 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14290 (let* ((old (org-entry-get pom property))
14291 (values (and old (org-split-string old "[ \t]"))))
14292 (setq value (org-entry-protect-space value))
14293 (member value values)))
14295 (defun org-entry-get-multivalued-property (pom property)
14296 "Return a list of values in a multivalued property."
14297 (let* ((value (org-entry-get pom property))
14298 (values (and value (org-split-string value "[ \t]"))))
14299 (mapcar 'org-entry-restore-space values)))
14301 (defun org-entry-put-multivalued-property (pom property &rest values)
14302 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14303 VALUES should be a list of strings. Spaces will be protected."
14304 (org-entry-put pom property
14305 (mapconcat 'org-entry-protect-space values " "))
14306 (let* ((value (org-entry-get pom property))
14307 (values (and value (org-split-string value "[ \t]"))))
14308 (mapcar 'org-entry-restore-space values)))
14310 (defun org-entry-protect-space (s)
14311 "Protect spaces and newline in string S."
14312 (while (string-match " " s)
14313 (setq s (replace-match "%20" t t s)))
14314 (while (string-match "\n" s)
14315 (setq s (replace-match "%0A" t t s)))
14318 (defun org-entry-restore-space (s)
14319 "Restore spaces and newline in string S."
14320 (while (string-match "%20" s)
14321 (setq s (replace-match " " t t s)))
14322 (while (string-match "%0A" s)
14323 (setq s (replace-match "\n" t t s)))
14326 (defvar org-entry-property-inherited-from (make-marker)
14327 "Marker pointing to the entry from where a property was inherited.
14328 Each call to `org-entry-get-with-inheritance' will set this marker to the
14329 location of the entry where the inheritance search matched. If there was
14330 no match, the marker will point nowhere.
14331 Note that also `org-entry-get' calls this function, if the INHERIT flag
14332 is set.")
14334 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14335 "Get entry property, and search higher levels if not present.
14336 The search will stop at the first ancestor which has the property defined.
14337 If the value found is \"nil\", return nil to show that the property
14338 should be considered as undefined (this is the meaning of nil here).
14339 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14340 (move-marker org-entry-property-inherited-from nil)
14341 (let (tmp)
14342 (unless (org-before-first-heading-p)
14343 (save-excursion
14344 (save-restriction
14345 (widen)
14346 (catch 'ex
14347 (while t
14348 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14349 (org-back-to-heading t)
14350 (move-marker org-entry-property-inherited-from (point))
14351 (throw 'ex tmp))
14352 (or (org-up-heading-safe) (throw 'ex nil)))))))
14353 (setq tmp (or tmp
14354 (cdr (assoc property org-file-properties))
14355 (cdr (assoc property org-global-properties))
14356 (cdr (assoc property org-global-properties-fixed))))
14357 (if literal-nil tmp (org-not-nil tmp))))
14359 (defvar org-property-changed-functions nil
14360 "Hook called when the value of a property has changed.
14361 Each hook function should accept two arguments, the name of the property
14362 and the new value.")
14364 (defun org-entry-put (pom property value)
14365 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14366 (org-with-point-at pom
14367 (org-back-to-heading t)
14368 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14369 range)
14370 (cond
14371 ((equal property "TODO")
14372 (when (and (stringp value) (string-match "\\S-" value)
14373 (not (member value org-todo-keywords-1)))
14374 (error "\"%s\" is not a valid TODO state" value))
14375 (if (or (not value)
14376 (not (string-match "\\S-" value)))
14377 (setq value 'none))
14378 (org-todo value)
14379 (org-set-tags nil 'align))
14380 ((equal property "PRIORITY")
14381 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14382 (string-to-char value) ?\ ))
14383 (org-set-tags nil 'align))
14384 ((equal property "SCHEDULED")
14385 (if (re-search-forward org-scheduled-time-regexp end t)
14386 (cond
14387 ((eq value 'earlier) (org-timestamp-change -1 'day))
14388 ((eq value 'later) (org-timestamp-change 1 'day))
14389 (t (call-interactively 'org-schedule)))
14390 (call-interactively 'org-schedule)))
14391 ((equal property "DEADLINE")
14392 (if (re-search-forward org-deadline-time-regexp end t)
14393 (cond
14394 ((eq value 'earlier) (org-timestamp-change -1 'day))
14395 ((eq value 'later) (org-timestamp-change 1 'day))
14396 (t (call-interactively 'org-deadline)))
14397 (call-interactively 'org-deadline)))
14398 ((member property org-special-properties)
14399 (error "The %s property can not yet be set with `org-entry-put'"
14400 property))
14401 (t ; a non-special property
14402 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14403 (setq range (org-get-property-block beg end 'force))
14404 (goto-char (car range))
14405 (if (re-search-forward
14406 (org-re-property property) (cdr range) t)
14407 (progn
14408 (delete-region (match-beginning 0) (match-end 0))
14409 (goto-char (match-beginning 0)))
14410 (goto-char (cdr range))
14411 (insert "\n")
14412 (backward-char 1)
14413 (org-indent-line-function))
14414 (insert ":" property ":")
14415 (and value (insert " " value))
14416 (org-indent-line-function)))))
14417 (run-hook-with-args 'org-property-changed-functions property value)))
14419 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14420 "Get all property keys in the current buffer.
14421 With INCLUDE-SPECIALS, also list the special properties that reflect things
14422 like tags and TODO state.
14423 With INCLUDE-DEFAULTS, also include properties that has special meaning
14424 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14425 and others.
14426 With INCLUDE-COLUMNS, also include property names given in COLUMN
14427 formats in the current buffer."
14428 (let (rtn range cfmt s p)
14429 (save-excursion
14430 (save-restriction
14431 (widen)
14432 (goto-char (point-min))
14433 (while (re-search-forward org-property-start-re nil t)
14434 (setq range (org-get-property-block))
14435 (goto-char (car range))
14436 (while (re-search-forward
14437 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14438 (cdr range) t)
14439 (add-to-list 'rtn (org-match-string-no-properties 1)))
14440 (outline-next-heading))))
14442 (when include-specials
14443 (setq rtn (append org-special-properties rtn)))
14445 (when include-defaults
14446 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14447 (add-to-list 'rtn org-effort-property))
14449 (when include-columns
14450 (save-excursion
14451 (save-restriction
14452 (widen)
14453 (goto-char (point-min))
14454 (while (re-search-forward
14455 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14456 nil t)
14457 (setq cfmt (match-string 2) s 0)
14458 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14459 cfmt s)
14460 (setq s (match-end 0)
14461 p (match-string 1 cfmt))
14462 (unless (or (equal p "ITEM")
14463 (member p org-special-properties))
14464 (add-to-list 'rtn (match-string 1 cfmt))))))))
14466 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14468 (defun org-property-values (key)
14469 "Return a list of all values of property KEY in the current buffer."
14470 (save-excursion
14471 (save-restriction
14472 (widen)
14473 (goto-char (point-min))
14474 (let ((re (org-re-property key))
14475 values)
14476 (while (re-search-forward re nil t)
14477 (add-to-list 'values (org-trim (match-string 1))))
14478 (delete "" values)))))
14480 (defun org-insert-property-drawer ()
14481 "Insert a property drawer into the current entry."
14482 (interactive)
14483 (org-back-to-heading t)
14484 (looking-at org-outline-regexp)
14485 (let ((indent (if org-adapt-indentation
14486 (- (match-end 0)(match-beginning 0))
14488 (beg (point))
14489 (re (concat "^[ \t]*" org-keyword-time-regexp))
14490 end hiddenp)
14491 (outline-next-heading)
14492 (setq end (point))
14493 (goto-char beg)
14494 (while (re-search-forward re end t))
14495 (setq hiddenp (outline-invisible-p))
14496 (end-of-line 1)
14497 (and (equal (char-after) ?\n) (forward-char 1))
14498 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14499 (if (member (match-string 1) '("CLOCK:" ":END:"))
14500 ;; just skip this line
14501 (beginning-of-line 2)
14502 ;; Drawer start, find the end
14503 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14504 (beginning-of-line 1)))
14505 (org-skip-over-state-notes)
14506 (skip-chars-backward " \t\n\r")
14507 (if (eq (char-before) ?*) (forward-char 1))
14508 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14509 (beginning-of-line 0)
14510 (org-indent-to-column indent)
14511 (beginning-of-line 2)
14512 (org-indent-to-column indent)
14513 (beginning-of-line 0)
14514 (if hiddenp
14515 (save-excursion
14516 (org-back-to-heading t)
14517 (hide-entry))
14518 (org-flag-drawer t))))
14520 (defvar org-property-set-functions-alist nil
14521 "Property set function alist.
14522 Each entry should have the following format:
14524 (PROPERTY . READ-FUNCTION)
14526 The read function will be called with the same argument as
14527 `org-completing-read'.")
14529 (defun org-set-property-function (property)
14530 "Get the function that should be used to set PROPERTY.
14531 This is computed according to `org-property-set-functions-alist'."
14532 (or (cdr (assoc property org-property-set-functions-alist))
14533 'org-completing-read))
14535 (defun org-read-property-value (property)
14536 "Read PROPERTY value from user."
14537 (let* ((completion-ignore-case t)
14538 (allowed (org-property-get-allowed-values nil property 'table))
14539 (cur (org-entry-get nil property))
14540 (prompt (concat property " value"
14541 (if (and cur (string-match "\\S-" cur))
14542 (concat " [" cur "]") "") ": "))
14543 (set-function (org-set-property-function property))
14544 (val (if allowed
14545 (funcall set-function prompt allowed nil
14546 (not (get-text-property 0 'org-unrestricted
14547 (caar allowed))))
14548 (let (org-completion-use-ido org-completion-use-iswitchb)
14549 (funcall set-function prompt
14550 (mapcar 'list (org-property-values property))
14551 nil nil "" nil cur)))))
14552 (if (equal val "")
14554 val)))
14556 (defvar org-last-set-property nil)
14557 (defun org-read-property-name ()
14558 "Read a property name."
14559 (let* ((completion-ignore-case t)
14560 (keys (org-buffer-property-keys nil t t))
14561 (default-prop (or (save-excursion
14562 (save-match-data
14563 (beginning-of-line)
14564 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14565 (null (string= (match-string 1) "END"))
14566 (match-string 1))))
14567 org-last-set-property))
14568 (property (org-icompleting-read
14569 (concat "Property"
14570 (if default-prop (concat " [" default-prop "]") "")
14571 ": ")
14572 (mapcar 'list keys)
14573 nil nil nil nil
14574 default-prop
14576 (if (member property keys)
14577 property
14578 (or (cdr (assoc (downcase property)
14579 (mapcar (lambda (x) (cons (downcase x) x))
14580 keys)))
14581 property))))
14583 (defun org-set-property (property value)
14584 "In the current entry, set PROPERTY to VALUE.
14585 When called interactively, this will prompt for a property name, offering
14586 completion on existing and default properties. And then it will prompt
14587 for a value, offering completion either on allowed values (via an inherited
14588 xxx_ALL property) or on existing values in other instances of this property
14589 in the current file."
14590 (interactive (list nil nil))
14591 (let* ((property (or property (org-read-property-name)))
14592 (value (or value (org-read-property-value property)))
14593 (fn (assoc property org-properties-postprocess-alist)))
14594 (setq org-last-set-property property)
14595 ;; Possibly postprocess the inserted value:
14596 (when fn (setq value (funcall (cadr fn) value)))
14597 (unless (equal (org-entry-get nil property) value)
14598 (org-entry-put nil property value))))
14600 (defun org-delete-property (property)
14601 "In the current entry, delete PROPERTY."
14602 (interactive
14603 (let* ((completion-ignore-case t)
14604 (prop (org-icompleting-read "Property: "
14605 (org-entry-properties nil 'standard))))
14606 (list prop)))
14607 (message "Property %s %s" property
14608 (if (org-entry-delete nil property)
14609 "deleted"
14610 "was not present in the entry")))
14612 (defun org-delete-property-globally (property)
14613 "Remove PROPERTY globally, from all entries."
14614 (interactive
14615 (let* ((completion-ignore-case t)
14616 (prop (org-icompleting-read
14617 "Globally remove property: "
14618 (mapcar 'list (org-buffer-property-keys)))))
14619 (list prop)))
14620 (save-excursion
14621 (save-restriction
14622 (widen)
14623 (goto-char (point-min))
14624 (let ((cnt 0))
14625 (while (re-search-forward
14626 (org-re-property property)
14627 nil t)
14628 (setq cnt (1+ cnt))
14629 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14630 (message "Property \"%s\" removed from %d entries" property cnt)))))
14632 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14634 (defun org-compute-property-at-point ()
14635 "Compute the property at point.
14636 This looks for an enclosing column format, extracts the operator and
14637 then applies it to the property in the column format's scope."
14638 (interactive)
14639 (unless (org-at-property-p)
14640 (error "Not at a property"))
14641 (let ((prop (org-match-string-no-properties 2)))
14642 (org-columns-get-format-and-top-level)
14643 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14644 (error "No operator defined for property %s" prop))
14645 (org-columns-compute prop)))
14647 (defvar org-property-allowed-value-functions nil
14648 "Hook for functions supplying allowed values for a specific property.
14649 The functions must take a single argument, the name of the property, and
14650 return a flat list of allowed values. If \":ETC\" is one of
14651 the values, this means that these values are intended as defaults for
14652 completion, but that other values should be allowed too.
14653 The functions must return nil if they are not responsible for this
14654 property.")
14656 (defun org-property-get-allowed-values (pom property &optional table)
14657 "Get allowed values for the property PROPERTY.
14658 When TABLE is non-nil, return an alist that can directly be used for
14659 completion."
14660 (let (vals)
14661 (cond
14662 ((equal property "TODO")
14663 (setq vals (org-with-point-at pom
14664 (append org-todo-keywords-1 '("")))))
14665 ((equal property "PRIORITY")
14666 (let ((n org-lowest-priority))
14667 (while (>= n org-highest-priority)
14668 (push (char-to-string n) vals)
14669 (setq n (1- n)))))
14670 ((member property org-special-properties))
14671 ((setq vals (run-hook-with-args-until-success
14672 'org-property-allowed-value-functions property)))
14674 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14675 (when (and vals (string-match "\\S-" vals))
14676 (setq vals (car (read-from-string (concat "(" vals ")"))))
14677 (setq vals (mapcar (lambda (x)
14678 (cond ((stringp x) x)
14679 ((numberp x) (number-to-string x))
14680 ((symbolp x) (symbol-name x))
14681 (t "???")))
14682 vals)))))
14683 (when (member ":ETC" vals)
14684 (setq vals (remove ":ETC" vals))
14685 (org-add-props (car vals) '(org-unrestricted t)))
14686 (if table (mapcar 'list vals) vals)))
14688 (defun org-property-previous-allowed-value (&optional previous)
14689 "Switch to the next allowed value for this property."
14690 (interactive)
14691 (org-property-next-allowed-value t))
14693 (defun org-property-next-allowed-value (&optional previous)
14694 "Switch to the next allowed value for this property."
14695 (interactive)
14696 (unless (org-at-property-p)
14697 (error "Not at a property"))
14698 (let* ((key (match-string 2))
14699 (value (match-string 3))
14700 (allowed (or (org-property-get-allowed-values (point) key)
14701 (and (member value '("[ ]" "[-]" "[X]"))
14702 '("[ ]" "[X]"))))
14703 nval)
14704 (unless allowed
14705 (error "Allowed values for this property have not been defined"))
14706 (if previous (setq allowed (reverse allowed)))
14707 (if (member value allowed)
14708 (setq nval (car (cdr (member value allowed)))))
14709 (setq nval (or nval (car allowed)))
14710 (if (equal nval value)
14711 (error "Only one allowed value for this property"))
14712 (org-at-property-p)
14713 (replace-match (concat " :" key ": " nval) t t)
14714 (org-indent-line-function)
14715 (beginning-of-line 1)
14716 (skip-chars-forward " \t")
14717 (run-hook-with-args 'org-property-changed-functions key nval)))
14719 (defun org-find-olp (path &optional this-buffer)
14720 "Return a marker pointing to the entry at outline path OLP.
14721 If anything goes wrong, throw an error.
14722 You can wrap this call to catch the error like this:
14724 (condition-case msg
14725 (org-mobile-locate-entry (match-string 4))
14726 (error (nth 1 msg)))
14728 The return value will then be either a string with the error message,
14729 or a marker if everything is OK.
14731 If THIS-BUFFER is set, the outline path does not contain a file,
14732 only headings."
14733 (let* ((file (if this-buffer buffer-file-name (pop path)))
14734 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14735 (level 1)
14736 (lmin 1)
14737 (lmax 1)
14738 limit re end found pos heading cnt flevel)
14739 (unless buffer (error "File not found :%s" file))
14740 (with-current-buffer buffer
14741 (save-excursion
14742 (save-restriction
14743 (widen)
14744 (setq limit (point-max))
14745 (goto-char (point-min))
14746 (while (setq heading (pop path))
14747 (setq re (format org-complex-heading-regexp-format
14748 (regexp-quote heading)))
14749 (setq cnt 0 pos (point))
14750 (while (re-search-forward re end t)
14751 (setq level (- (match-end 1) (match-beginning 1)))
14752 (if (and (>= level lmin) (<= level lmax))
14753 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14754 (when (= cnt 0) (error "Heading not found on level %d: %s"
14755 lmax heading))
14756 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14757 lmax heading))
14758 (goto-char found)
14759 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14760 (setq end (save-excursion (org-end-of-subtree t t))))
14761 (when (org-at-heading-p)
14762 (move-marker (make-marker) (point))))))))
14764 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14765 "Find node HEADING in BUFFER.
14766 Return a marker to the heading if it was found, or nil if not.
14767 If POS-ONLY is set, return just the position instead of a marker.
14769 The heading text must match exact, but it may have a TODO keyword,
14770 a priority cookie and tags in the standard locations."
14771 (with-current-buffer (or buffer (current-buffer))
14772 (save-excursion
14773 (save-restriction
14774 (widen)
14775 (goto-char (point-min))
14776 (let (case-fold-search)
14777 (if (re-search-forward
14778 (format org-complex-heading-regexp-format
14779 (regexp-quote heading)) nil t)
14780 (if pos-only
14781 (match-beginning 0)
14782 (move-marker (make-marker) (match-beginning 0)))))))))
14784 (defun org-find-exact-heading-in-directory (heading &optional dir)
14785 "Find Org node headline HEADING in all .org files in directory DIR.
14786 When the target headline is found, return a marker to this location."
14787 (let ((files (directory-files (or dir default-directory)
14788 nil "\\`[^.#].*\\.org\\'"))
14789 file visiting m buffer)
14790 (catch 'found
14791 (while (setq file (pop files))
14792 (message "trying %s" file)
14793 (setq visiting (org-find-base-buffer-visiting file))
14794 (setq buffer (or visiting (find-file-noselect file)))
14795 (setq m (org-find-exact-headline-in-buffer
14796 heading buffer))
14797 (when (and (not m) (not visiting)) (kill-buffer buffer))
14798 (and m (throw 'found m))))))
14800 (defun org-find-entry-with-id (ident)
14801 "Locate the entry that contains the ID property with exact value IDENT.
14802 IDENT can be a string, a symbol or a number, this function will search for
14803 the string representation of it.
14804 Return the position where this entry starts, or nil if there is no such entry."
14805 (interactive "sID: ")
14806 (let ((id (cond
14807 ((stringp ident) ident)
14808 ((symbol-name ident) (symbol-name ident))
14809 ((numberp ident) (number-to-string ident))
14810 (t (error "IDENT %s must be a string, symbol or number" ident))))
14811 (case-fold-search nil))
14812 (save-excursion
14813 (save-restriction
14814 (widen)
14815 (goto-char (point-min))
14816 (when (re-search-forward
14817 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14818 nil t)
14819 (org-back-to-heading t)
14820 (point))))))
14822 ;;;; Timestamps
14824 (defvar org-last-changed-timestamp nil)
14825 (defvar org-last-inserted-timestamp nil
14826 "The last time stamp inserted with `org-insert-time-stamp'.")
14827 (defvar org-time-was-given) ; dynamically scoped parameter
14828 (defvar org-end-time-was-given) ; dynamically scoped parameter
14829 (defvar org-ts-what) ; dynamically scoped parameter
14831 (defun org-time-stamp (arg &optional inactive)
14832 "Prompt for a date/time and insert a time stamp.
14833 If the user specifies a time like HH:MM, or if this command is called
14834 with a prefix argument, the time stamp will contain date and time.
14835 Otherwise, only the date will be included. All parts of a date not
14836 specified by the user will be filled in from the current date/time.
14837 So if you press just return without typing anything, the time stamp
14838 will represent the current date/time. If there is already a timestamp
14839 at the cursor, it will be modified."
14840 (interactive "P")
14841 (let* ((ts nil)
14842 (default-time
14843 ;; Default time is either today, or, when entering a range,
14844 ;; the range start.
14845 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14846 (save-excursion
14847 (re-search-backward
14848 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14849 (- (point) 20) t)))
14850 (apply 'encode-time (org-parse-time-string (match-string 1)))
14851 (current-time)))
14852 (default-input (and ts (org-get-compact-tod ts)))
14853 (repeater (save-excursion
14854 (save-match-data
14855 (beginning-of-line)
14856 (when (re-search-forward
14857 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14858 (save-excursion (progn (end-of-line) (point))) t)
14859 (match-string 0)))))
14860 org-time-was-given org-end-time-was-given time)
14861 (cond
14862 ((and (org-at-timestamp-p t)
14863 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14864 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14865 (insert "--")
14866 (setq time (let ((this-command this-command))
14867 (org-read-date arg 'totime nil nil
14868 default-time default-input)))
14869 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14870 ((org-at-timestamp-p t)
14871 (setq time (let ((this-command this-command))
14872 (org-read-date arg 'totime nil nil default-time default-input)))
14873 (when (org-at-timestamp-p t) ; just to get the match data
14874 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14875 (replace-match "")
14876 (setq org-last-changed-timestamp
14877 (org-insert-time-stamp
14878 time (or org-time-was-given arg)
14879 inactive nil nil (list org-end-time-was-given)))
14880 (when repeater (goto-char (1- (point))) (insert " " repeater)
14881 (setq org-last-changed-timestamp
14882 (concat (substring org-last-inserted-timestamp 0 -1)
14883 " " repeater ">"))))
14884 (message "Timestamp updated"))
14886 (setq time (let ((this-command this-command))
14887 (org-read-date arg 'totime nil nil default-time default-input)))
14888 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14889 nil nil (list org-end-time-was-given))))))
14891 ;; FIXME: can we use this for something else, like computing time differences?
14892 (defun org-get-compact-tod (s)
14893 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14894 (let* ((t1 (match-string 1 s))
14895 (h1 (string-to-number (match-string 2 s)))
14896 (m1 (string-to-number (match-string 3 s)))
14897 (t2 (and (match-end 4) (match-string 5 s)))
14898 (h2 (and t2 (string-to-number (match-string 6 s))))
14899 (m2 (and t2 (string-to-number (match-string 7 s))))
14900 dh dm)
14901 (if (not t2)
14903 (setq dh (- h2 h1) dm (- m2 m1))
14904 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14905 (concat t1 "+" (number-to-string dh)
14906 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14908 (defun org-time-stamp-inactive (&optional arg)
14909 "Insert an inactive time stamp.
14910 An inactive time stamp is enclosed in square brackets instead of angle
14911 brackets. It is inactive in the sense that it does not trigger agenda entries,
14912 does not link to the calendar and cannot be changed with the S-cursor keys.
14913 So these are more for recording a certain time/date."
14914 (interactive "P")
14915 (org-time-stamp arg 'inactive))
14917 (defvar org-date-ovl (make-overlay 1 1))
14918 (overlay-put org-date-ovl 'face 'org-date-selected)
14919 (org-detach-overlay org-date-ovl)
14921 (defvar org-ans1) ; dynamically scoped parameter
14922 (defvar org-ans2) ; dynamically scoped parameter
14924 (defvar org-plain-time-of-day-regexp) ; defined below
14926 (defvar org-overriding-default-time nil) ; dynamically scoped
14927 (defvar org-read-date-overlay nil)
14928 (defvar org-dcst nil) ; dynamically scoped
14929 (defvar org-read-date-history nil)
14930 (defvar org-read-date-final-answer nil)
14931 (defvar org-read-date-analyze-futurep nil)
14932 (defvar org-read-date-analyze-forced-year nil)
14934 (defun org-read-date (&optional org-with-time to-time from-string prompt
14935 default-time default-input)
14936 "Read a date, possibly a time, and make things smooth for the user.
14937 The prompt will suggest to enter an ISO date, but you can also enter anything
14938 which will at least partially be understood by `parse-time-string'.
14939 Unrecognized parts of the date will default to the current day, month, year,
14940 hour and minute. If this command is called to replace a timestamp at point,
14941 or to enter the second timestamp of a range, the default time is taken
14942 from the existing stamp. Furthermore, the command prefers the future,
14943 so if you are giving a date where the year is not given, and the day-month
14944 combination is already past in the current year, it will assume you
14945 mean next year. For details, see the manual. A few examples:
14947 3-2-5 --> 2003-02-05
14948 feb 15 --> currentyear-02-15
14949 2/15 --> currentyear-02-15
14950 sep 12 9 --> 2009-09-12
14951 12:45 --> today 12:45
14952 22 sept 0:34 --> currentyear-09-22 0:34
14953 12 --> currentyear-currentmonth-12
14954 Fri --> nearest Friday (today or later)
14955 etc.
14957 Furthermore you can specify a relative date by giving, as the *first* thing
14958 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14959 change in days weeks, months, years.
14960 With a single plus or minus, the date is relative to today. With a double
14961 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14962 +4d --> four days from today
14963 +4 --> same as above
14964 +2w --> two weeks from today
14965 ++5 --> five days from default date
14967 The function understands only English month and weekday abbreviations.
14969 While prompting, a calendar is popped up - you can also select the
14970 date with the mouse (button 1). The calendar shows a period of three
14971 months. To scroll it to other months, use the keys `>' and `<'.
14972 If you don't like the calendar, turn it off with
14973 \(setq org-read-date-popup-calendar nil)
14975 With optional argument TO-TIME, the date will immediately be converted
14976 to an internal time.
14977 With an optional argument WITH-TIME, the prompt will suggest to also
14978 insert a time. Note that when WITH-TIME is not set, you can still
14979 enter a time, and this function will inform the calling routine about
14980 this change. The calling routine may then choose to change the format
14981 used to insert the time stamp into the buffer to include the time.
14982 With optional argument FROM-STRING, read from this string instead from
14983 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14984 the time/date that is used for everything that is not specified by the
14985 user."
14986 (require 'parse-time)
14987 (let* ((org-time-stamp-rounding-minutes
14988 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14989 (org-dcst org-display-custom-times)
14990 (ct (org-current-time))
14991 (org-def (or org-overriding-default-time default-time ct))
14992 (org-defdecode (decode-time org-def))
14993 (dummy (progn
14994 (when (< (nth 2 org-defdecode) org-extend-today-until)
14995 (setcar (nthcdr 2 org-defdecode) -1)
14996 (setcar (nthcdr 1 org-defdecode) 59)
14997 (setq org-def (apply 'encode-time org-defdecode)
14998 org-defdecode (decode-time org-def)))))
14999 (calendar-frame-setup nil)
15000 (calendar-setup nil)
15001 (calendar-move-hook nil)
15002 (calendar-view-diary-initially-flag nil)
15003 (calendar-view-holidays-initially-flag nil)
15004 (timestr (format-time-string
15005 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15006 (prompt (concat (if prompt (concat prompt " ") "")
15007 (format "Date+time [%s]: " timestr)))
15008 ans (org-ans0 "") org-ans1 org-ans2 final)
15010 (cond
15011 (from-string (setq ans from-string))
15012 (org-read-date-popup-calendar
15013 (save-excursion
15014 (save-window-excursion
15015 (calendar)
15016 (unwind-protect
15017 (progn
15018 (calendar-forward-day (- (time-to-days org-def)
15019 (calendar-absolute-from-gregorian
15020 (calendar-current-date))))
15021 (org-eval-in-calendar nil t)
15022 (let* ((old-map (current-local-map))
15023 (map (copy-keymap calendar-mode-map))
15024 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15025 (org-defkey map (kbd "RET") 'org-calendar-select)
15026 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15027 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15028 (org-defkey minibuffer-local-map [(meta shift left)]
15029 (lambda () (interactive)
15030 (org-eval-in-calendar '(calendar-backward-month 1))))
15031 (org-defkey minibuffer-local-map [(meta shift right)]
15032 (lambda () (interactive)
15033 (org-eval-in-calendar '(calendar-forward-month 1))))
15034 (org-defkey minibuffer-local-map [(meta shift up)]
15035 (lambda () (interactive)
15036 (org-eval-in-calendar '(calendar-backward-year 1))))
15037 (org-defkey minibuffer-local-map [(meta shift down)]
15038 (lambda () (interactive)
15039 (org-eval-in-calendar '(calendar-forward-year 1))))
15040 (org-defkey minibuffer-local-map [?\e (shift left)]
15041 (lambda () (interactive)
15042 (org-eval-in-calendar '(calendar-backward-month 1))))
15043 (org-defkey minibuffer-local-map [?\e (shift right)]
15044 (lambda () (interactive)
15045 (org-eval-in-calendar '(calendar-forward-month 1))))
15046 (org-defkey minibuffer-local-map [?\e (shift up)]
15047 (lambda () (interactive)
15048 (org-eval-in-calendar '(calendar-backward-year 1))))
15049 (org-defkey minibuffer-local-map [?\e (shift down)]
15050 (lambda () (interactive)
15051 (org-eval-in-calendar '(calendar-forward-year 1))))
15052 (org-defkey minibuffer-local-map [(shift up)]
15053 (lambda () (interactive)
15054 (org-eval-in-calendar '(calendar-backward-week 1))))
15055 (org-defkey minibuffer-local-map [(shift down)]
15056 (lambda () (interactive)
15057 (org-eval-in-calendar '(calendar-forward-week 1))))
15058 (org-defkey minibuffer-local-map [(shift left)]
15059 (lambda () (interactive)
15060 (org-eval-in-calendar '(calendar-backward-day 1))))
15061 (org-defkey minibuffer-local-map [(shift right)]
15062 (lambda () (interactive)
15063 (org-eval-in-calendar '(calendar-forward-day 1))))
15064 (org-defkey minibuffer-local-map ">"
15065 (lambda () (interactive)
15066 (org-eval-in-calendar '(scroll-calendar-left 1))))
15067 (org-defkey minibuffer-local-map "<"
15068 (lambda () (interactive)
15069 (org-eval-in-calendar '(scroll-calendar-right 1))))
15070 (org-defkey minibuffer-local-map "\C-v"
15071 (lambda () (interactive)
15072 (org-eval-in-calendar
15073 '(calendar-scroll-left-three-months 1))))
15074 (org-defkey minibuffer-local-map "\M-v"
15075 (lambda () (interactive)
15076 (org-eval-in-calendar
15077 '(calendar-scroll-right-three-months 1))))
15078 (run-hooks 'org-read-date-minibuffer-setup-hook)
15079 (unwind-protect
15080 (progn
15081 (use-local-map map)
15082 (add-hook 'post-command-hook 'org-read-date-display)
15083 (setq org-ans0 (read-string prompt default-input
15084 'org-read-date-history nil))
15085 ;; org-ans0: from prompt
15086 ;; org-ans1: from mouse click
15087 ;; org-ans2: from calendar motion
15088 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15089 (remove-hook 'post-command-hook 'org-read-date-display)
15090 (use-local-map old-map)
15091 (when org-read-date-overlay
15092 (delete-overlay org-read-date-overlay)
15093 (setq org-read-date-overlay nil)))))
15094 (bury-buffer "*Calendar*")))))
15096 (t ; Naked prompt only
15097 (unwind-protect
15098 (setq ans (read-string prompt default-input
15099 'org-read-date-history timestr))
15100 (when org-read-date-overlay
15101 (delete-overlay org-read-date-overlay)
15102 (setq org-read-date-overlay nil)))))
15104 (setq final (org-read-date-analyze ans org-def org-defdecode))
15106 (when org-read-date-analyze-forced-year
15107 (message "Year was forced into %s"
15108 (if org-read-date-force-compatible-dates
15109 "compatible range (1970-2037)"
15110 "range representable on this machine"))
15111 (ding))
15113 ;; One round trip to get rid of 34th of August and stuff like that....
15114 (setq final (decode-time (apply 'encode-time final)))
15116 (setq org-read-date-final-answer ans)
15118 (if to-time
15119 (apply 'encode-time final)
15120 (if (and (boundp 'org-time-was-given) org-time-was-given)
15121 (format "%04d-%02d-%02d %02d:%02d"
15122 (nth 5 final) (nth 4 final) (nth 3 final)
15123 (nth 2 final) (nth 1 final))
15124 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15126 (defvar org-def)
15127 (defvar org-defdecode)
15128 (defvar org-with-time)
15129 (defun org-read-date-display ()
15130 "Display the current date prompt interpretation in the minibuffer."
15131 (when org-read-date-display-live
15132 (when org-read-date-overlay
15133 (delete-overlay org-read-date-overlay))
15134 (let ((p (point)))
15135 (end-of-line 1)
15136 (while (not (equal (buffer-substring
15137 (max (point-min) (- (point) 4)) (point))
15138 " "))
15139 (insert " "))
15140 (goto-char p))
15141 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15142 " " (or org-ans1 org-ans2)))
15143 (org-end-time-was-given nil)
15144 (f (org-read-date-analyze ans org-def org-defdecode))
15145 (fmts (if org-dcst
15146 org-time-stamp-custom-formats
15147 org-time-stamp-formats))
15148 (fmt (if (or org-with-time
15149 (and (boundp 'org-time-was-given) org-time-was-given))
15150 (cdr fmts)
15151 (car fmts)))
15152 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15153 (when (and org-end-time-was-given
15154 (string-match org-plain-time-of-day-regexp txt))
15155 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15156 org-end-time-was-given
15157 (substring txt (match-end 0)))))
15158 (when org-read-date-analyze-futurep
15159 (setq txt (concat txt " (=>F)")))
15160 (setq org-read-date-overlay
15161 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15162 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15164 (defun org-read-date-analyze (ans org-def org-defdecode)
15165 "Analyze the combined answer of the date prompt."
15166 ;; FIXME: cleanup and comment
15167 (let ((nowdecode (decode-time (current-time)))
15168 delta deltan deltaw deltadef year month day
15169 hour minute second wday pm h2 m2 tl wday1
15170 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15171 (setq org-read-date-analyze-futurep nil
15172 org-read-date-analyze-forced-year nil)
15173 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15174 (setq ans "+0"))
15176 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15177 (setq ans (replace-match "" t t ans)
15178 deltan (car delta)
15179 deltaw (nth 1 delta)
15180 deltadef (nth 2 delta)))
15182 ;; Check if there is an iso week date in there
15183 ;; If yes, store the info and postpone interpreting it until the rest
15184 ;; of the parsing is done
15185 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15186 (setq iso-year (if (match-end 1)
15187 (org-small-year-to-year
15188 (string-to-number (match-string 1 ans))))
15189 iso-weekday (if (match-end 3)
15190 (string-to-number (match-string 3 ans)))
15191 iso-week (string-to-number (match-string 2 ans)))
15192 (setq ans (replace-match "" t t ans)))
15194 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15195 (when (string-match
15196 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15197 (setq year (if (match-end 2)
15198 (string-to-number (match-string 2 ans))
15199 (progn (setq kill-year t)
15200 (string-to-number (format-time-string "%Y"))))
15201 month (string-to-number (match-string 3 ans))
15202 day (string-to-number (match-string 4 ans)))
15203 (if (< year 100) (setq year (+ 2000 year)))
15204 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15205 t nil ans)))
15207 ;; Help matching dotted european dates
15208 (when (string-match
15209 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15210 (setq year (if (match-end 3)
15211 (string-to-number (match-string 3 ans))
15212 (progn (setq kill-year t)
15213 (string-to-number (format-time-string "%Y"))))
15214 day (string-to-number (match-string 1 ans))
15215 month (string-to-number (match-string 2 ans))
15216 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15217 t nil ans)))
15219 ;; Help matching american dates, like 5/30 or 5/30/7
15220 (when (string-match
15221 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15222 (setq year (if (match-end 4)
15223 (string-to-number (match-string 4 ans))
15224 (progn (setq kill-year t)
15225 (string-to-number (format-time-string "%Y"))))
15226 month (string-to-number (match-string 1 ans))
15227 day (string-to-number (match-string 2 ans)))
15228 (if (< year 100) (setq year (+ 2000 year)))
15229 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15230 t nil ans)))
15231 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15232 ;; If there is a time with am/pm, and *no* time without it, we convert
15233 ;; so that matching will be successful.
15234 (loop for i from 1 to 2 do ; twice, for end time as well
15235 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15236 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15237 (setq hour (string-to-number (match-string 1 ans))
15238 minute (if (match-end 3)
15239 (string-to-number (match-string 3 ans))
15241 pm (equal ?p
15242 (string-to-char (downcase (match-string 4 ans)))))
15243 (if (and (= hour 12) (not pm))
15244 (setq hour 0)
15245 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15246 (setq ans (replace-match (format "%02d:%02d" hour minute)
15247 t t ans))))
15249 ;; Check if a time range is given as a duration
15250 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15251 (setq hour (string-to-number (match-string 1 ans))
15252 h2 (+ hour (string-to-number (match-string 3 ans)))
15253 minute (string-to-number (match-string 2 ans))
15254 m2 (+ minute (if (match-end 5) (string-to-number
15255 (match-string 5 ans))0)))
15256 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15257 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15258 t t ans)))
15260 ;; Check if there is a time range
15261 (when (boundp 'org-end-time-was-given)
15262 (setq org-time-was-given nil)
15263 (when (and (string-match org-plain-time-of-day-regexp ans)
15264 (match-end 8))
15265 (setq org-end-time-was-given (match-string 8 ans))
15266 (setq ans (concat (substring ans 0 (match-beginning 7))
15267 (substring ans (match-end 7))))))
15269 (setq tl (parse-time-string ans)
15270 day (or (nth 3 tl) (nth 3 org-defdecode))
15271 month (or (nth 4 tl)
15272 (if (and org-read-date-prefer-future
15273 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15274 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15275 (nth 4 org-defdecode)))
15276 year (or (and (not kill-year) (nth 5 tl))
15277 (if (and org-read-date-prefer-future
15278 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15279 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15280 (nth 5 org-defdecode)))
15281 hour (or (nth 2 tl) (nth 2 org-defdecode))
15282 minute (or (nth 1 tl) (nth 1 org-defdecode))
15283 second (or (nth 0 tl) 0)
15284 wday (nth 6 tl))
15286 (when (and (eq org-read-date-prefer-future 'time)
15287 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15288 (equal day (nth 3 nowdecode))
15289 (equal month (nth 4 nowdecode))
15290 (equal year (nth 5 nowdecode))
15291 (nth 2 tl)
15292 (or (< (nth 2 tl) (nth 2 nowdecode))
15293 (and (= (nth 2 tl) (nth 2 nowdecode))
15294 (nth 1 tl)
15295 (< (nth 1 tl) (nth 1 nowdecode)))))
15296 (setq day (1+ day)
15297 futurep t))
15299 ;; Special date definitions below
15300 (cond
15301 (iso-week
15302 ;; There was an iso week
15303 (require 'cal-iso)
15304 (setq futurep nil)
15305 (setq year (or iso-year year)
15306 day (or iso-weekday wday 1)
15307 wday nil ; to make sure that the trigger below does not match
15308 iso-date (calendar-gregorian-from-absolute
15309 (calendar-absolute-from-iso
15310 (list iso-week day year))))
15311 ; FIXME: Should we also push ISO weeks into the future?
15312 ; (when (and org-read-date-prefer-future
15313 ; (not iso-year)
15314 ; (< (calendar-absolute-from-gregorian iso-date)
15315 ; (time-to-days (current-time))))
15316 ; (setq year (1+ year)
15317 ; iso-date (calendar-gregorian-from-absolute
15318 ; (calendar-absolute-from-iso
15319 ; (list iso-week day year)))))
15320 (setq month (car iso-date)
15321 year (nth 2 iso-date)
15322 day (nth 1 iso-date)))
15323 (deltan
15324 (setq futurep nil)
15325 (unless deltadef
15326 (let ((now (decode-time (current-time))))
15327 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15328 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15329 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15330 ((equal deltaw "m") (setq month (+ month deltan)))
15331 ((equal deltaw "y") (setq year (+ year deltan)))))
15332 ((and wday (not (nth 3 tl)))
15333 (setq futurep nil)
15334 ;; Weekday was given, but no day, so pick that day in the week
15335 ;; on or after the derived date.
15336 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15337 (unless (equal wday wday1)
15338 (setq day (+ day (% (- wday wday1 -7) 7))))))
15339 (if (and (boundp 'org-time-was-given)
15340 (nth 2 tl))
15341 (setq org-time-was-given t))
15342 (if (< year 100) (setq year (+ 2000 year)))
15343 ;; Check of the date is representable
15344 (if org-read-date-force-compatible-dates
15345 (progn
15346 (if (< year 1970)
15347 (setq year 1970 org-read-date-analyze-forced-year t))
15348 (if (> year 2037)
15349 (setq year 2037 org-read-date-analyze-forced-year t)))
15350 (condition-case nil
15351 (ignore (encode-time second minute hour day month year))
15352 (error
15353 (setq year (nth 5 org-defdecode))
15354 (setq org-read-date-analyze-forced-year t))))
15355 (setq org-read-date-analyze-futurep futurep)
15356 (list second minute hour day month year)))
15358 (defvar parse-time-weekdays)
15359 (defun org-read-date-get-relative (s today default)
15360 "Check string S for special relative date string.
15361 TODAY and DEFAULT are internal times, for today and for a default.
15362 Return shift list (N what def-flag)
15363 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15364 N is the number of WHATs to shift.
15365 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15366 the DEFAULT date rather than TODAY."
15367 (require 'parse-time)
15368 (when (and
15369 (string-match
15370 (concat
15371 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15372 "\\([0-9]+\\)?"
15373 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15374 "\\([ \t]\\|$\\)") s)
15375 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15376 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15377 (string-to-char (substring (match-string 1 s) -1))
15378 ?+))
15379 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15380 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15381 (what (if (match-end 3) (match-string 3 s) "d"))
15382 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15383 (date (if rel default today))
15384 (wday (nth 6 (decode-time date)))
15385 delta)
15386 (if wday1
15387 (progn
15388 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15389 (if (= dir ?-) (setq delta (- delta 7)))
15390 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15391 (list delta "d" rel))
15392 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15394 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15395 "Turn a user-specified date into the internal representation.
15396 The internal representation needed by the calendar is (month day year).
15397 This is a wrapper to handle the brain-dead convention in calendar that
15398 user function argument order change dependent on argument order."
15399 (if (boundp 'calendar-date-style)
15400 (cond
15401 ((eq calendar-date-style 'american)
15402 (list arg1 arg2 arg3))
15403 ((eq calendar-date-style 'european)
15404 (list arg2 arg1 arg3))
15405 ((eq calendar-date-style 'iso)
15406 (list arg2 arg3 arg1)))
15407 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15408 (if (org-bound-and-true-p european-calendar-style)
15409 (list arg2 arg1 arg3)
15410 (list arg1 arg2 arg3)))))
15412 (defun org-eval-in-calendar (form &optional keepdate)
15413 "Eval FORM in the calendar window and return to current window.
15414 Also, store the cursor date in variable org-ans2."
15415 (let ((sf (selected-frame))
15416 (sw (selected-window)))
15417 (select-window (get-buffer-window "*Calendar*" t))
15418 (eval form)
15419 (when (and (not keepdate) (calendar-cursor-to-date))
15420 (let* ((date (calendar-cursor-to-date))
15421 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15422 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15423 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15424 (select-window sw)
15425 (org-select-frame-set-input-focus sf)))
15427 (defun org-calendar-select ()
15428 "Return to `org-read-date' with the date currently selected.
15429 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15430 (interactive)
15431 (when (calendar-cursor-to-date)
15432 (let* ((date (calendar-cursor-to-date))
15433 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15434 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15435 (if (active-minibuffer-window) (exit-minibuffer))))
15437 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15438 "Insert a date stamp for the date given by the internal TIME.
15439 WITH-HM means use the stamp format that includes the time of the day.
15440 INACTIVE means use square brackets instead of angular ones, so that the
15441 stamp will not contribute to the agenda.
15442 PRE and POST are optional strings to be inserted before and after the
15443 stamp.
15444 The command returns the inserted time stamp."
15445 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15446 stamp)
15447 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15448 (insert-before-markers (or pre ""))
15449 (when (listp extra)
15450 (setq extra (car extra))
15451 (if (and (stringp extra)
15452 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15453 (setq extra (format "-%02d:%02d"
15454 (string-to-number (match-string 1 extra))
15455 (string-to-number (match-string 2 extra))))
15456 (setq extra nil)))
15457 (when extra
15458 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15459 (insert-before-markers (setq stamp (format-time-string fmt time)))
15460 (insert-before-markers (or post ""))
15461 (setq org-last-inserted-timestamp stamp)))
15463 (defun org-toggle-time-stamp-overlays ()
15464 "Toggle the use of custom time stamp formats."
15465 (interactive)
15466 (setq org-display-custom-times (not org-display-custom-times))
15467 (unless org-display-custom-times
15468 (let ((p (point-min)) (bmp (buffer-modified-p)))
15469 (while (setq p (next-single-property-change p 'display))
15470 (if (and (get-text-property p 'display)
15471 (eq (get-text-property p 'face) 'org-date))
15472 (remove-text-properties
15473 p (setq p (next-single-property-change p 'display))
15474 '(display t))))
15475 (set-buffer-modified-p bmp)))
15476 (if (featurep 'xemacs)
15477 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15478 (org-restart-font-lock)
15479 (setq org-table-may-need-update t)
15480 (if org-display-custom-times
15481 (message "Time stamps are overlaid with custom format")
15482 (message "Time stamp overlays removed")))
15484 (defun org-display-custom-time (beg end)
15485 "Overlay modified time stamp format over timestamp between BEG and END."
15486 (let* ((ts (buffer-substring beg end))
15487 t1 w1 with-hm tf time str w2 (off 0))
15488 (save-match-data
15489 (setq t1 (org-parse-time-string ts t))
15490 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15491 (setq off (- (match-end 0) (match-beginning 0)))))
15492 (setq end (- end off))
15493 (setq w1 (- end beg)
15494 with-hm (and (nth 1 t1) (nth 2 t1))
15495 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15496 time (org-fix-decoded-time t1)
15497 str (org-add-props
15498 (format-time-string
15499 (substring tf 1 -1) (apply 'encode-time time))
15500 nil 'mouse-face 'highlight)
15501 w2 (length str))
15502 (if (not (= w2 w1))
15503 (add-text-properties (1+ beg) (+ 2 beg)
15504 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15505 (if (featurep 'xemacs)
15506 (progn
15507 (put-text-property beg end 'invisible t)
15508 (put-text-property beg end 'end-glyph (make-glyph str)))
15509 (put-text-property beg end 'display str))))
15511 (defun org-translate-time (string)
15512 "Translate all timestamps in STRING to custom format.
15513 But do this only if the variable `org-display-custom-times' is set."
15514 (when org-display-custom-times
15515 (save-match-data
15516 (let* ((start 0)
15517 (re org-ts-regexp-both)
15518 t1 with-hm inactive tf time str beg end)
15519 (while (setq start (string-match re string start))
15520 (setq beg (match-beginning 0)
15521 end (match-end 0)
15522 t1 (save-match-data
15523 (org-parse-time-string (substring string beg end) t))
15524 with-hm (and (nth 1 t1) (nth 2 t1))
15525 inactive (equal (substring string beg (1+ beg)) "[")
15526 tf (funcall (if with-hm 'cdr 'car)
15527 org-time-stamp-custom-formats)
15528 time (org-fix-decoded-time t1)
15529 str (format-time-string
15530 (concat
15531 (if inactive "[" "<") (substring tf 1 -1)
15532 (if inactive "]" ">"))
15533 (apply 'encode-time time))
15534 string (replace-match str t t string)
15535 start (+ start (length str)))))))
15536 string)
15538 (defun org-fix-decoded-time (time)
15539 "Set 0 instead of nil for the first 6 elements of time.
15540 Don't touch the rest."
15541 (let ((n 0))
15542 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15544 (defun org-days-to-time (timestamp-string)
15545 "Difference between TIMESTAMP-STRING and now in days."
15546 (- (time-to-days (org-time-string-to-time timestamp-string))
15547 (time-to-days (current-time))))
15549 (defun org-deadline-close (timestamp-string &optional ndays)
15550 "Is the time in TIMESTAMP-STRING close to the current date?"
15551 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15552 (and (< (org-days-to-time timestamp-string) ndays)
15553 (not (org-entry-is-done-p))))
15555 (defun org-get-wdays (ts)
15556 "Get the deadline lead time appropriate for timestring TS."
15557 (cond
15558 ((<= org-deadline-warning-days 0)
15559 ;; 0 or negative, enforce this value no matter what
15560 (- org-deadline-warning-days))
15561 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15562 ;; lead time is specified.
15563 (floor (* (string-to-number (match-string 1 ts))
15564 (cdr (assoc (match-string 2 ts)
15565 '(("d" . 1) ("w" . 7)
15566 ("m" . 30.4) ("y" . 365.25)))))))
15567 ;; go for the default.
15568 (t org-deadline-warning-days)))
15570 (defun org-calendar-select-mouse (ev)
15571 "Return to `org-read-date' with the date currently selected.
15572 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15573 (interactive "e")
15574 (mouse-set-point ev)
15575 (when (calendar-cursor-to-date)
15576 (let* ((date (calendar-cursor-to-date))
15577 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15578 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15579 (if (active-minibuffer-window) (exit-minibuffer))))
15581 (defun org-check-deadlines (ndays)
15582 "Check if there are any deadlines due or past due.
15583 A deadline is considered due if it happens within `org-deadline-warning-days'
15584 days from today's date. If the deadline appears in an entry marked DONE,
15585 it is not shown. The prefix arg NDAYS can be used to test that many
15586 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15587 (interactive "P")
15588 (let* ((org-warn-days
15589 (cond
15590 ((equal ndays '(4)) 100000)
15591 (ndays (prefix-numeric-value ndays))
15592 (t (abs org-deadline-warning-days))))
15593 (case-fold-search nil)
15594 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15595 (callback
15596 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15598 (message "%d deadlines past-due or due within %d days"
15599 (org-occur regexp nil callback)
15600 org-warn-days)))
15602 (defun org-check-before-date (date)
15603 "Check if there are deadlines or scheduled entries before DATE."
15604 (interactive (list (org-read-date)))
15605 (let ((case-fold-search nil)
15606 (regexp (concat "\\<\\(" org-deadline-string
15607 "\\|" org-scheduled-string
15608 "\\) *<\\([^>]+\\)>"))
15609 (callback
15610 (lambda () (time-less-p
15611 (org-time-string-to-time (match-string 2))
15612 (org-time-string-to-time date)))))
15613 (message "%d entries before %s"
15614 (org-occur regexp nil callback) date)))
15616 (defun org-check-after-date (date)
15617 "Check if there are deadlines or scheduled entries after DATE."
15618 (interactive (list (org-read-date)))
15619 (let ((case-fold-search nil)
15620 (regexp (concat "\\<\\(" org-deadline-string
15621 "\\|" org-scheduled-string
15622 "\\) *<\\([^>]+\\)>"))
15623 (callback
15624 (lambda () (not
15625 (time-less-p
15626 (org-time-string-to-time (match-string 2))
15627 (org-time-string-to-time date))))))
15628 (message "%d entries after %s"
15629 (org-occur regexp nil callback) date)))
15631 (defun org-check-dates-range (start-date end-date)
15632 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15633 (interactive (list (org-read-date nil nil nil "Range starts")
15634 (org-read-date nil nil nil "Range end")))
15635 (let ((case-fold-search nil)
15636 (regexp (concat "\\<\\(" org-deadline-string
15637 "\\|" org-scheduled-string
15638 "\\) *<\\([^>]+\\)>"))
15639 (callback
15640 (lambda ()
15641 (let ((match (match-string 2)))
15642 (and
15643 (not (time-less-p
15644 (org-time-string-to-time match)
15645 (org-time-string-to-time start-date)))
15646 (time-less-p
15647 (org-time-string-to-time match)
15648 (org-time-string-to-time end-date)))))))
15649 (message "%d entries between %s and %s"
15650 (org-occur regexp nil callback) start-date end-date)))
15652 (defun org-evaluate-time-range (&optional to-buffer)
15653 "Evaluate a time range by computing the difference between start and end.
15654 Normally the result is just printed in the echo area, but with prefix arg
15655 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15656 If the time range is actually in a table, the result is inserted into the
15657 next column.
15658 For time difference computation, a year is assumed to be exactly 365
15659 days in order to avoid rounding problems."
15660 (interactive "P")
15662 (org-clock-update-time-maybe)
15663 (save-excursion
15664 (unless (org-at-date-range-p t)
15665 (goto-char (point-at-bol))
15666 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15667 (if (not (org-at-date-range-p t))
15668 (error "Not at a time-stamp range, and none found in current line")))
15669 (let* ((ts1 (match-string 1))
15670 (ts2 (match-string 2))
15671 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15672 (match-end (match-end 0))
15673 (time1 (org-time-string-to-time ts1))
15674 (time2 (org-time-string-to-time ts2))
15675 (t1 (org-float-time time1))
15676 (t2 (org-float-time time2))
15677 (diff (abs (- t2 t1)))
15678 (negative (< (- t2 t1) 0))
15679 ;; (ys (floor (* 365 24 60 60)))
15680 (ds (* 24 60 60))
15681 (hs (* 60 60))
15682 (fy "%dy %dd %02d:%02d")
15683 (fy1 "%dy %dd")
15684 (fd "%dd %02d:%02d")
15685 (fd1 "%dd")
15686 (fh "%02d:%02d")
15687 y d h m align)
15688 (if havetime
15689 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15691 d (floor (/ diff ds)) diff (mod diff ds)
15692 h (floor (/ diff hs)) diff (mod diff hs)
15693 m (floor (/ diff 60)))
15694 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15696 d (floor (+ (/ diff ds) 0.5))
15697 h 0 m 0))
15698 (if (not to-buffer)
15699 (message "%s" (org-make-tdiff-string y d h m))
15700 (if (org-at-table-p)
15701 (progn
15702 (goto-char match-end)
15703 (setq align t)
15704 (and (looking-at " *|") (goto-char (match-end 0))))
15705 (goto-char match-end))
15706 (if (looking-at
15707 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15708 (replace-match ""))
15709 (if negative (insert " -"))
15710 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15711 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15712 (insert " " (format fh h m))))
15713 (if align (org-table-align))
15714 (message "Time difference inserted")))))
15716 (defun org-make-tdiff-string (y d h m)
15717 (let ((fmt "")
15718 (l nil))
15719 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15720 l (push y l)))
15721 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15722 l (push d l)))
15723 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15724 l (push h l)))
15725 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15726 l (push m l)))
15727 (apply 'format fmt (nreverse l))))
15729 (defun org-time-string-to-time (s &optional buffer pos)
15730 (condition-case errdata
15731 (apply 'encode-time (org-parse-time-string s))
15732 (error (error "Bad timestamp `%s'%s\nError was: %s"
15733 s (if (not (and buffer pos))
15735 (format " at %d in buffer `%s'" pos buffer))
15736 (cdr errdata)))))
15738 (defun org-time-string-to-seconds (s)
15739 (org-float-time (org-time-string-to-time s)))
15741 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15742 "Convert a time stamp to an absolute day number.
15743 If there is a specifier for a cyclic time stamp, get the closest date to
15744 DAYNR.
15745 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15746 The variable date is bound by the calendar when this is called."
15747 (cond
15748 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15749 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15750 daynr
15751 (+ daynr 1000)))
15752 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15753 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15754 (time-to-days (current-time))) (match-string 0 s)
15755 prefer show-all))
15756 (t (time-to-days
15757 (condition-case errdata
15758 (apply 'encode-time (org-parse-time-string s))
15759 (error (error "Bad timestamp `%s'%s\nError was: %s"
15760 s (if (not (and buffer pos))
15762 (format " at %d in buffer `%s'" pos buffer))
15763 (cdr errdata))))))))
15765 (defun org-days-to-iso-week (days)
15766 "Return the iso week number."
15767 (require 'cal-iso)
15768 (car (calendar-iso-from-absolute days)))
15770 (defun org-small-year-to-year (year)
15771 "Convert 2-digit years into 4-digit years.
15772 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15773 The year 2000 cannot be abbreviated. Any year larger than 99
15774 is returned unchanged."
15775 (if (< year 38)
15776 (setq year (+ 2000 year))
15777 (if (< year 100)
15778 (setq year (+ 1900 year))))
15779 year)
15781 (defun org-time-from-absolute (d)
15782 "Return the time corresponding to date D.
15783 D may be an absolute day number, or a calendar-type list (month day year)."
15784 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15785 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15787 (defun org-calendar-holiday ()
15788 "List of holidays, for Diary display in Org-mode."
15789 (require 'holidays)
15790 (let ((hl (funcall
15791 (if (fboundp 'calendar-check-holidays)
15792 'calendar-check-holidays 'check-calendar-holidays) date)))
15793 (if hl (mapconcat 'identity hl "; "))))
15795 (defun org-diary-sexp-entry (sexp entry date)
15796 "Process a SEXP diary ENTRY for DATE."
15797 (require 'diary-lib)
15798 (let ((result (if calendar-debug-sexp
15799 (let ((stack-trace-on-error t))
15800 (eval (car (read-from-string sexp))))
15801 (condition-case nil
15802 (eval (car (read-from-string sexp)))
15803 (error
15804 (beep)
15805 (message "Bad sexp at line %d in %s: %s"
15806 (org-current-line)
15807 (buffer-file-name) sexp)
15808 (sleep-for 2))))))
15809 (cond ((stringp result) (split-string result "; "))
15810 ((and (consp result)
15811 (not (consp (cdr result)))
15812 (stringp (cdr result))) (cdr result))
15813 ((and (consp result)
15814 (stringp (car result))) result)
15815 (result entry)
15816 (t nil))))
15818 (defun org-diary-to-ical-string (frombuf)
15819 "Get iCalendar entries from diary entries in buffer FROMBUF.
15820 This uses the icalendar.el library."
15821 (let* ((tmpdir (if (featurep 'xemacs)
15822 (temp-directory)
15823 temporary-file-directory))
15824 (tmpfile (make-temp-name
15825 (expand-file-name "orgics" tmpdir)))
15826 buf rtn b e)
15827 (with-current-buffer frombuf
15828 (icalendar-export-region (point-min) (point-max) tmpfile)
15829 (setq buf (find-buffer-visiting tmpfile))
15830 (set-buffer buf)
15831 (goto-char (point-min))
15832 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15833 (setq b (match-beginning 0)))
15834 (goto-char (point-max))
15835 (if (re-search-backward "^END:VEVENT" nil t)
15836 (setq e (match-end 0)))
15837 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15838 (kill-buffer buf)
15839 (delete-file tmpfile)
15840 rtn))
15842 (defun org-closest-date (start current change prefer show-all)
15843 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15844 When PREFER is `past', return a date that is either CURRENT or past.
15845 When PREFER is `future', return a date that is either CURRENT or future.
15846 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15847 ;; Make the proper lists from the dates
15848 (catch 'exit
15849 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15850 dn dw sday cday n1 n2 n0
15851 d m y y1 y2 date1 date2 nmonths nm ny m2)
15853 (setq start (org-date-to-gregorian start)
15854 current (org-date-to-gregorian
15855 (if show-all
15856 current
15857 (time-to-days (current-time))))
15858 sday (calendar-absolute-from-gregorian start)
15859 cday (calendar-absolute-from-gregorian current))
15861 (if (<= cday sday) (throw 'exit sday))
15863 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15864 (setq dn (string-to-number (match-string 1 change))
15865 dw (cdr (assoc (match-string 2 change) a1)))
15866 (error "Invalid change specifier: %s" change))
15867 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15868 (cond
15869 ((eq dw 'day)
15870 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15871 n2 (+ n1 dn)))
15872 ((eq dw 'year)
15873 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15874 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15875 (setq date1 (list m d y1)
15876 n1 (calendar-absolute-from-gregorian date1)
15877 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15878 n2 (calendar-absolute-from-gregorian date2)))
15879 ((eq dw 'month)
15880 ;; approx number of month between the two dates
15881 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15882 ;; How often does dn fit in there?
15883 (setq d (nth 1 start) m (car start) y (nth 2 start)
15884 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15885 m (+ m nm)
15886 ny (floor (/ m 12))
15887 y (+ y ny)
15888 m (- m (* ny 12)))
15889 (while (> m 12) (setq m (- m 12) y (1+ y)))
15890 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15891 (setq m2 (+ m dn) y2 y)
15892 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15893 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15894 (while (<= n2 cday)
15895 (setq n1 n2 m m2 y y2)
15896 (setq m2 (+ m dn) y2 y)
15897 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15898 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15899 ;; Make sure n1 is the earlier date
15900 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15901 (if show-all
15902 (cond
15903 ((eq prefer 'past) (if (= cday n2) n2 n1))
15904 ((eq prefer 'future) (if (= cday n1) n1 n2))
15905 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15906 (cond
15907 ((eq prefer 'past) (if (= cday n2) n2 n1))
15908 ((eq prefer 'future) (if (= cday n1) n1 n2))
15909 (t (if (= cday n1) n1 n2)))))))
15911 (defun org-date-to-gregorian (date)
15912 "Turn any specification of DATE into a Gregorian date for the calendar."
15913 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15914 ((and (listp date) (= (length date) 3)) date)
15915 ((stringp date)
15916 (setq date (org-parse-time-string date))
15917 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15918 ((listp date)
15919 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15921 (defun org-parse-time-string (s &optional nodefault)
15922 "Parse the standard Org-mode time string.
15923 This should be a lot faster than the normal `parse-time-string'.
15924 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15925 hour and minute fields will be nil if not given."
15926 (if (string-match org-ts-regexp0 s)
15927 (list 0
15928 (if (or (match-beginning 8) (not nodefault))
15929 (string-to-number (or (match-string 8 s) "0")))
15930 (if (or (match-beginning 7) (not nodefault))
15931 (string-to-number (or (match-string 7 s) "0")))
15932 (string-to-number (match-string 4 s))
15933 (string-to-number (match-string 3 s))
15934 (string-to-number (match-string 2 s))
15935 nil nil nil)
15936 (error "Not a standard Org-mode time string: %s" s)))
15938 (defun org-timestamp-up (&optional arg)
15939 "Increase the date item at the cursor by one.
15940 If the cursor is on the year, change the year. If it is on the month,
15941 the day or the time, change that.
15942 With prefix ARG, change by that many units."
15943 (interactive "p")
15944 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15946 (defun org-timestamp-down (&optional arg)
15947 "Decrease the date item at the cursor by one.
15948 If the cursor is on the year, change the year. If it is on the month,
15949 the day or the time, change that.
15950 With prefix ARG, change by that many units."
15951 (interactive "p")
15952 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15954 (defun org-timestamp-up-day (&optional arg)
15955 "Increase the date in the time stamp by one day.
15956 With prefix ARG, change that many days."
15957 (interactive "p")
15958 (if (and (not (org-at-timestamp-p t))
15959 (org-at-heading-p))
15960 (org-todo 'up)
15961 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15963 (defun org-timestamp-down-day (&optional arg)
15964 "Decrease the date in the time stamp by one day.
15965 With prefix ARG, change that many days."
15966 (interactive "p")
15967 (if (and (not (org-at-timestamp-p t))
15968 (org-at-heading-p))
15969 (org-todo 'down)
15970 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15972 (defun org-at-timestamp-p (&optional inactive-ok)
15973 "Determine if the cursor is in or at a timestamp."
15974 (interactive)
15975 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15976 (pos (point))
15977 (ans (or (looking-at tsr)
15978 (save-excursion
15979 (skip-chars-backward "^[<\n\r\t")
15980 (if (> (point) (point-min)) (backward-char 1))
15981 (and (looking-at tsr)
15982 (> (- (match-end 0) pos) -1))))))
15983 (and ans
15984 (boundp 'org-ts-what)
15985 (setq org-ts-what
15986 (cond
15987 ((= pos (match-beginning 0)) 'bracket)
15988 ;; Point is considered to be "on the bracket" whether
15989 ;; it's really on it or right after it.
15990 ((or (= pos (1- (match-end 0)))
15991 (= pos (match-end 0))) 'bracket)
15992 ((org-pos-in-match-range pos 2) 'year)
15993 ((org-pos-in-match-range pos 3) 'month)
15994 ((org-pos-in-match-range pos 7) 'hour)
15995 ((org-pos-in-match-range pos 8) 'minute)
15996 ((or (org-pos-in-match-range pos 4)
15997 (org-pos-in-match-range pos 5)) 'day)
15998 ((and (> pos (or (match-end 8) (match-end 5)))
15999 (< pos (match-end 0)))
16000 (- pos (or (match-end 8) (match-end 5))))
16001 (t 'day))))
16002 ans))
16004 (defun org-toggle-timestamp-type ()
16005 "Toggle the type (<active> or [inactive]) of a time stamp."
16006 (interactive)
16007 (when (org-at-timestamp-p t)
16008 (let ((beg (match-beginning 0)) (end (match-end 0))
16009 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16010 (save-excursion
16011 (goto-char beg)
16012 (while (re-search-forward "[][<>]" end t)
16013 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16014 t t)))
16015 (message "Timestamp is now %sactive"
16016 (if (equal (char-after beg) ?<) "" "in")))))
16018 (defun org-timestamp-change (n &optional what updown)
16019 "Change the date in the time stamp at point.
16020 The date will be changed by N times WHAT. WHAT can be `day', `month',
16021 `year', `minute', `second'. If WHAT is not given, the cursor position
16022 in the timestamp determines what will be changed."
16023 (let ((origin (point)) origin-cat
16024 with-hm inactive
16025 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16026 org-ts-what
16027 extra rem
16028 ts time time0)
16029 (if (not (org-at-timestamp-p t))
16030 (error "Not at a timestamp"))
16031 (if (and (not what) (eq org-ts-what 'bracket))
16032 (org-toggle-timestamp-type)
16033 ;; Point isn't on brackets. Remember the part of the time-stamp
16034 ;; the point was in. Indeed, size of time-stamps may change,
16035 ;; but point must be kept in the same category nonetheless.
16036 (setq origin-cat org-ts-what)
16037 (if (and (not what) (not (eq org-ts-what 'day))
16038 org-display-custom-times
16039 (get-text-property (point) 'display)
16040 (not (get-text-property (1- (point)) 'display)))
16041 (setq org-ts-what 'day))
16042 (setq org-ts-what (or what org-ts-what)
16043 inactive (= (char-after (match-beginning 0)) ?\[)
16044 ts (match-string 0))
16045 (replace-match "")
16046 (if (string-match
16047 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16049 (setq extra (match-string 1 ts)))
16050 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16051 (setq with-hm t))
16052 (setq time0 (org-parse-time-string ts))
16053 (when (and updown
16054 (eq org-ts-what 'minute)
16055 (not current-prefix-arg))
16056 ;; This looks like s-up and s-down. Change by one rounding step.
16057 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16058 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16059 (setcar (cdr time0) (+ (nth 1 time0)
16060 (if (> n 0) (- rem) (- dm rem))))))
16061 (setq time
16062 (encode-time (or (car time0) 0)
16063 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16064 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16065 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16066 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16067 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16068 (nthcdr 6 time0)))
16069 (when (and (member org-ts-what '(hour minute))
16070 extra
16071 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16072 (setq extra (org-modify-ts-extra
16073 extra
16074 (if (eq org-ts-what 'hour) 2 5)
16075 n dm)))
16076 (when (integerp org-ts-what)
16077 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16078 (if (eq what 'calendar)
16079 (let ((cal-date (org-get-date-from-calendar)))
16080 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16081 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16082 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16083 (setcar time0 (or (car time0) 0))
16084 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16085 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16086 (setq time (apply 'encode-time time0))))
16087 ;; Insert the new time-stamp, and ensure point stays in the same
16088 ;; category as before (i.e. not after the last position in that
16089 ;; category).
16090 (let ((pos (point)))
16091 ;; Stay before inserted string. `save-excursion' is of no use.
16092 (setq org-last-changed-timestamp
16093 (org-insert-time-stamp time with-hm inactive nil nil extra))
16094 (goto-char pos))
16095 (save-match-data
16096 (looking-at org-ts-regexp3)
16097 (goto-char (cond
16098 ;; `day' category ends before `hour' if any, or at
16099 ;; the end of the day name.
16100 ((eq origin-cat 'day)
16101 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16102 ((eq origin-cat 'hour) (min (match-end 7) origin))
16103 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16104 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16105 ;; `year' and `month' have both fixed size: point
16106 ;; couldn't have moved into another part.
16107 (t origin))))
16108 ;; Update clock if on a CLOCK line.
16109 (org-clock-update-time-maybe)
16110 ;; Try to recenter the calendar window, if any.
16111 (if (and org-calendar-follow-timestamp-change
16112 (get-buffer-window "*Calendar*" t)
16113 (memq org-ts-what '(day month year)))
16114 (org-recenter-calendar (time-to-days time))))))
16116 (defun org-modify-ts-extra (s pos n dm)
16117 "Change the different parts of the lead-time and repeat fields in timestamp."
16118 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16119 ng h m new rem)
16120 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16121 (cond
16122 ((or (org-pos-in-match-range pos 2)
16123 (org-pos-in-match-range pos 3))
16124 (setq m (string-to-number (match-string 3 s))
16125 h (string-to-number (match-string 2 s)))
16126 (if (org-pos-in-match-range pos 2)
16127 (setq h (+ h n))
16128 (setq n (* dm (org-no-warnings (signum n))))
16129 (when (not (= 0 (setq rem (% m dm))))
16130 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16131 (setq m (+ m n)))
16132 (if (< m 0) (setq m (+ m 60) h (1- h)))
16133 (if (> m 59) (setq m (- m 60) h (1+ h)))
16134 (setq h (min 24 (max 0 h)))
16135 (setq ng 1 new (format "-%02d:%02d" h m)))
16136 ((org-pos-in-match-range pos 6)
16137 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16138 ((org-pos-in-match-range pos 5)
16139 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16141 ((org-pos-in-match-range pos 9)
16142 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16143 ((org-pos-in-match-range pos 8)
16144 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16146 (when ng
16147 (setq s (concat
16148 (substring s 0 (match-beginning ng))
16150 (substring s (match-end ng))))))
16153 (defun org-recenter-calendar (date)
16154 "If the calendar is visible, recenter it to DATE."
16155 (let ((cwin (get-buffer-window "*Calendar*" t)))
16156 (when cwin
16157 (let ((calendar-move-hook nil))
16158 (with-selected-window cwin
16159 (calendar-goto-date (if (listp date) date
16160 (calendar-gregorian-from-absolute date))))))))
16162 (defun org-goto-calendar (&optional arg)
16163 "Go to the Emacs calendar at the current date.
16164 If there is a time stamp in the current line, go to that date.
16165 A prefix ARG can be used to force the current date."
16166 (interactive "P")
16167 (let ((tsr org-ts-regexp) diff
16168 (calendar-move-hook nil)
16169 (calendar-view-holidays-initially-flag nil)
16170 (calendar-view-diary-initially-flag nil))
16171 (if (or (org-at-timestamp-p)
16172 (save-excursion
16173 (beginning-of-line 1)
16174 (looking-at (concat ".*" tsr))))
16175 (let ((d1 (time-to-days (current-time)))
16176 (d2 (time-to-days
16177 (org-time-string-to-time (match-string 1)))))
16178 (setq diff (- d2 d1))))
16179 (calendar)
16180 (calendar-goto-today)
16181 (if (and diff (not arg)) (calendar-forward-day diff))))
16183 (defun org-get-date-from-calendar ()
16184 "Return a list (month day year) of date at point in calendar."
16185 (with-current-buffer "*Calendar*"
16186 (save-match-data
16187 (calendar-cursor-to-date))))
16189 (defun org-date-from-calendar ()
16190 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16191 If there is already a time stamp at the cursor position, update it."
16192 (interactive)
16193 (if (org-at-timestamp-p t)
16194 (org-timestamp-change 0 'calendar)
16195 (let ((cal-date (org-get-date-from-calendar)))
16196 (org-insert-time-stamp
16197 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16199 (defun org-minutes-to-hh:mm-string (m)
16200 "Compute H:MM from a number of minutes."
16201 (let ((h (/ m 60)))
16202 (setq m (- m (* 60 h)))
16203 (format org-time-clocksum-format h m)))
16205 (defun org-hh:mm-string-to-minutes (s)
16206 "Convert a string H:MM to a number of minutes.
16207 If the string is just a number, interpret it as minutes.
16208 In fact, the first hh:mm or number in the string will be taken,
16209 there can be extra stuff in the string.
16210 If no number is found, the return value is 0."
16211 (cond
16212 ((integerp s) s)
16213 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16214 (+ (* (string-to-number (match-string 1 s)) 60)
16215 (string-to-number (match-string 2 s))))
16216 ((string-match "\\([0-9]+\\)" s)
16217 (string-to-number (match-string 1 s)))
16218 (t 0)))
16220 (defcustom org-effort-durations
16221 `(("h" . 60)
16222 ("d" . ,(* 60 8))
16223 ("w" . ,(* 60 8 5))
16224 ("m" . ,(* 60 8 5 4))
16225 ("y" . ,(* 60 8 5 40)))
16226 "Conversion factor to minutes for an effort modifier.
16228 Each entry has the form (MODIFIER . MINUTES).
16230 In an effort string, a number followed by MODIFIER is multiplied
16231 by the specified number of MINUTES to obtain an effort in
16232 minutes.
16234 For example, if the value of this variable is ((\"hours\" . 60)), then an
16235 effort string \"2hours\" is equivalent to 120 minutes."
16236 :group 'org-agenda
16237 :version "24.1"
16238 :type '(alist :key-type (string :tag "Modifier")
16239 :value-type (number :tag "Minutes")))
16241 (defun org-duration-string-to-minutes (s)
16242 "Convert a duration string S to minutes.
16244 A bare number is interpreted as minutes, modifiers can be set by
16245 customizing `org-effort-durations' (which see).
16247 Entries containing a colon are interpreted as H:MM by
16248 `org-hh:mm-string-to-minutes'."
16249 (let ((result 0)
16250 (re (concat "\\([0-9]+\\) *\\("
16251 (regexp-opt (mapcar 'car org-effort-durations))
16252 "\\)")))
16253 (while (string-match re s)
16254 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16255 (string-to-number (match-string 1 s))))
16256 (setq s (replace-match "" nil t s)))
16257 (incf result (org-hh:mm-string-to-minutes s))
16258 result))
16260 ;;;; Files
16262 (defun org-save-all-org-buffers ()
16263 "Save all Org-mode buffers without user confirmation."
16264 (interactive)
16265 (message "Saving all Org-mode buffers...")
16266 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16267 (when (featurep 'org-id) (org-id-locations-save))
16268 (message "Saving all Org-mode buffers... done"))
16270 (defun org-revert-all-org-buffers ()
16271 "Revert all Org-mode buffers.
16272 Prompt for confirmation when there are unsaved changes.
16273 Be sure you know what you are doing before letting this function
16274 overwrite your changes.
16276 This function is useful in a setup where one tracks org files
16277 with a version control system, to revert on one machine after pulling
16278 changes from another. I believe the procedure must be like this:
16280 1. M-x org-save-all-org-buffers
16281 2. Pull changes from the other machine, resolve conflicts
16282 3. M-x org-revert-all-org-buffers"
16283 (interactive)
16284 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16285 (error "Abort"))
16286 (save-excursion
16287 (save-window-excursion
16288 (mapc
16289 (lambda (b)
16290 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16291 (with-current-buffer b buffer-file-name))
16292 (org-pop-to-buffer-same-window b)
16293 (revert-buffer t 'no-confirm)))
16294 (buffer-list))
16295 (when (and (featurep 'org-id) org-id-track-globally)
16296 (org-id-locations-load)))))
16298 ;;;; Agenda files
16300 ;;;###autoload
16301 (defun org-switchb (&optional arg)
16302 "Switch between Org buffers.
16303 With one prefix argument, restrict available buffers to files.
16304 With two prefix arguments, restrict available buffers to agenda files.
16306 Defaults to `iswitchb' for buffer name completion.
16307 Set `org-completion-use-ido' to make it use ido instead."
16308 (interactive "P")
16309 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16310 ((equal arg '(16)) (org-buffer-list 'agenda))
16311 (t (org-buffer-list))))
16312 (org-completion-use-iswitchb org-completion-use-iswitchb)
16313 (org-completion-use-ido org-completion-use-ido))
16314 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16315 (setq org-completion-use-iswitchb t))
16316 (org-pop-to-buffer-same-window
16317 (org-icompleting-read "Org buffer: "
16318 (mapcar 'list (mapcar 'buffer-name blist))
16319 nil t))))
16321 ;;; Define some older names previously used for this functionality
16322 ;;;###autoload
16323 (defalias 'org-ido-switchb 'org-switchb)
16324 ;;;###autoload
16325 (defalias 'org-iswitchb 'org-switchb)
16327 (defun org-buffer-list (&optional predicate exclude-tmp)
16328 "Return a list of Org buffers.
16329 PREDICATE can be `export', `files' or `agenda'.
16331 export restrict the list to Export buffers.
16332 files restrict the list to buffers visiting Org files.
16333 agenda restrict the list to buffers visiting agenda files.
16335 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16336 (let* ((bfn nil)
16337 (agenda-files (and (eq predicate 'agenda)
16338 (mapcar 'file-truename (org-agenda-files t))))
16339 (filter
16340 (cond
16341 ((eq predicate 'files)
16342 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16343 ((eq predicate 'export)
16344 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16345 ((eq predicate 'agenda)
16346 (lambda (b)
16347 (with-current-buffer b
16348 (and (eq major-mode 'org-mode)
16349 (setq bfn (buffer-file-name b))
16350 (member (file-truename bfn) agenda-files)))))
16351 (t (lambda (b) (with-current-buffer b
16352 (or (eq major-mode 'org-mode)
16353 (string-match "\*Org .*Export"
16354 (buffer-name b)))))))))
16355 (delq nil
16356 (mapcar
16357 (lambda(b)
16358 (if (and (funcall filter b)
16359 (or (not exclude-tmp)
16360 (not (string-match "tmp" (buffer-name b)))))
16362 nil))
16363 (buffer-list)))))
16365 (defun org-agenda-files (&optional unrestricted archives)
16366 "Get the list of agenda files.
16367 Optional UNRESTRICTED means return the full list even if a restriction
16368 is currently in place.
16369 When ARCHIVES is t, include all archive files that are really being
16370 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16371 `org-agenda-archives-mode' is t."
16372 (let ((files
16373 (cond
16374 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16375 ((stringp org-agenda-files) (org-read-agenda-file-list))
16376 ((listp org-agenda-files) org-agenda-files)
16377 (t (error "Invalid value of `org-agenda-files'")))))
16378 (setq files (apply 'append
16379 (mapcar (lambda (f)
16380 (if (file-directory-p f)
16381 (directory-files
16382 f t org-agenda-file-regexp)
16383 (list f)))
16384 files)))
16385 (when org-agenda-skip-unavailable-files
16386 (setq files (delq nil
16387 (mapcar (function
16388 (lambda (file)
16389 (and (file-readable-p file) file)))
16390 files))))
16391 (when (or (eq archives t)
16392 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16393 (setq files (org-add-archive-files files)))
16394 files))
16396 (defun org-agenda-file-p (&optional file)
16397 "Return non-nil, if FILE is an agenda file.
16398 If FILE is omitted, use the file associated with the current
16399 buffer."
16400 (member (or file (buffer-file-name))
16401 (org-agenda-files t)))
16403 (defun org-edit-agenda-file-list ()
16404 "Edit the list of agenda files.
16405 Depending on setup, this either uses customize to edit the variable
16406 `org-agenda-files', or it visits the file that is holding the list. In the
16407 latter case, the buffer is set up in a way that saving it automatically kills
16408 the buffer and restores the previous window configuration."
16409 (interactive)
16410 (if (stringp org-agenda-files)
16411 (let ((cw (current-window-configuration)))
16412 (find-file org-agenda-files)
16413 (org-set-local 'org-window-configuration cw)
16414 (org-add-hook 'after-save-hook
16415 (lambda ()
16416 (set-window-configuration
16417 (prog1 org-window-configuration
16418 (kill-buffer (current-buffer))))
16419 (org-install-agenda-files-menu)
16420 (message "New agenda file list installed"))
16421 nil 'local)
16422 (message "%s" (substitute-command-keys
16423 "Edit list and finish with \\[save-buffer]")))
16424 (customize-variable 'org-agenda-files)))
16426 (defun org-store-new-agenda-file-list (list)
16427 "Set new value for the agenda file list and save it correctly."
16428 (if (stringp org-agenda-files)
16429 (let ((fe (org-read-agenda-file-list t)) b u)
16430 (while (setq b (find-buffer-visiting org-agenda-files))
16431 (kill-buffer b))
16432 (with-temp-file org-agenda-files
16433 (insert
16434 (mapconcat
16435 (lambda (f) ;; Keep un-expanded entries.
16436 (if (setq u (assoc f fe))
16437 (cdr u)
16439 list "\n")
16440 "\n")))
16441 (let ((org-mode-hook nil) (org-inhibit-startup t)
16442 (org-insert-mode-line-in-empty-file nil))
16443 (setq org-agenda-files list)
16444 (customize-save-variable 'org-agenda-files org-agenda-files))))
16446 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16447 "Read the list of agenda files from a file.
16448 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16449 filenames, used by `org-store-new-agenda-file-list' to write back
16450 un-expanded file names."
16451 (when (file-directory-p org-agenda-files)
16452 (error "`org-agenda-files' cannot be a single directory"))
16453 (when (stringp org-agenda-files)
16454 (with-temp-buffer
16455 (insert-file-contents org-agenda-files)
16456 (mapcar
16457 (lambda (f)
16458 (let ((e (expand-file-name (substitute-in-file-name f)
16459 org-directory)))
16460 (if pair-with-expansion
16461 (cons e f)
16462 e)))
16463 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16465 ;;;###autoload
16466 (defun org-cycle-agenda-files ()
16467 "Cycle through the files in `org-agenda-files'.
16468 If the current buffer visits an agenda file, find the next one in the list.
16469 If the current buffer does not, find the first agenda file."
16470 (interactive)
16471 (let* ((fs (org-agenda-files t))
16472 (files (append fs (list (car fs))))
16473 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16474 file)
16475 (unless files (error "No agenda files"))
16476 (catch 'exit
16477 (while (setq file (pop files))
16478 (if (equal (file-truename file) tcf)
16479 (when (car files)
16480 (find-file (car files))
16481 (throw 'exit t))))
16482 (find-file (car fs)))
16483 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16485 (defun org-agenda-file-to-front (&optional to-end)
16486 "Move/add the current file to the top of the agenda file list.
16487 If the file is not present in the list, it is added to the front. If it is
16488 present, it is moved there. With optional argument TO-END, add/move to the
16489 end of the list."
16490 (interactive "P")
16491 (let ((org-agenda-skip-unavailable-files nil)
16492 (file-alist (mapcar (lambda (x)
16493 (cons (file-truename x) x))
16494 (org-agenda-files t)))
16495 (ctf (file-truename buffer-file-name))
16496 x had)
16497 (setq x (assoc ctf file-alist) had x)
16499 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16500 (if to-end
16501 (setq file-alist (append (delq x file-alist) (list x)))
16502 (setq file-alist (cons x (delq x file-alist))))
16503 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16504 (org-install-agenda-files-menu)
16505 (message "File %s to %s of agenda file list"
16506 (if had "moved" "added") (if to-end "end" "front"))))
16508 (defun org-remove-file (&optional file)
16509 "Remove current file from the list of files in variable `org-agenda-files'.
16510 These are the files which are being checked for agenda entries.
16511 Optional argument FILE means use this file instead of the current."
16512 (interactive)
16513 (let* ((org-agenda-skip-unavailable-files nil)
16514 (file (or file buffer-file-name))
16515 (true-file (file-truename file))
16516 (afile (abbreviate-file-name file))
16517 (files (delq nil (mapcar
16518 (lambda (x)
16519 (if (equal true-file
16520 (file-truename x))
16521 nil x))
16522 (org-agenda-files t)))))
16523 (if (not (= (length files) (length (org-agenda-files t))))
16524 (progn
16525 (org-store-new-agenda-file-list files)
16526 (org-install-agenda-files-menu)
16527 (message "Removed file: %s" afile))
16528 (message "File was not in list: %s (not removed)" afile))))
16530 (defun org-file-menu-entry (file)
16531 (vector file (list 'find-file file) t))
16533 (defun org-check-agenda-file (file)
16534 "Make sure FILE exists. If not, ask user what to do."
16535 (when (not (file-exists-p file))
16536 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16537 (abbreviate-file-name file))
16538 (let ((r (downcase (read-char-exclusive))))
16539 (cond
16540 ((equal r ?r)
16541 (org-remove-file file)
16542 (throw 'nextfile t))
16543 (t (error "Abort"))))))
16545 (defun org-get-agenda-file-buffer (file)
16546 "Get a buffer visiting FILE. If the buffer needs to be created, add
16547 it to the list of buffers which might be released later."
16548 (let ((buf (org-find-base-buffer-visiting file)))
16549 (if buf
16550 buf ; just return it
16551 ;; Make a new buffer and remember it
16552 (setq buf (find-file-noselect file))
16553 (if buf (push buf org-agenda-new-buffers))
16554 buf)))
16556 (defun org-release-buffers (blist)
16557 "Release all buffers in list, asking the user for confirmation when needed.
16558 When a buffer is unmodified, it is just killed. When modified, it is saved
16559 \(if the user agrees) and then killed."
16560 (let (buf file)
16561 (while (setq buf (pop blist))
16562 (setq file (buffer-file-name buf))
16563 (when (and (buffer-modified-p buf)
16564 file
16565 (y-or-n-p (format "Save file %s? " file)))
16566 (with-current-buffer buf (save-buffer)))
16567 (kill-buffer buf))))
16569 (defun org-prepare-agenda-buffers (files)
16570 "Create buffers for all agenda files, protect archived trees and comments."
16571 (interactive)
16572 (let ((pa '(:org-archived t))
16573 (pc '(:org-comment t))
16574 (pall '(:org-archived t :org-comment t))
16575 (inhibit-read-only t)
16576 (rea (concat ":" org-archive-tag ":"))
16577 bmp file re)
16578 (save-excursion
16579 (save-restriction
16580 (while (setq file (pop files))
16581 (catch 'nextfile
16582 (if (bufferp file)
16583 (set-buffer file)
16584 (org-check-agenda-file file)
16585 (set-buffer (org-get-agenda-file-buffer file)))
16586 (widen)
16587 (setq bmp (buffer-modified-p))
16588 (org-refresh-category-properties)
16589 (setq org-todo-keywords-for-agenda
16590 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16591 (setq org-done-keywords-for-agenda
16592 (append org-done-keywords-for-agenda org-done-keywords))
16593 (setq org-todo-keyword-alist-for-agenda
16594 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16595 (setq org-drawers-for-agenda
16596 (append org-drawers-for-agenda org-drawers))
16597 (setq org-tag-alist-for-agenda
16598 (append org-tag-alist-for-agenda org-tag-alist))
16600 (save-excursion
16601 (remove-text-properties (point-min) (point-max) pall)
16602 (when org-agenda-skip-archived-trees
16603 (goto-char (point-min))
16604 (while (re-search-forward rea nil t)
16605 (if (org-at-heading-p t)
16606 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16607 (goto-char (point-min))
16608 (setq re (format org-heading-keyword-regexp-format
16609 org-comment-string))
16610 (while (re-search-forward re nil t)
16611 (add-text-properties
16612 (match-beginning 0) (org-end-of-subtree t) pc)))
16613 (set-buffer-modified-p bmp)))))
16614 (setq org-todo-keywords-for-agenda
16615 (org-uniquify org-todo-keywords-for-agenda))
16616 (setq org-todo-keyword-alist-for-agenda
16617 (org-uniquify org-todo-keyword-alist-for-agenda)
16618 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16620 ;;;; Embedded LaTeX
16622 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16623 "Keymap for the minor `org-cdlatex-mode'.")
16625 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16626 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16627 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16628 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16629 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16631 (defvar org-cdlatex-texmathp-advice-is-done nil
16632 "Flag remembering if we have applied the advice to texmathp already.")
16634 (define-minor-mode org-cdlatex-mode
16635 "Toggle the minor `org-cdlatex-mode'.
16636 This mode supports entering LaTeX environment and math in LaTeX fragments
16637 in Org-mode.
16638 \\{org-cdlatex-mode-map}"
16639 nil " OCDL" nil
16640 (when org-cdlatex-mode
16641 (require 'cdlatex)
16642 (run-hooks 'cdlatex-mode-hook)
16643 (cdlatex-compute-tables))
16644 (unless org-cdlatex-texmathp-advice-is-done
16645 (setq org-cdlatex-texmathp-advice-is-done t)
16646 (defadvice texmathp (around org-math-always-on activate)
16647 "Always return t in org-mode buffers.
16648 This is because we want to insert math symbols without dollars even outside
16649 the LaTeX math segments. If Orgmode thinks that point is actually inside
16650 an embedded LaTeX fragment, let texmathp do its job.
16651 \\[org-cdlatex-mode-map]"
16652 (interactive)
16653 (let (p)
16654 (cond
16655 ((not (eq major-mode 'org-mode)) ad-do-it)
16656 ((eq this-command 'cdlatex-math-symbol)
16657 (setq ad-return-value t
16658 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16660 (let ((p (org-inside-LaTeX-fragment-p)))
16661 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16662 (setq ad-return-value t
16663 texmathp-why '("Org-mode embedded math" . 0))
16664 (if p ad-do-it)))))))))
16666 (defun turn-on-org-cdlatex ()
16667 "Unconditionally turn on `org-cdlatex-mode'."
16668 (org-cdlatex-mode 1))
16670 (defun org-inside-LaTeX-fragment-p ()
16671 "Test if point is inside a LaTeX fragment.
16672 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16673 sequence appearing also before point.
16674 Even though the matchers for math are configurable, this function assumes
16675 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16676 delimiters are skipped when they have been removed by customization.
16677 The return value is nil, or a cons cell with the delimiter and the
16678 position of this delimiter.
16680 This function does a reasonably good job, but can locally be fooled by
16681 for example currency specifications. For example it will assume being in
16682 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16683 fragments that are properly closed, but during editing, we have to live
16684 with the uncertainty caused by missing closing delimiters. This function
16685 looks only before point, not after."
16686 (catch 'exit
16687 (let ((pos (point))
16688 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16689 (lim (progn
16690 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16691 (point)))
16692 dd-on str (start 0) m re)
16693 (goto-char pos)
16694 (when dodollar
16695 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16696 re (nth 1 (assoc "$" org-latex-regexps)))
16697 (while (string-match re str start)
16698 (cond
16699 ((= (match-end 0) (length str))
16700 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16701 ((= (match-end 0) (- (length str) 5))
16702 (throw 'exit nil))
16703 (t (setq start (match-end 0))))))
16704 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16705 (goto-char pos)
16706 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16707 (and (match-beginning 2) (throw 'exit nil))
16708 ;; count $$
16709 (while (re-search-backward "\\$\\$" lim t)
16710 (setq dd-on (not dd-on)))
16711 (goto-char pos)
16712 (if dd-on (cons "$$" m))))))
16714 (defun org-inside-latex-macro-p ()
16715 "Is point inside a LaTeX macro or its arguments?"
16716 (save-match-data
16717 (org-in-regexp
16718 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16720 (defun org-try-cdlatex-tab ()
16721 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16722 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16723 - inside a LaTeX fragment, or
16724 - after the first word in a line, where an abbreviation expansion could
16725 insert a LaTeX environment."
16726 (when org-cdlatex-mode
16727 (cond
16728 ;; Before any word on the line: No expansion possible.
16729 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16730 ;; Just after first word on the line: Expand it. Make sure it
16731 ;; cannot happen on headlines, though.
16732 ((save-excursion
16733 (skip-chars-backward "a-zA-Z0-9*")
16734 (skip-chars-backward " \t")
16735 (and (bolp) (not (org-at-heading-p))))
16736 (cdlatex-tab) t)
16737 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16739 (defun org-cdlatex-underscore-caret (&optional arg)
16740 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16741 Revert to the normal definition outside of these fragments."
16742 (interactive "P")
16743 (if (org-inside-LaTeX-fragment-p)
16744 (call-interactively 'cdlatex-sub-superscript)
16745 (let (org-cdlatex-mode)
16746 (call-interactively (key-binding (vector last-input-event))))))
16748 (defun org-cdlatex-math-modify (&optional arg)
16749 "Execute `cdlatex-math-modify' in LaTeX fragments.
16750 Revert to the normal definition outside of these fragments."
16751 (interactive "P")
16752 (if (org-inside-LaTeX-fragment-p)
16753 (call-interactively 'cdlatex-math-modify)
16754 (let (org-cdlatex-mode)
16755 (call-interactively (key-binding (vector last-input-event))))))
16757 (defvar org-latex-fragment-image-overlays nil
16758 "List of overlays carrying the images of latex fragments.")
16759 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16761 (defun org-remove-latex-fragment-image-overlays ()
16762 "Remove all overlays with LaTeX fragment images in current buffer."
16763 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16764 (setq org-latex-fragment-image-overlays nil))
16766 (defun org-preview-latex-fragment (&optional subtree)
16767 "Preview the LaTeX fragment at point, or all locally or globally.
16768 If the cursor is in a LaTeX fragment, create the image and overlay
16769 it over the source code. If there is no fragment at point, display
16770 all fragments in the current text, from one headline to the next. With
16771 prefix SUBTREE, display all fragments in the current subtree. With a
16772 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16773 the cursor is before the first headline,
16774 display all fragments in the buffer.
16775 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16776 (interactive "P")
16777 (unless buffer-file-name
16778 (error "Can't preview LaTeX fragment in a non-file buffer"))
16779 (org-remove-latex-fragment-image-overlays)
16780 (save-excursion
16781 (save-restriction
16782 (let (beg end at msg)
16783 (cond
16784 ((or (equal subtree '(16))
16785 (not (save-excursion
16786 (re-search-backward org-outline-regexp-bol nil t))))
16787 (setq beg (point-min) end (point-max)
16788 msg "Creating images for buffer...%s"))
16789 ((equal subtree '(4))
16790 (org-back-to-heading)
16791 (setq beg (point) end (org-end-of-subtree t)
16792 msg "Creating images for subtree...%s"))
16794 (if (setq at (org-inside-LaTeX-fragment-p))
16795 (goto-char (max (point-min) (- (cdr at) 2)))
16796 (org-back-to-heading))
16797 (setq beg (point) end (progn (outline-next-heading) (point))
16798 msg (if at "Creating image...%s"
16799 "Creating images for entry...%s"))))
16800 (message msg "")
16801 (narrow-to-region beg end)
16802 (goto-char beg)
16803 (org-format-latex
16804 (concat "ltxpng/" (file-name-sans-extension
16805 (file-name-nondirectory
16806 buffer-file-name)))
16807 default-directory 'overlays msg at 'forbuffer 'dvipng)
16808 (message msg "done. Use `C-c C-c' to remove images.")))))
16810 (defvar org-latex-regexps
16811 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16812 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16813 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16814 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16815 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16816 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16817 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16818 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16819 "Regular expressions for matching embedded LaTeX.")
16821 (defvar org-export-have-math nil) ;; dynamic scoping
16822 (defun org-format-latex (prefix &optional dir overlays msg at
16823 forbuffer processing-type)
16824 "Replace LaTeX fragments with links to an image, and produce images.
16825 Some of the options can be changed using the variable
16826 `org-format-latex-options'."
16827 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16828 (let* ((prefixnodir (file-name-nondirectory prefix))
16829 (absprefix (expand-file-name prefix dir))
16830 (todir (file-name-directory absprefix))
16831 (opt org-format-latex-options)
16832 (matchers (plist-get opt :matchers))
16833 (re-list org-latex-regexps)
16834 (org-format-latex-header-extra
16835 (plist-get (org-infile-export-plist) :latex-header-extra))
16836 (cnt 0) txt hash link beg end re e checkdir
16837 executables-checked string
16838 m n block-type block linkfile movefile ov)
16839 ;; Check the different regular expressions
16840 (while (setq e (pop re-list))
16841 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16842 block (if block-type "\n\n" ""))
16843 (when (member m matchers)
16844 (goto-char (point-min))
16845 (while (re-search-forward re nil t)
16846 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16847 (not (get-text-property (match-beginning n)
16848 'org-protected))
16849 (or (not overlays)
16850 (not (eq (get-char-property (match-beginning n)
16851 'org-overlay-type)
16852 'org-latex-overlay))))
16853 (setq org-export-have-math t)
16854 (cond
16855 ((eq processing-type 'verbatim)
16856 ;; Leave the text verbatim, just protect it
16857 (add-text-properties (match-beginning n) (match-end n)
16858 '(org-protected t)))
16859 ((eq processing-type 'mathjax)
16860 ;; Prepare for MathJax processing
16861 (setq string (match-string n))
16862 (if (member m '("$" "$1"))
16863 (save-excursion
16864 (delete-region (match-beginning n) (match-end n))
16865 (goto-char (match-beginning n))
16866 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16867 "\\)")
16868 '(org-protected t))))
16869 (add-text-properties (match-beginning n) (match-end n)
16870 '(org-protected t))))
16871 ((eq processing-type 'dvipng)
16872 ;; Process to an image
16873 (setq txt (match-string n)
16874 beg (match-beginning n) end (match-end n)
16875 cnt (1+ cnt))
16876 (let (print-length print-level) ; make sure full list is printed
16877 (setq hash (sha1 (prin1-to-string
16878 (list org-format-latex-header
16879 org-format-latex-header-extra
16880 org-export-latex-default-packages-alist
16881 org-export-latex-packages-alist
16882 org-format-latex-options
16883 forbuffer txt)))
16884 linkfile (format "%s_%s.png" prefix hash)
16885 movefile (format "%s_%s.png" absprefix hash)))
16886 (setq link (concat block "[[file:" linkfile "]]" block))
16887 (if msg (message msg cnt))
16888 (goto-char beg)
16889 (unless checkdir ; make sure the directory exists
16890 (setq checkdir t)
16891 (or (file-directory-p todir) (make-directory todir t)))
16893 (unless executables-checked
16894 (org-check-external-command
16895 "latex" "needed to convert LaTeX fragments to images")
16896 (org-check-external-command
16897 "dvipng" "needed to convert LaTeX fragments to images")
16898 (setq executables-checked t))
16900 (unless (file-exists-p movefile)
16901 (org-create-formula-image
16902 txt movefile opt forbuffer))
16903 (if overlays
16904 (progn
16905 (mapc (lambda (o)
16906 (if (eq (overlay-get o 'org-overlay-type)
16907 'org-latex-overlay)
16908 (delete-overlay o)))
16909 (overlays-in beg end))
16910 (setq ov (make-overlay beg end))
16911 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16912 (if (featurep 'xemacs)
16913 (progn
16914 (overlay-put ov 'invisible t)
16915 (overlay-put
16916 ov 'end-glyph
16917 (make-glyph (vector 'png :file movefile))))
16918 (overlay-put
16919 ov 'display
16920 (list 'image :type 'png :file movefile :ascent 'center)))
16921 (push ov org-latex-fragment-image-overlays)
16922 (goto-char end))
16923 (delete-region beg end)
16924 (insert (org-add-props link
16925 (list 'org-latex-src
16926 (replace-regexp-in-string
16927 "\"" "" txt)
16928 'org-latex-src-embed-type
16929 (if block-type 'paragraph 'character))))))
16930 ((eq processing-type 'mathml)
16931 ;; Process to MathML
16932 (unless executables-checked
16933 (unless (save-match-data (org-format-latex-mathml-available-p))
16934 (error "LaTeX to MathML converter not configured"))
16935 (setq executables-checked t))
16936 (setq txt (match-string n)
16937 beg (match-beginning n) end (match-end n)
16938 cnt (1+ cnt))
16939 (if msg (message msg cnt))
16940 (goto-char beg)
16941 (delete-region beg end)
16942 (insert (org-format-latex-as-mathml
16943 txt block-type prefix dir)))
16945 (error "Unknown conversion type %s for latex fragments"
16946 processing-type)))))))))
16948 (defun org-create-math-formula (latex-frag &optional mathml-file)
16949 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16950 Use `org-latex-to-mathml-convert-command'. If the conversion is
16951 sucessful, return the portion between \"<math...> </math>\"
16952 elements otherwise return nil. When MATHML-FILE is specified,
16953 write the results in to that file. When invoked as an
16954 interactive command, prompt for LATEX-FRAG, with initial value
16955 set to the current active region and echo the results for user
16956 inspection."
16957 (interactive (list (let ((frag (when (region-active-p)
16958 (buffer-substring-no-properties
16959 (region-beginning) (region-end)))))
16960 (read-string "LaTeX Fragment: " frag nil frag))))
16961 (unless latex-frag (error "Invalid latex-frag"))
16962 (let* ((tmp-in-file (file-relative-name
16963 (make-temp-name (expand-file-name "ltxmathml-in"))))
16964 (ignore (write-region latex-frag nil tmp-in-file))
16965 (tmp-out-file (file-relative-name
16966 (make-temp-name (expand-file-name "ltxmathml-out"))))
16967 (cmd (format-spec
16968 org-latex-to-mathml-convert-command
16969 `((?j . ,(shell-quote-argument
16970 (expand-file-name org-latex-to-mathml-jar-file)))
16971 (?I . ,(shell-quote-argument tmp-in-file))
16972 (?o . ,(shell-quote-argument tmp-out-file)))))
16973 mathml shell-command-output)
16974 (when (org-called-interactively-p 'any)
16975 (unless (org-format-latex-mathml-available-p)
16976 (error "LaTeX to MathML converter not configured")))
16977 (message "Running %s" cmd)
16978 (setq shell-command-output (shell-command-to-string cmd))
16979 (setq mathml
16980 (when (file-readable-p tmp-out-file)
16981 (with-current-buffer (find-file-noselect tmp-out-file t)
16982 (goto-char (point-min))
16983 (when (re-search-forward
16984 (concat
16985 (regexp-quote
16986 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16987 "\\(.\\|\n\\)*"
16988 (regexp-quote "</math>")) nil t)
16989 (prog1 (match-string 0) (kill-buffer))))))
16990 (cond
16991 (mathml
16992 (setq mathml
16993 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16994 (when mathml-file
16995 (write-region mathml nil mathml-file))
16996 (when (org-called-interactively-p 'any)
16997 (message mathml)))
16998 ((message "LaTeX to MathML conversion failed")
16999 (message shell-command-output)))
17000 (delete-file tmp-in-file)
17001 (when (file-exists-p tmp-out-file)
17002 (delete-file tmp-out-file))
17003 mathml))
17005 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17006 prefix &optional dir)
17007 "Use `org-create-math-formula' but check local cache first."
17008 (let* ((absprefix (expand-file-name prefix dir))
17009 (print-length nil) (print-level nil)
17010 (formula-id (concat
17011 "formula-"
17012 (sha1
17013 (prin1-to-string
17014 (list latex-frag
17015 org-latex-to-mathml-convert-command)))))
17016 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17017 (formula-cache-dir (file-name-directory formula-cache)))
17019 (unless (file-directory-p formula-cache-dir)
17020 (make-directory formula-cache-dir t))
17022 (unless (file-exists-p formula-cache)
17023 (org-create-math-formula latex-frag formula-cache))
17025 (if (file-exists-p formula-cache)
17026 ;; Successful conversion. Return the link to MathML file.
17027 (org-add-props
17028 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17029 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17030 'org-latex-src-embed-type (if latex-frag-type
17031 'paragraph 'character)))
17032 ;; Failed conversion. Return the LaTeX fragment verbatim
17033 (add-text-properties
17034 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17035 latex-frag)))
17037 ;; This function borrows from Ganesh Swami's latex2png.el
17038 (defun org-create-formula-image (string tofile options buffer)
17039 "This calls dvipng."
17040 (require 'org-latex)
17041 (let* ((tmpdir (if (featurep 'xemacs)
17042 (temp-directory)
17043 temporary-file-directory))
17044 (texfilebase (make-temp-name
17045 (expand-file-name "orgtex" tmpdir)))
17046 (texfile (concat texfilebase ".tex"))
17047 (dvifile (concat texfilebase ".dvi"))
17048 (pngfile (concat texfilebase ".png"))
17049 (fnh (if (featurep 'xemacs)
17050 (font-height (face-font 'default))
17051 (face-attribute 'default :height nil)))
17052 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17053 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17054 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17055 "Black"))
17056 (bg (or (plist-get options (if buffer :background :html-background))
17057 "Transparent")))
17058 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17059 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17060 (with-temp-file texfile
17061 (insert (org-splice-latex-header
17062 org-format-latex-header
17063 org-export-latex-default-packages-alist
17064 org-export-latex-packages-alist t
17065 org-format-latex-header-extra))
17066 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17067 (require 'org-latex)
17068 (org-export-latex-fix-inputenc))
17069 (let ((dir default-directory))
17070 (condition-case nil
17071 (progn
17072 (cd tmpdir)
17073 (call-process "latex" nil nil nil texfile))
17074 (error nil))
17075 (cd dir))
17076 (if (not (file-exists-p dvifile))
17077 (progn (message "Failed to create dvi file from %s" texfile) nil)
17078 (condition-case nil
17079 (if (featurep 'xemacs)
17080 (call-process "dvipng" nil nil nil
17081 "-fg" fg "-bg" bg
17082 "-T" "tight"
17083 "-o" pngfile
17084 dvifile)
17085 (call-process "dvipng" nil nil nil
17086 "-fg" fg "-bg" bg
17087 "-D" dpi
17088 ;;"-x" scale "-y" scale
17089 "-T" "tight"
17090 "-o" pngfile
17091 dvifile))
17092 (error nil))
17093 (if (not (file-exists-p pngfile))
17094 (if org-format-latex-signal-error
17095 (error "Failed to create png file from %s" texfile)
17096 (message "Failed to create png file from %s" texfile)
17097 nil)
17098 ;; Use the requested file name and clean up
17099 (copy-file pngfile tofile 'replace)
17100 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17101 (delete-file (concat texfilebase e)))
17102 pngfile))))
17104 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17105 "Fill a LaTeX header template TPL.
17106 In the template, the following place holders will be recognized:
17108 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17109 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17110 [PACKAGES] \\usepackage statements for PKG
17111 [NO-PACKAGES] do not include PKG
17112 [EXTRA] the string EXTRA
17113 [NO-EXTRA] do not include EXTRA
17115 For backward compatibility, if both the positive and the negative place
17116 holder is missing, the positive one (without the \"NO-\") will be
17117 assumed to be present at the end of the template.
17118 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17119 EXTRA is a string.
17120 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17121 (let (rpl (end ""))
17122 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17123 (setq rpl (if (or (match-end 1) (not def-pkg))
17124 "" (org-latex-packages-to-string def-pkg snippets-p t))
17125 tpl (replace-match rpl t t tpl))
17126 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17128 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17129 (setq rpl (if (or (match-end 1) (not pkg))
17130 "" (org-latex-packages-to-string pkg snippets-p t))
17131 tpl (replace-match rpl t t tpl))
17132 (if pkg (setq end
17133 (concat end "\n"
17134 (org-latex-packages-to-string pkg snippets-p)))))
17136 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17137 (setq rpl (if (or (match-end 1) (not extra))
17138 "" (concat extra "\n"))
17139 tpl (replace-match rpl t t tpl))
17140 (if (and extra (string-match "\\S-" extra))
17141 (setq end (concat end "\n" extra))))
17143 (if (string-match "\\S-" end)
17144 (concat tpl "\n" end)
17145 tpl)))
17147 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17148 "Turn an alist of packages into a string with the \\usepackage macros."
17149 (setq pkg (mapconcat (lambda(p)
17150 (cond
17151 ((stringp p) p)
17152 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17153 (format "%% Package %s omitted" (cadr p)))
17154 ((equal "" (car p))
17155 (format "\\usepackage{%s}" (cadr p)))
17157 (format "\\usepackage[%s]{%s}"
17158 (car p) (cadr p)))))
17160 "\n"))
17161 (if newline (concat pkg "\n") pkg))
17163 (defun org-dvipng-color (attr)
17164 "Return an rgb color specification for dvipng."
17165 (apply 'format "rgb %s %s %s"
17166 (mapcar 'org-normalize-color
17167 (if (featurep 'xemacs)
17168 (color-rgb-components
17169 (face-property 'default
17170 (cond ((eq attr :foreground) 'foreground)
17171 ((eq attr :background) 'background))))
17172 (color-values (face-attribute 'default attr nil))))))
17174 (defun org-normalize-color (value)
17175 "Return string to be used as color value for an RGB component."
17176 (format "%g" (/ value 65535.0)))
17178 ;; Image display
17181 (defvar org-inline-image-overlays nil)
17182 (make-variable-buffer-local 'org-inline-image-overlays)
17184 (defun org-toggle-inline-images (&optional include-linked)
17185 "Toggle the display of inline images.
17186 INCLUDE-LINKED is passed to `org-display-inline-images'."
17187 (interactive "P")
17188 (if org-inline-image-overlays
17189 (progn
17190 (org-remove-inline-images)
17191 (message "Inline image display turned off"))
17192 (org-display-inline-images include-linked)
17193 (if org-inline-image-overlays
17194 (message "%d images displayed inline"
17195 (length org-inline-image-overlays))
17196 (message "No images to display inline"))))
17198 (defun org-display-inline-images (&optional include-linked refresh beg end)
17199 "Display inline images.
17200 Normally only links without a description part are inlined, because this
17201 is how it will work for export. When INCLUDE-LINKED is set, also links
17202 with a description part will be inlined. This can be nice for a quick
17203 look at those images, but it does not reflect what exported files will look
17204 like.
17205 When REFRESH is set, refresh existing images between BEG and END.
17206 This will create new image displays only if necessary.
17207 BEG and END default to the buffer boundaries."
17208 (interactive "P")
17209 (unless refresh
17210 (org-remove-inline-images)
17211 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17212 (save-excursion
17213 (save-restriction
17214 (widen)
17215 (setq beg (or beg (point-min)) end (or end (point-max)))
17216 (goto-char beg)
17217 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17218 (substring (org-image-file-name-regexp) 0 -2)
17219 "\\)\\]" (if include-linked "" "\\]")))
17220 old file ov img)
17221 (while (re-search-forward re end t)
17222 (setq old (get-char-property-and-overlay (match-beginning 1)
17223 'org-image-overlay))
17224 (setq file (expand-file-name
17225 (concat (or (match-string 3) "") (match-string 4))))
17226 (when (file-exists-p file)
17227 (if (and (car-safe old) refresh)
17228 (image-refresh (overlay-get (cdr old) 'display))
17229 (setq img (save-match-data (create-image file)))
17230 (when img
17231 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17232 (overlay-put ov 'display img)
17233 (overlay-put ov 'face 'default)
17234 (overlay-put ov 'org-image-overlay t)
17235 (overlay-put ov 'modification-hooks
17236 (list 'org-display-inline-modification-hook))
17237 (push ov org-inline-image-overlays)))))))))
17239 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17240 "Remove inline-display overlay if a corresponding region is modified."
17241 (let ((inhibit-modification-hooks t))
17242 (when (and ov after)
17243 (delete ov org-inline-image-overlays)
17244 (delete-overlay ov))))
17246 (defun org-remove-inline-images ()
17247 "Remove inline display of images."
17248 (interactive)
17249 (mapc 'delete-overlay org-inline-image-overlays)
17250 (setq org-inline-image-overlays nil))
17252 ;;;; Key bindings
17254 ;; Outline functions from `outline-mode-prefix-map'
17255 ;; that can be remapped in Org:
17256 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17257 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17258 (define-key org-mode-map [remap outline-forward-same-level]
17259 'org-forward-same-level)
17260 (define-key org-mode-map [remap outline-backward-same-level]
17261 'org-backward-same-level)
17262 (define-key org-mode-map [remap show-branches]
17263 'org-kill-note-or-show-branches)
17264 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17265 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17266 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17268 ;; Outline functions from `outline-mode-prefix-map'
17269 ;; that can not be remapped in Org:
17270 ;; - the column "key binding" shows whether the Outline function is still
17271 ;; available in Org mode on the same key that it has been bound to in
17272 ;; Outline mode:
17273 ;; - "overridden": key used for a different functionality in Org mode
17274 ;; - else: key still bound to the same Outline function in Org mode
17275 ;; | Outline function | key binding | Org replacement |
17276 ;; |------------------------------------+-------------+-----------------------|
17277 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17278 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17279 ;; | `show-children' | `C-c C-i' | visibility cycling |
17280 ;; | `hide-subtree' | overridden | visibility cycling |
17281 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17282 ;; | `hide-body' | overridden | no replacement |
17283 ;; | `show-all' | overridden | no replacement |
17284 ;; | `hide-entry' | overridden | visibility cycling |
17285 ;; | `show-entry' | overridden | no replacement |
17286 ;; | `hide-leaves' | overridden | no replacement |
17287 ;; | `hide-sublevels' | overridden | no replacement |
17288 ;; | `hide-other' | overridden | no replacement |
17289 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17290 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17292 ;; Make `C-c C-x' a prefix key
17293 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17295 ;; TAB key with modifiers
17296 (org-defkey org-mode-map "\C-i" 'org-cycle)
17297 (org-defkey org-mode-map [(tab)] 'org-cycle)
17298 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17299 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17300 ;; The following line is necessary under Suse GNU/Linux
17301 (unless (featurep 'xemacs)
17302 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17303 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17304 (define-key org-mode-map [backtab] 'org-shifttab)
17306 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17307 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17308 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17310 ;; Cursor keys with modifiers
17311 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17312 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17313 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17314 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17316 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17317 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17318 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17319 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17321 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17322 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17323 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17324 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17326 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17327 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17328 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17329 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17331 ;; Babel keys
17332 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17333 (mapc (lambda (pair)
17334 (define-key org-babel-map (car pair) (cdr pair)))
17335 org-babel-key-bindings)
17337 ;;; Extra keys for tty access.
17338 ;; We only set them when really needed because otherwise the
17339 ;; menus don't show the simple keys
17341 (when (or org-use-extra-keys
17342 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17343 (not window-system))
17344 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17345 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17346 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17347 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17348 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17349 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17350 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17351 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17352 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17353 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17354 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17355 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17356 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17357 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17358 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17359 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17360 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17361 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17362 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17363 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17364 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17365 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17366 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17367 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17368 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17369 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17370 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17371 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17373 ;; All the other keys
17375 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17376 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17377 (if (boundp 'narrow-map)
17378 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17379 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17380 (if (boundp 'narrow-map)
17381 (org-defkey narrow-map "b" 'org-narrow-to-block)
17382 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17383 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17384 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17385 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17386 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17387 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17388 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17389 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17390 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17391 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17392 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17393 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17394 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17395 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17396 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17397 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17398 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17399 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17400 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17401 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17402 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17403 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17404 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17405 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17406 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17407 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17408 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17409 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17410 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17411 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17412 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17413 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17414 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17415 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17416 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17417 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17418 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17419 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17420 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17421 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17422 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17423 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17424 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17425 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17426 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17427 (org-defkey org-mode-map "\C-c^" 'org-sort)
17428 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17429 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17430 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17431 (org-defkey org-mode-map "\C-m" 'org-return)
17432 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17433 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17434 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17435 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17436 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17437 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17438 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17439 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17440 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17441 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17442 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17443 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17444 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17445 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17446 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17447 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17448 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17449 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17450 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17451 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17452 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17453 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17455 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17456 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17457 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17458 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17460 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17461 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17462 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17463 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17464 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17465 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17466 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17467 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17468 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17469 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17470 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17471 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17472 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17473 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17474 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17475 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17476 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17477 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17479 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17480 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17481 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17482 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17483 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17485 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17487 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17489 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17490 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17492 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17495 (when (featurep 'xemacs)
17496 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17499 (defconst org-speed-commands-default
17501 ("Outline Navigation")
17502 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17503 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17504 ("f" . (org-speed-move-safe 'org-forward-same-level))
17505 ("b" . (org-speed-move-safe 'org-backward-same-level))
17506 ("u" . (org-speed-move-safe 'outline-up-heading))
17507 ("j" . org-goto)
17508 ("g" . (org-refile t))
17509 ("Outline Visibility")
17510 ("c" . org-cycle)
17511 ("C" . org-shifttab)
17512 (" " . org-display-outline-path)
17513 ("Outline Structure Editing")
17514 ("U" . org-shiftmetaup)
17515 ("D" . org-shiftmetadown)
17516 ("r" . org-metaright)
17517 ("l" . org-metaleft)
17518 ("R" . org-shiftmetaright)
17519 ("L" . org-shiftmetaleft)
17520 ("i" . (progn (forward-char 1) (call-interactively
17521 'org-insert-heading-respect-content)))
17522 ("^" . org-sort)
17523 ("w" . org-refile)
17524 ("a" . org-archive-subtree-default-with-confirmation)
17525 ("." . org-mark-subtree)
17526 ("Clock Commands")
17527 ("I" . org-clock-in)
17528 ("O" . org-clock-out)
17529 ("Meta Data Editing")
17530 ("t" . org-todo)
17531 ("0" . (org-priority ?\ ))
17532 ("1" . (org-priority ?A))
17533 ("2" . (org-priority ?B))
17534 ("3" . (org-priority ?C))
17535 (";" . org-set-tags-command)
17536 ("e" . org-set-effort)
17537 ("Agenda Views etc")
17538 ("v" . org-agenda)
17539 ("/" . org-sparse-tree)
17540 ("Misc")
17541 ("o" . org-open-at-point)
17542 ("?" . org-speed-command-help)
17543 ("<" . (org-agenda-set-restriction-lock 'subtree))
17544 (">" . (org-agenda-remove-restriction-lock))
17546 "The default speed commands.")
17548 (defun org-print-speed-command (e)
17549 (if (> (length (car e)) 1)
17550 (progn
17551 (princ "\n")
17552 (princ (car e))
17553 (princ "\n")
17554 (princ (make-string (length (car e)) ?-))
17555 (princ "\n"))
17556 (princ (car e))
17557 (princ " ")
17558 (if (symbolp (cdr e))
17559 (princ (symbol-name (cdr e)))
17560 (prin1 (cdr e)))
17561 (princ "\n")))
17563 (defun org-speed-command-help ()
17564 "Show the available speed commands."
17565 (interactive)
17566 (if (not org-use-speed-commands)
17567 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17568 (with-output-to-temp-buffer "*Help*"
17569 (princ "User-defined Speed commands\n===========================\n")
17570 (mapc 'org-print-speed-command org-speed-commands-user)
17571 (princ "\n")
17572 (princ "Built-in Speed commands\n=======================\n")
17573 (mapc 'org-print-speed-command org-speed-commands-default))
17574 (with-current-buffer "*Help*"
17575 (setq truncate-lines t))))
17577 (defun org-speed-move-safe (cmd)
17578 "Execute CMD, but make sure that the cursor always ends up in a headline.
17579 If not, return to the original position and throw an error."
17580 (interactive)
17581 (let ((pos (point)))
17582 (call-interactively cmd)
17583 (unless (and (bolp) (org-at-heading-p))
17584 (goto-char pos)
17585 (error "Boundary reached while executing %s" cmd))))
17587 (defvar org-self-insert-command-undo-counter 0)
17589 (defvar org-table-auto-blank-field) ; defined in org-table.el
17590 (defvar org-speed-command nil)
17592 (defun org-speed-command-default-hook (keys)
17593 "Hook for activating single-letter speed commands.
17594 `org-speed-commands-default' specifies a minimal command set.
17595 Use `org-speed-commands-user' for further customization."
17596 (when (or (and (bolp) (looking-at org-outline-regexp))
17597 (and (functionp org-use-speed-commands)
17598 (funcall org-use-speed-commands)))
17599 (cdr (assoc keys (append org-speed-commands-user
17600 org-speed-commands-default)))))
17602 (defun org-babel-speed-command-hook (keys)
17603 "Hook for activating single-letter code block commands."
17604 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17605 (cdr (assoc keys org-babel-key-bindings))))
17607 (defcustom org-speed-command-hook
17608 '(org-speed-command-default-hook org-babel-speed-command-hook)
17609 "Hook for activating speed commands at strategic locations.
17610 Hook functions are called in sequence until a valid handler is
17611 found.
17613 Each hook takes a single argument, a user-pressed command key
17614 which is also a `self-insert-command' from the global map.
17616 Within the hook, examine the cursor position and the command key
17617 and return nil or a valid handler as appropriate. Handler could
17618 be one of an interactive command, a function, or a form.
17620 Set `org-use-speed-commands' to non-nil value to enable this
17621 hook. The default setting is `org-speed-command-default-hook'."
17622 :group 'org-structure
17623 :type 'hook)
17625 (defun org-self-insert-command (N)
17626 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17627 If the cursor is in a table looking at whitespace, the whitespace is
17628 overwritten, and the table is not marked as requiring realignment."
17629 (interactive "p")
17630 (org-check-before-invisible-edit 'insert)
17631 (cond
17632 ((and org-use-speed-commands
17633 (setq org-speed-command
17634 (run-hook-with-args-until-success
17635 'org-speed-command-hook (this-command-keys))))
17636 (cond
17637 ((commandp org-speed-command)
17638 (setq this-command org-speed-command)
17639 (call-interactively org-speed-command))
17640 ((functionp org-speed-command)
17641 (funcall org-speed-command))
17642 ((and org-speed-command (listp org-speed-command))
17643 (eval org-speed-command))
17644 (t (let (org-use-speed-commands)
17645 (call-interactively 'org-self-insert-command)))))
17646 ((and
17647 (org-table-p)
17648 (progn
17649 ;; check if we blank the field, and if that triggers align
17650 (and (featurep 'org-table) org-table-auto-blank-field
17651 (member last-command
17652 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17653 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17654 ;; got extra space, this field does not determine column width
17655 (let (org-table-may-need-update) (org-table-blank-field))
17656 ;; no extra space, this field may determine column width
17657 (org-table-blank-field)))
17659 (eq N 1)
17660 (looking-at "[^|\n]* |"))
17661 (let (org-table-may-need-update)
17662 (goto-char (1- (match-end 0)))
17663 (backward-delete-char 1)
17664 (goto-char (match-beginning 0))
17665 (self-insert-command N)))
17667 (setq org-table-may-need-update t)
17668 (self-insert-command N)
17669 (org-fix-tags-on-the-fly)
17670 (if org-self-insert-cluster-for-undo
17671 (if (not (eq last-command 'org-self-insert-command))
17672 (setq org-self-insert-command-undo-counter 1)
17673 (if (>= org-self-insert-command-undo-counter 20)
17674 (setq org-self-insert-command-undo-counter 1)
17675 (and (> org-self-insert-command-undo-counter 0)
17676 buffer-undo-list (listp buffer-undo-list)
17677 (not (cadr buffer-undo-list)) ; remove nil entry
17678 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17679 (setq org-self-insert-command-undo-counter
17680 (1+ org-self-insert-command-undo-counter))))))))
17682 (defun org-check-before-invisible-edit (kind)
17683 "Check is editing if kind KIND would be dangerous with invisible text around.
17684 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17685 ;; First, try to get out of here as quickly as possible, to reduce overhead
17686 (if (and org-catch-invisible-edits
17687 (or (not (boundp 'visible-mode)) (not visible-mode))
17688 (or (get-char-property (point) 'invisible)
17689 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17690 ;; OK, we need to take a closer look
17691 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17692 (invisible-before-point (if (bobp) nil (get-char-property
17693 (1- (point)) 'invisible)))
17694 (border-and-ok-direction
17696 ;; Check if we are acting predictably before invisible text
17697 (and invisible-at-point (not invisible-before-point)
17698 (memq kind '(insert delete-backward)))
17699 ;; Check if we are acting predictably after invisible text
17700 ;; This works not well, and I have turned it off. It seems
17701 ;; better to always show and stop after invisible text.
17702 ;; (and (not invisible-at-point) invisible-before-point
17703 ;; (memq kind '(insert delete)))
17706 (when (or (memq invisible-at-point '(outline org-hide-block))
17707 (memq invisible-before-point '(outline org-hide-block)))
17708 (if (eq org-catch-invisible-edits 'error)
17709 (error "Editing in invisible areas is prohibited - make visible first"))
17710 ;; Make the area visible
17711 (save-excursion
17712 (if invisible-before-point
17713 (goto-char (previous-single-char-property-change
17714 (point) 'invisible)))
17715 (org-cycle))
17716 (cond
17717 ((eq org-catch-invisible-edits 'show)
17718 ;; That's it, we do the edit after showing
17719 (message
17720 "Unfolding invisible region around point before editing")
17721 (sit-for 1))
17722 ((and (eq org-catch-invisible-edits 'smart)
17723 border-and-ok-direction)
17724 (message "Unfolding invisible region around point before editing"))
17726 ;; Don't do the edit, make the user repeat it in full visibility
17727 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17729 (defun org-fix-tags-on-the-fly ()
17730 (when (and (equal (char-after (point-at-bol)) ?*)
17731 (org-at-heading-p))
17732 (org-align-tags-here org-tags-column)))
17734 (defun org-delete-backward-char (N)
17735 "Like `delete-backward-char', insert whitespace at field end in tables.
17736 When deleting backwards, in tables this function will insert whitespace in
17737 front of the next \"|\" separator, to keep the table aligned. The table will
17738 still be marked for re-alignment if the field did fill the entire column,
17739 because, in this case the deletion might narrow the column."
17740 (interactive "p")
17741 (org-check-before-invisible-edit 'delete-backward)
17742 (if (and (org-table-p)
17743 (eq N 1)
17744 (string-match "|" (buffer-substring (point-at-bol) (point)))
17745 (looking-at ".*?|"))
17746 (let ((pos (point))
17747 (noalign (looking-at "[^|\n\r]* |"))
17748 (c org-table-may-need-update))
17749 (backward-delete-char N)
17750 (if (not overwrite-mode)
17751 (progn
17752 (skip-chars-forward "^|")
17753 (insert " ")
17754 (goto-char (1- pos))))
17755 ;; noalign: if there were two spaces at the end, this field
17756 ;; does not determine the width of the column.
17757 (if noalign (setq org-table-may-need-update c)))
17758 (backward-delete-char N)
17759 (org-fix-tags-on-the-fly)))
17761 (defun org-delete-char (N)
17762 "Like `delete-char', but insert whitespace at field end in tables.
17763 When deleting characters, in tables this function will insert whitespace in
17764 front of the next \"|\" separator, to keep the table aligned. The table will
17765 still be marked for re-alignment if the field did fill the entire column,
17766 because, in this case the deletion might narrow the column."
17767 (interactive "p")
17768 (org-check-before-invisible-edit 'delete)
17769 (if (and (org-table-p)
17770 (not (bolp))
17771 (not (= (char-after) ?|))
17772 (eq N 1))
17773 (if (looking-at ".*?|")
17774 (let ((pos (point))
17775 (noalign (looking-at "[^|\n\r]* |"))
17776 (c org-table-may-need-update))
17777 (replace-match (concat
17778 (substring (match-string 0) 1 -1)
17779 " |"))
17780 (goto-char pos)
17781 ;; noalign: if there were two spaces at the end, this field
17782 ;; does not determine the width of the column.
17783 (if noalign (setq org-table-may-need-update c)))
17784 (delete-char N))
17785 (delete-char N)
17786 (org-fix-tags-on-the-fly)))
17788 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17789 (put 'org-self-insert-command 'delete-selection t)
17790 (put 'orgtbl-self-insert-command 'delete-selection t)
17791 (put 'org-delete-char 'delete-selection 'supersede)
17792 (put 'org-delete-backward-char 'delete-selection 'supersede)
17793 (put 'org-yank 'delete-selection 'yank)
17795 ;; Make `flyspell-mode' delay after some commands
17796 (put 'org-self-insert-command 'flyspell-delayed t)
17797 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17798 (put 'org-delete-char 'flyspell-delayed t)
17799 (put 'org-delete-backward-char 'flyspell-delayed t)
17801 ;; Make pabbrev-mode expand after org-mode commands
17802 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17803 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17805 ;; How to do this: Measure non-white length of current string
17806 ;; If equal to column width, we should realign.
17808 (defun org-remap (map &rest commands)
17809 "In MAP, remap the functions given in COMMANDS.
17810 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17811 (let (new old)
17812 (while commands
17813 (setq old (pop commands) new (pop commands))
17814 (if (fboundp 'command-remapping)
17815 (org-defkey map (vector 'remap old) new)
17816 (substitute-key-definition old new map global-map)))))
17818 (when (eq org-enable-table-editor 'optimized)
17819 ;; If the user wants maximum table support, we need to hijack
17820 ;; some standard editing functions
17821 (org-remap org-mode-map
17822 'self-insert-command 'org-self-insert-command
17823 'delete-char 'org-delete-char
17824 'delete-backward-char 'org-delete-backward-char)
17825 (org-defkey org-mode-map "|" 'org-force-self-insert))
17827 (defvar org-ctrl-c-ctrl-c-hook nil
17828 "Hook for functions attaching themselves to `C-c C-c'.
17830 This can be used to add additional functionality to the C-c C-c
17831 key which executes context-dependent commands. This hook is run
17832 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17833 run after the last test.
17835 Each function will be called with no arguments. The function
17836 must check if the context is appropriate for it to act. If yes,
17837 it should do its thing and then return a non-nil value. If the
17838 context is wrong, just do nothing and return nil.")
17840 (defvar org-ctrl-c-ctrl-c-final-hook nil
17841 "Hook for functions attaching themselves to `C-c C-c'.
17843 This can be used to add additional functionality to the C-c C-c
17844 key which executes context-dependent commands. This hook is run
17845 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17846 before the first test.
17848 Each function will be called with no arguments. The function
17849 must check if the context is appropriate for it to act. If yes,
17850 it should do its thing and then return a non-nil value. If the
17851 context is wrong, just do nothing and return nil.")
17853 (defvar org-tab-first-hook nil
17854 "Hook for functions to attach themselves to TAB.
17855 See `org-ctrl-c-ctrl-c-hook' for more information.
17856 This hook runs as the first action when TAB is pressed, even before
17857 `org-cycle' messes around with the `outline-regexp' to cater for
17858 inline tasks and plain list item folding.
17859 If any function in this hook returns t, any other actions that
17860 would have been caused by TAB (such as table field motion or visibility
17861 cycling) will not occur.")
17863 (defvar org-tab-after-check-for-table-hook nil
17864 "Hook for functions to attach themselves to TAB.
17865 See `org-ctrl-c-ctrl-c-hook' for more information.
17866 This hook runs after it has been established that the cursor is not in a
17867 table, but before checking if the cursor is in a headline or if global cycling
17868 should be done.
17869 If any function in this hook returns t, not other actions like visibility
17870 cycling will be done.")
17872 (defvar org-tab-after-check-for-cycling-hook nil
17873 "Hook for functions to attach themselves to TAB.
17874 See `org-ctrl-c-ctrl-c-hook' for more information.
17875 This hook runs after it has been established that not table field motion and
17876 not visibility should be done because of current context. This is probably
17877 the place where a package like yasnippets can hook in.")
17879 (defvar org-tab-before-tab-emulation-hook nil
17880 "Hook for functions to attach themselves to TAB.
17881 See `org-ctrl-c-ctrl-c-hook' for more information.
17882 This hook runs after every other options for TAB have been exhausted, but
17883 before indentation and \t insertion takes place.")
17885 (defvar org-metaleft-hook nil
17886 "Hook for functions attaching themselves to `M-left'.
17887 See `org-ctrl-c-ctrl-c-hook' for more information.")
17888 (defvar org-metaright-hook nil
17889 "Hook for functions attaching themselves to `M-right'.
17890 See `org-ctrl-c-ctrl-c-hook' for more information.")
17891 (defvar org-metaup-hook nil
17892 "Hook for functions attaching themselves to `M-up'.
17893 See `org-ctrl-c-ctrl-c-hook' for more information.")
17894 (defvar org-metadown-hook nil
17895 "Hook for functions attaching themselves to `M-down'.
17896 See `org-ctrl-c-ctrl-c-hook' for more information.")
17897 (defvar org-shiftmetaleft-hook nil
17898 "Hook for functions attaching themselves to `M-S-left'.
17899 See `org-ctrl-c-ctrl-c-hook' for more information.")
17900 (defvar org-shiftmetaright-hook nil
17901 "Hook for functions attaching themselves to `M-S-right'.
17902 See `org-ctrl-c-ctrl-c-hook' for more information.")
17903 (defvar org-shiftmetaup-hook nil
17904 "Hook for functions attaching themselves to `M-S-up'.
17905 See `org-ctrl-c-ctrl-c-hook' for more information.")
17906 (defvar org-shiftmetadown-hook nil
17907 "Hook for functions attaching themselves to `M-S-down'.
17908 See `org-ctrl-c-ctrl-c-hook' for more information.")
17909 (defvar org-metareturn-hook nil
17910 "Hook for functions attaching themselves to `M-RET'.
17911 See `org-ctrl-c-ctrl-c-hook' for more information.")
17912 (defvar org-shiftup-hook nil
17913 "Hook for functions attaching themselves to `S-up'.
17914 See `org-ctrl-c-ctrl-c-hook' for more information.")
17915 (defvar org-shiftup-final-hook nil
17916 "Hook for functions attaching themselves to `S-up'.
17917 This one runs after all other options except shift-select have been excluded.
17918 See `org-ctrl-c-ctrl-c-hook' for more information.")
17919 (defvar org-shiftdown-hook nil
17920 "Hook for functions attaching themselves to `S-down'.
17921 See `org-ctrl-c-ctrl-c-hook' for more information.")
17922 (defvar org-shiftdown-final-hook nil
17923 "Hook for functions attaching themselves to `S-down'.
17924 This one runs after all other options except shift-select have been excluded.
17925 See `org-ctrl-c-ctrl-c-hook' for more information.")
17926 (defvar org-shiftleft-hook nil
17927 "Hook for functions attaching themselves to `S-left'.
17928 See `org-ctrl-c-ctrl-c-hook' for more information.")
17929 (defvar org-shiftleft-final-hook nil
17930 "Hook for functions attaching themselves to `S-left'.
17931 This one runs after all other options except shift-select have been excluded.
17932 See `org-ctrl-c-ctrl-c-hook' for more information.")
17933 (defvar org-shiftright-hook nil
17934 "Hook for functions attaching themselves to `S-right'.
17935 See `org-ctrl-c-ctrl-c-hook' for more information.")
17936 (defvar org-shiftright-final-hook nil
17937 "Hook for functions attaching themselves to `S-right'.
17938 This one runs after all other options except shift-select have been excluded.
17939 See `org-ctrl-c-ctrl-c-hook' for more information.")
17941 (defun org-modifier-cursor-error ()
17942 "Throw an error, a modified cursor command was applied in wrong context."
17943 (error "This command is active in special context like tables, headlines or items"))
17945 (defun org-shiftselect-error ()
17946 "Throw an error because Shift-Cursor command was applied in wrong context."
17947 (if (and (boundp 'shift-select-mode) shift-select-mode)
17948 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17949 (error "This command works only in special context like headlines or timestamps")))
17951 (defun org-call-for-shift-select (cmd)
17952 (let ((this-command-keys-shift-translated t))
17953 (call-interactively cmd)))
17955 (defun org-shifttab (&optional arg)
17956 "Global visibility cycling or move to previous table field.
17957 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17958 on context.
17959 See the individual commands for more information."
17960 (interactive "P")
17961 (cond
17962 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17963 ((integerp arg)
17964 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17965 (message "Content view to level: %d" arg)
17966 (org-content (prefix-numeric-value arg2))
17967 (setq org-cycle-global-status 'overview)))
17968 (t (call-interactively 'org-global-cycle))))
17970 (defun org-shiftmetaleft ()
17971 "Promote subtree or delete table column.
17972 Calls `org-promote-subtree', `org-outdent-item',
17973 or `org-table-delete-column', depending on context.
17974 See the individual commands for more information."
17975 (interactive)
17976 (cond
17977 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17978 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17979 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17980 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17981 (t (org-modifier-cursor-error))))
17983 (defun org-shiftmetaright ()
17984 "Demote subtree or insert table column.
17985 Calls `org-demote-subtree', `org-indent-item',
17986 or `org-table-insert-column', depending on context.
17987 See the individual commands for more information."
17988 (interactive)
17989 (cond
17990 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17991 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17992 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
17993 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17994 (t (org-modifier-cursor-error))))
17996 (defun org-shiftmetaup (&optional arg)
17997 "Move subtree up or kill table row.
17998 Calls `org-move-subtree-up' or `org-table-kill-row' or
17999 `org-move-item-up' depending on context. See the individual commands
18000 for more information."
18001 (interactive "P")
18002 (cond
18003 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18004 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18005 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18006 ((org-at-item-p) (call-interactively 'org-move-item-up))
18007 (t (org-modifier-cursor-error))))
18009 (defun org-shiftmetadown (&optional arg)
18010 "Move subtree down or insert table row.
18011 Calls `org-move-subtree-down' or `org-table-insert-row' or
18012 `org-move-item-down', depending on context. See the individual
18013 commands for more information."
18014 (interactive "P")
18015 (cond
18016 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18017 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18018 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18019 ((org-at-item-p) (call-interactively 'org-move-item-down))
18020 (t (org-modifier-cursor-error))))
18022 (defsubst org-hidden-tree-error ()
18023 (error
18024 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18026 (defun org-metaleft (&optional arg)
18027 "Promote heading or move table column to left.
18028 Calls `org-do-promote' or `org-table-move-column', depending on context.
18029 With no specific context, calls the Emacs default `backward-word'.
18030 See the individual commands for more information."
18031 (interactive "P")
18032 (cond
18033 ((run-hook-with-args-until-success 'org-metaleft-hook))
18034 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18035 ((org-with-limited-levels
18036 (or (org-at-heading-p)
18037 (and (org-region-active-p)
18038 (save-excursion
18039 (goto-char (region-beginning))
18040 (org-at-heading-p)))))
18041 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18042 (call-interactively 'org-do-promote))
18043 ;; At an inline task.
18044 ((org-at-heading-p)
18045 (call-interactively 'org-inlinetask-promote))
18046 ((or (org-at-item-p)
18047 (and (org-region-active-p)
18048 (save-excursion
18049 (goto-char (region-beginning))
18050 (org-at-item-p))))
18051 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18052 (call-interactively 'org-outdent-item))
18053 (t (call-interactively 'backward-word))))
18055 (defun org-metaright (&optional arg)
18056 "Demote subtree or move table column to right.
18057 Calls `org-do-demote' or `org-table-move-column', depending on context.
18058 With no specific context, calls the Emacs default `forward-word'.
18059 See the individual commands for more information."
18060 (interactive "P")
18061 (cond
18062 ((run-hook-with-args-until-success 'org-metaright-hook))
18063 ((org-at-table-p) (call-interactively 'org-table-move-column))
18064 ((org-with-limited-levels
18065 (or (org-at-heading-p)
18066 (and (org-region-active-p)
18067 (save-excursion
18068 (goto-char (region-beginning))
18069 (org-at-heading-p)))))
18070 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18071 (call-interactively 'org-do-demote))
18072 ;; At an inline task.
18073 ((org-at-heading-p)
18074 (call-interactively 'org-inlinetask-demote))
18075 ((or (org-at-item-p)
18076 (and (org-region-active-p)
18077 (save-excursion
18078 (goto-char (region-beginning))
18079 (org-at-item-p))))
18080 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18081 (call-interactively 'org-indent-item))
18082 (t (call-interactively 'forward-word))))
18084 (defun org-check-for-hidden (what)
18085 "Check if there are hidden headlines/items in the current visual line.
18086 WHAT can be either `headlines' or `items'. If the current line is
18087 an outline or item heading and it has a folded subtree below it,
18088 this function returns t, nil otherwise."
18089 (let ((re (cond
18090 ((eq what 'headlines) org-outline-regexp-bol)
18091 ((eq what 'items) (org-item-beginning-re))
18092 (t (error "This should not happen"))))
18093 beg end)
18094 (save-excursion
18095 (catch 'exit
18096 (unless (org-region-active-p)
18097 (setq beg (point-at-bol))
18098 (beginning-of-line 2)
18099 (while (and (not (eobp)) ;; this is like `next-line'
18100 (get-char-property (1- (point)) 'invisible))
18101 (beginning-of-line 2))
18102 (setq end (point))
18103 (goto-char beg)
18104 (goto-char (point-at-eol))
18105 (setq end (max end (point)))
18106 (while (re-search-forward re end t)
18107 (if (get-char-property (match-beginning 0) 'invisible)
18108 (throw 'exit t))))
18109 nil))))
18111 (defun org-metaup (&optional arg)
18112 "Move subtree up or move table row up.
18113 Calls `org-move-subtree-up' or `org-table-move-row' or
18114 `org-move-item-up', depending on context. See the individual commands
18115 for more information."
18116 (interactive "P")
18117 (cond
18118 ((run-hook-with-args-until-success 'org-metaup-hook))
18119 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18120 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18121 ((org-at-item-p) (call-interactively 'org-move-item-up))
18122 (t (transpose-lines 1) (beginning-of-line -1))))
18124 (defun org-metadown (&optional arg)
18125 "Move subtree down or move table row down.
18126 Calls `org-move-subtree-down' or `org-table-move-row' or
18127 `org-move-item-down', depending on context. See the individual
18128 commands for more information."
18129 (interactive "P")
18130 (cond
18131 ((run-hook-with-args-until-success 'org-metadown-hook))
18132 ((org-at-table-p) (call-interactively 'org-table-move-row))
18133 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18134 ((org-at-item-p) (call-interactively 'org-move-item-down))
18135 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18137 (defun org-shiftup (&optional arg)
18138 "Increase item in timestamp or increase priority of current headline.
18139 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18140 depending on context. See the individual commands for more information."
18141 (interactive "P")
18142 (cond
18143 ((run-hook-with-args-until-success 'org-shiftup-hook))
18144 ((and org-support-shift-select (org-region-active-p))
18145 (org-call-for-shift-select 'previous-line))
18146 ((org-at-timestamp-p t)
18147 (call-interactively (if org-edit-timestamp-down-means-later
18148 'org-timestamp-down 'org-timestamp-up)))
18149 ((and (not (eq org-support-shift-select 'always))
18150 org-enable-priority-commands
18151 (org-at-heading-p))
18152 (call-interactively 'org-priority-up))
18153 ((and (not org-support-shift-select) (org-at-item-p))
18154 (call-interactively 'org-previous-item))
18155 ((org-clocktable-try-shift 'up arg))
18156 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18157 (org-support-shift-select
18158 (org-call-for-shift-select 'previous-line))
18159 (t (org-shiftselect-error))))
18161 (defun org-shiftdown (&optional arg)
18162 "Decrease item in timestamp or decrease priority of current headline.
18163 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18164 depending on context. See the individual commands for more information."
18165 (interactive "P")
18166 (cond
18167 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18168 ((and org-support-shift-select (org-region-active-p))
18169 (org-call-for-shift-select 'next-line))
18170 ((org-at-timestamp-p t)
18171 (call-interactively (if org-edit-timestamp-down-means-later
18172 'org-timestamp-up 'org-timestamp-down)))
18173 ((and (not (eq org-support-shift-select 'always))
18174 org-enable-priority-commands
18175 (org-at-heading-p))
18176 (call-interactively 'org-priority-down))
18177 ((and (not org-support-shift-select) (org-at-item-p))
18178 (call-interactively 'org-next-item))
18179 ((org-clocktable-try-shift 'down arg))
18180 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18181 (org-support-shift-select
18182 (org-call-for-shift-select 'next-line))
18183 (t (org-shiftselect-error))))
18185 (defun org-shiftright (&optional arg)
18186 "Cycle the thing at point or in the current line, depending on context.
18187 Depending on context, this does one of the following:
18189 - switch a timestamp at point one day into the future
18190 - on a headline, switch to the next TODO keyword.
18191 - on an item, switch entire list to the next bullet type
18192 - on a property line, switch to the next allowed value
18193 - on a clocktable definition line, move time block into the future"
18194 (interactive "P")
18195 (cond
18196 ((run-hook-with-args-until-success 'org-shiftright-hook))
18197 ((and org-support-shift-select (org-region-active-p))
18198 (org-call-for-shift-select 'forward-char))
18199 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18200 ((and (not (eq org-support-shift-select 'always))
18201 (org-at-heading-p))
18202 (let ((org-inhibit-logging
18203 (not org-treat-S-cursor-todo-selection-as-state-change))
18204 (org-inhibit-blocking
18205 (not org-treat-S-cursor-todo-selection-as-state-change)))
18206 (org-call-with-arg 'org-todo 'right)))
18207 ((or (and org-support-shift-select
18208 (not (eq org-support-shift-select 'always))
18209 (org-at-item-bullet-p))
18210 (and (not org-support-shift-select) (org-at-item-p)))
18211 (org-call-with-arg 'org-cycle-list-bullet nil))
18212 ((and (not (eq org-support-shift-select 'always))
18213 (org-at-property-p))
18214 (call-interactively 'org-property-next-allowed-value))
18215 ((org-clocktable-try-shift 'right arg))
18216 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18217 (org-support-shift-select
18218 (org-call-for-shift-select 'forward-char))
18219 (t (org-shiftselect-error))))
18221 (defun org-shiftleft (&optional arg)
18222 "Cycle the thing at point or in the current line, depending on context.
18223 Depending on context, this does one of the following:
18225 - switch a timestamp at point one day into the past
18226 - on a headline, switch to the previous TODO keyword.
18227 - on an item, switch entire list to the previous bullet type
18228 - on a property line, switch to the previous allowed value
18229 - on a clocktable definition line, move time block into the past"
18230 (interactive "P")
18231 (cond
18232 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18233 ((and org-support-shift-select (org-region-active-p))
18234 (org-call-for-shift-select 'backward-char))
18235 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18236 ((and (not (eq org-support-shift-select 'always))
18237 (org-at-heading-p))
18238 (let ((org-inhibit-logging
18239 (not org-treat-S-cursor-todo-selection-as-state-change))
18240 (org-inhibit-blocking
18241 (not org-treat-S-cursor-todo-selection-as-state-change)))
18242 (org-call-with-arg 'org-todo 'left)))
18243 ((or (and org-support-shift-select
18244 (not (eq org-support-shift-select 'always))
18245 (org-at-item-bullet-p))
18246 (and (not org-support-shift-select) (org-at-item-p)))
18247 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18248 ((and (not (eq org-support-shift-select 'always))
18249 (org-at-property-p))
18250 (call-interactively 'org-property-previous-allowed-value))
18251 ((org-clocktable-try-shift 'left arg))
18252 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18253 (org-support-shift-select
18254 (org-call-for-shift-select 'backward-char))
18255 (t (org-shiftselect-error))))
18257 (defun org-shiftcontrolright ()
18258 "Switch to next TODO set."
18259 (interactive)
18260 (cond
18261 ((and org-support-shift-select (org-region-active-p))
18262 (org-call-for-shift-select 'forward-word))
18263 ((and (not (eq org-support-shift-select 'always))
18264 (org-at-heading-p))
18265 (org-call-with-arg 'org-todo 'nextset))
18266 (org-support-shift-select
18267 (org-call-for-shift-select 'forward-word))
18268 (t (org-shiftselect-error))))
18270 (defun org-shiftcontrolleft ()
18271 "Switch to previous TODO set."
18272 (interactive)
18273 (cond
18274 ((and org-support-shift-select (org-region-active-p))
18275 (org-call-for-shift-select 'backward-word))
18276 ((and (not (eq org-support-shift-select 'always))
18277 (org-at-heading-p))
18278 (org-call-with-arg 'org-todo 'previousset))
18279 (org-support-shift-select
18280 (org-call-for-shift-select 'backward-word))
18281 (t (org-shiftselect-error))))
18283 (defun org-shiftcontrolup ()
18284 "Change timestamps synchronously up in CLOCK log lines."
18285 (interactive)
18286 (cond ((and (not org-support-shift-select)
18287 (org-at-clock-log-p)
18288 (org-at-timestamp-p t))
18289 (org-clock-timestamps-up))
18290 (t (org-shiftselect-error))))
18292 (defun org-shiftcontroldown ()
18293 "Change timestamps synchronously down in CLOCK log lines."
18294 (interactive)
18295 (cond ((and (not org-support-shift-select)
18296 (org-at-clock-log-p)
18297 (org-at-timestamp-p t))
18298 (org-clock-timestamps-down))
18299 (t (org-shiftselect-error))))
18301 (defun org-ctrl-c-ret ()
18302 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18303 (interactive)
18304 (cond
18305 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18306 (t (call-interactively 'org-insert-heading))))
18308 (defun org-find-visible ()
18309 (let ((s (point)))
18310 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18311 (get-char-property s 'invisible)))
18313 (defun org-find-invisible ()
18314 (let ((s (point)))
18315 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18316 (not (get-char-property s 'invisible))))
18319 (defun org-copy-visible (beg end)
18320 "Copy the visible parts of the region."
18321 (interactive "r")
18322 (let (snippets s)
18323 (save-excursion
18324 (save-restriction
18325 (narrow-to-region beg end)
18326 (setq s (goto-char (point-min)))
18327 (while (not (= (point) (point-max)))
18328 (goto-char (org-find-invisible))
18329 (push (buffer-substring s (point)) snippets)
18330 (setq s (goto-char (org-find-visible))))))
18331 (kill-new (apply 'concat (nreverse snippets)))))
18333 (defun org-copy-special ()
18334 "Copy region in table or copy current subtree.
18335 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18336 See the individual commands for more information."
18337 (interactive)
18338 (call-interactively
18339 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18341 (defun org-cut-special ()
18342 "Cut region in table or cut current subtree.
18343 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18344 See the individual commands for more information."
18345 (interactive)
18346 (call-interactively
18347 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18349 (defun org-paste-special (arg)
18350 "Paste rectangular region into table, or past subtree relative to level.
18351 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18352 See the individual commands for more information."
18353 (interactive "P")
18354 (if (org-at-table-p)
18355 (org-table-paste-rectangle)
18356 (org-paste-subtree arg)))
18358 (defun org-edit-special (&optional arg)
18359 "Call a special editor for the stuff at point.
18360 When at a table, call the formula editor with `org-table-edit-formulas'.
18361 When at the first line of an src example, call `org-edit-src-code'.
18362 When in an #+include line, visit the include file. Otherwise call
18363 `ffap' to visit the file at point."
18364 (interactive)
18365 ;; possibly prep session before editing source
18366 (when arg
18367 (let* ((info (org-babel-get-src-block-info))
18368 (lang (nth 0 info))
18369 (params (nth 2 info))
18370 (session (cdr (assoc :session params))))
18371 (when (and info session) ;; we are in a source-code block with a session
18372 (funcall
18373 (intern (concat "org-babel-prep-session:" lang)) session params))))
18374 (cond ;; proceed with `org-edit-special'
18375 ((save-excursion
18376 (beginning-of-line 1)
18377 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18378 (find-file (org-trim (match-string 1))))
18379 ((org-edit-src-code))
18380 ((org-edit-fixed-width-region))
18381 ((org-at-table.el-p)
18382 (org-edit-src-code))
18383 ((or (org-at-table-p)
18384 (save-excursion
18385 (beginning-of-line 1)
18386 (looking-at "[ \t]*#\\+TBLFM:")))
18387 (call-interactively 'org-table-edit-formulas))
18388 (t (call-interactively 'ffap))))
18390 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18391 (defun org-ctrl-c-ctrl-c (&optional arg)
18392 "Set tags in headline, or update according to changed information at point.
18394 This command does many different things, depending on context:
18396 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18397 this is what we do.
18399 - If the cursor is on a statistics cookie, update it.
18401 - If the cursor is in a headline, prompt for tags and insert them
18402 into the current line, aligned to `org-tags-column'. When called
18403 with prefix arg, realign all tags in the current buffer.
18405 - If the cursor is in one of the special #+KEYWORD lines, this
18406 triggers scanning the buffer for these lines and updating the
18407 information.
18409 - If the cursor is inside a table, realign the table. This command
18410 works even if the automatic table editor has been turned off.
18412 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18413 the entire table.
18415 - If the cursor is at a footnote reference or definition, jump to
18416 the corresponding definition or references, respectively.
18418 - If the cursor is a the beginning of a dynamic block, update it.
18420 - If the current buffer is a capture buffer, close note and file it.
18422 - If the cursor is on a <<<target>>>, update radio targets and
18423 corresponding links in this buffer.
18425 - If the cursor is on a numbered item in a plain list, renumber the
18426 ordered list.
18428 - If the cursor is on a checkbox, toggle it.
18430 - If the cursor is on a code block, evaluate it. The variable
18431 `org-confirm-babel-evaluate' can be used to control prompting
18432 before code block evaluation, by default every code block
18433 evaluation requires confirmation. Code block evaluation can be
18434 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18435 (interactive "P")
18436 (let ((org-enable-table-editor t))
18437 (cond
18438 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18439 org-occur-highlights
18440 org-latex-fragment-image-overlays)
18441 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18442 (org-remove-occur-highlights)
18443 (org-remove-latex-fragment-image-overlays)
18444 (message "Temporary highlights/overlays removed from current buffer"))
18445 ((and (local-variable-p 'org-finish-function (current-buffer))
18446 (fboundp org-finish-function))
18447 (funcall org-finish-function))
18448 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18449 ((org-in-regexp org-ts-regexp-both)
18450 (org-timestamp-change 0 'day))
18451 ((or (looking-at org-property-start-re)
18452 (org-at-property-p))
18453 (call-interactively 'org-property-action))
18454 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18455 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18456 (or (org-at-heading-p) (org-at-item-p)))
18457 (call-interactively 'org-update-statistics-cookies))
18458 ((org-at-heading-p) (call-interactively 'org-set-tags))
18459 ((org-at-table.el-p)
18460 (message "Use C-c ' to edit table.el tables"))
18461 ((org-at-table-p)
18462 (org-table-maybe-eval-formula)
18463 (if arg
18464 (call-interactively 'org-table-recalculate)
18465 (org-table-maybe-recalculate-line))
18466 (call-interactively 'org-table-align)
18467 (orgtbl-send-table 'maybe))
18468 ((or (org-footnote-at-reference-p)
18469 (org-footnote-at-definition-p))
18470 (call-interactively 'org-footnote-action))
18471 ((org-at-item-checkbox-p)
18472 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18473 ;; list only if at top item.
18474 (let* ((cbox (match-string 1))
18475 (struct (org-list-struct))
18476 (old-struct (copy-tree struct))
18477 (parents (org-list-parents-alist struct))
18478 (orderedp (org-entry-get nil "ORDERED"))
18479 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18480 block-item)
18481 ;; Use a light version of `org-toggle-checkbox' to avoid
18482 ;; computing list structure twice.
18483 (let ((new-box (cond
18484 ((equal arg '(16)) "[-]")
18485 ((equal arg '(4)) nil)
18486 ((equal "[X]" cbox) "[ ]")
18487 (t "[X]"))))
18488 (if (and firstp arg)
18489 ;; If at first item of sub-list, remove check-box from
18490 ;; every item at the same level.
18491 (mapc
18492 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18493 (org-list-get-all-items
18494 (point-at-bol) struct (org-list-prevs-alist struct)))
18495 (org-list-set-checkbox (point-at-bol) struct new-box)))
18496 ;; Replicate `org-list-write-struct', while grabbing a return
18497 ;; value from `org-list-struct-fix-box'.
18498 (org-list-struct-fix-ind struct parents 2)
18499 (org-list-struct-fix-item-end struct)
18500 (let ((prevs (org-list-prevs-alist struct)))
18501 (org-list-struct-fix-bul struct prevs)
18502 (org-list-struct-fix-ind struct parents)
18503 (setq block-item
18504 (org-list-struct-fix-box struct parents prevs orderedp)))
18505 (org-list-struct-apply-struct struct old-struct)
18506 (org-update-checkbox-count-maybe)
18507 (when block-item
18508 (message
18509 "Checkboxes were removed due to unchecked box at line %d"
18510 (org-current-line block-item)))
18511 (when firstp (org-list-send-list 'maybe))))
18512 ((org-at-item-p)
18513 ;; Cursor at an item: repair list. Do checkbox related actions
18514 ;; only if function was called with an argument. Send list only
18515 ;; if at top item.
18516 (let* ((struct (org-list-struct))
18517 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18518 old-struct)
18519 (when arg
18520 (setq old-struct (copy-tree struct))
18521 (if firstp
18522 ;; If at first item of sub-list, add check-box to every
18523 ;; item at the same level.
18524 (mapc
18525 (lambda (pos)
18526 (unless (org-list-get-checkbox pos struct)
18527 (org-list-set-checkbox pos struct "[ ]")))
18528 (org-list-get-all-items
18529 (point-at-bol) struct (org-list-prevs-alist struct)))
18530 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18531 (org-list-write-struct
18532 struct (org-list-parents-alist struct) old-struct)
18533 (when arg (org-update-checkbox-count-maybe))
18534 (when firstp (org-list-send-list 'maybe))))
18535 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18536 ;; Dynamic block
18537 (beginning-of-line 1)
18538 (save-excursion (org-update-dblock)))
18539 ((save-excursion
18540 (beginning-of-line 1)
18541 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18542 (cond
18543 ((equal (match-string 1) "TBLFM")
18544 ;; Recalculate the table before this line
18545 (save-excursion
18546 (beginning-of-line 1)
18547 (skip-chars-backward " \r\n\t")
18548 (if (org-at-table-p)
18549 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18551 (let ((org-inhibit-startup-visibility-stuff t)
18552 (org-startup-align-all-tables nil))
18553 (when (boundp 'org-table-coordinate-overlays)
18554 (mapc 'delete-overlay org-table-coordinate-overlays)
18555 (setq org-table-coordinate-overlays nil))
18556 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18557 (message "Local setup has been refreshed"))))
18558 ((org-clock-update-time-maybe))
18560 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18561 (error "C-c C-c can do nothing useful at this location"))))))
18563 (defun org-mode-restart ()
18564 "Restart Org-mode, to scan again for special lines.
18565 Also updates the keyword regular expressions."
18566 (interactive)
18567 (org-mode)
18568 (message "Org-mode restarted"))
18570 (defun org-kill-note-or-show-branches ()
18571 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18572 (interactive)
18573 (if (not org-finish-function)
18574 (progn
18575 (hide-subtree)
18576 (call-interactively 'show-branches))
18577 (let ((org-note-abort t))
18578 (funcall org-finish-function))))
18580 (defun org-return (&optional indent)
18581 "Goto next table row or insert a newline.
18582 Calls `org-table-next-row' or `newline', depending on context.
18583 See the individual commands for more information."
18584 (interactive)
18585 (cond
18586 ((bobp) (if indent (newline-and-indent) (newline)))
18587 ((org-at-table-p)
18588 (org-table-justify-field-maybe)
18589 (call-interactively 'org-table-next-row))
18590 ;; when `newline-and-indent' is called within a list, make sure
18591 ;; text moved stays inside the item.
18592 ((and (org-in-item-p) indent)
18593 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18594 (progn
18595 (save-match-data (newline))
18596 (org-indent-line-to (length (match-string 0))))
18597 (let ((ind (org-get-indentation)))
18598 (newline)
18599 (if (org-looking-back org-list-end-re)
18600 (org-indent-line-function)
18601 (org-indent-line-to ind)))))
18602 ((and org-return-follows-link
18603 (let ((tprop (get-text-property (point) 'face)))
18604 (or (eq tprop 'org-link)
18605 (and (listp tprop) (memq 'org-link tprop)))))
18606 (call-interactively 'org-open-at-point))
18607 ((and (org-at-heading-p)
18608 (looking-at
18609 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18610 (org-show-entry)
18611 (end-of-line 1)
18612 (newline))
18613 (t (if indent (newline-and-indent) (newline)))))
18615 (defun org-return-indent ()
18616 "Goto next table row or insert a newline and indent.
18617 Calls `org-table-next-row' or `newline-and-indent', depending on
18618 context. See the individual commands for more information."
18619 (interactive)
18620 (org-return t))
18622 (defun org-ctrl-c-star ()
18623 "Compute table, or change heading status of lines.
18624 Calls `org-table-recalculate' or `org-toggle-heading',
18625 depending on context."
18626 (interactive)
18627 (cond
18628 ((org-at-table-p)
18629 (call-interactively 'org-table-recalculate))
18631 ;; Convert all lines in region to list items
18632 (call-interactively 'org-toggle-heading))))
18634 (defun org-ctrl-c-minus ()
18635 "Insert separator line in table or modify bullet status of line.
18636 Also turns a plain line or a region of lines into list items.
18637 Calls `org-table-insert-hline', `org-toggle-item', or
18638 `org-cycle-list-bullet', depending on context."
18639 (interactive)
18640 (cond
18641 ((org-at-table-p)
18642 (call-interactively 'org-table-insert-hline))
18643 ((org-region-active-p)
18644 (call-interactively 'org-toggle-item))
18645 ((org-in-item-p)
18646 (call-interactively 'org-cycle-list-bullet))
18648 (call-interactively 'org-toggle-item))))
18650 (defun org-toggle-item (arg)
18651 "Convert headings or normal lines to items, items to normal lines.
18652 If there is no active region, only the current line is considered.
18654 If the first non blank line in the region is an headline, convert
18655 all headlines to items, shifting text accordingly.
18657 If it is an item, convert all items to normal lines.
18659 If it is normal text, change region into an item. With a prefix
18660 argument ARG, change each line in region into an item."
18661 (interactive "P")
18662 (let ((shift-text
18663 (function
18664 ;; Shift text in current section to IND, from point to END.
18665 ;; The function leaves point to END line.
18666 (lambda (ind end)
18667 (let ((min-i 1000) (end (copy-marker end)))
18668 ;; First determine the minimum indentation (MIN-I) of
18669 ;; the text.
18670 (save-excursion
18671 (catch 'exit
18672 (while (< (point) end)
18673 (let ((i (org-get-indentation)))
18674 (cond
18675 ;; Skip blank lines and inline tasks.
18676 ((looking-at "^[ \t]*$"))
18677 ((looking-at org-outline-regexp-bol))
18678 ;; We can't find less than 0 indentation.
18679 ((zerop i) (throw 'exit (setq min-i 0)))
18680 ((< i min-i) (setq min-i i))))
18681 (forward-line))))
18682 ;; Then indent each line so that a line indented to
18683 ;; MIN-I becomes indented to IND. Ignore blank lines
18684 ;; and inline tasks in the process.
18685 (let ((delta (- ind min-i)))
18686 (while (< (point) end)
18687 (unless (or (looking-at "^[ \t]*$")
18688 (looking-at org-outline-regexp-bol))
18689 (org-indent-line-to (+ (org-get-indentation) delta)))
18690 (forward-line)))))))
18691 (skip-blanks
18692 (function
18693 ;; Return beginning of first non-blank line, starting from
18694 ;; line at POS.
18695 (lambda (pos)
18696 (save-excursion
18697 (goto-char pos)
18698 (skip-chars-forward " \r\t\n")
18699 (point-at-bol)))))
18700 beg end)
18701 ;; Determine boundaries of changes.
18702 (if (org-region-active-p)
18703 (setq beg (funcall skip-blanks (region-beginning))
18704 end (copy-marker (region-end)))
18705 (setq beg (funcall skip-blanks (point-at-bol))
18706 end (copy-marker (point-at-eol))))
18707 ;; Depending on the starting line, choose an action on the text
18708 ;; between BEG and END.
18709 (org-with-limited-levels
18710 (save-excursion
18711 (goto-char beg)
18712 (cond
18713 ;; Case 1. Start at an item: de-itemize. Note that it only
18714 ;; happens when a region is active: `org-ctrl-c-minus'
18715 ;; would call `org-cycle-list-bullet' otherwise.
18716 ((org-at-item-p)
18717 (while (< (point) end)
18718 (when (org-at-item-p)
18719 (skip-chars-forward " \t")
18720 (delete-region (point) (match-end 0)))
18721 (forward-line)))
18722 ;; Case 2. Start at an heading: convert to items.
18723 ((org-at-heading-p)
18724 (let* ((bul (org-list-bullet-string "-"))
18725 (bul-len (length bul))
18726 ;; Indentation of the first heading. It should be
18727 ;; relative to the indentation of its parent, if any.
18728 (start-ind (save-excursion
18729 (cond
18730 ((not org-adapt-indentation) 0)
18731 ((not (outline-previous-heading)) 0)
18732 (t (length (match-string 0))))))
18733 ;; Level of first heading. Further headings will be
18734 ;; compared to it to determine hierarchy in the list.
18735 (ref-level (org-reduced-level (org-outline-level))))
18736 (while (< (point) end)
18737 (let* ((level (org-reduced-level (org-outline-level)))
18738 (delta (max 0 (- level ref-level))))
18739 ;; If current headline is less indented than the first
18740 ;; one, set it as reference, in order to preserve
18741 ;; subtrees.
18742 (when (< level ref-level) (setq ref-level level))
18743 (replace-match bul t t)
18744 (org-indent-line-to (+ start-ind (* delta bul-len)))
18745 ;; Ensure all text down to END (or SECTION-END) belongs
18746 ;; to the newly created item.
18747 (let ((section-end (save-excursion
18748 (or (outline-next-heading) (point)))))
18749 (forward-line)
18750 (funcall shift-text
18751 (+ start-ind (* (1+ delta) bul-len))
18752 (min end section-end)))))))
18753 ;; Case 3. Normal line with ARG: turn each non-item line into
18754 ;; an item.
18755 (arg
18756 (while (< (point) end)
18757 (unless (or (org-at-heading-p) (org-at-item-p))
18758 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18759 (replace-match
18760 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18761 (forward-line)))
18762 ;; Case 4. Normal line without ARG: make the first line of
18763 ;; region an item, and shift indentation of others
18764 ;; lines to set them as item's body.
18765 (t (let* ((bul (org-list-bullet-string "-"))
18766 (bul-len (length bul))
18767 (ref-ind (org-get-indentation)))
18768 (skip-chars-forward " \t")
18769 (insert bul)
18770 (forward-line)
18771 (while (< (point) end)
18772 ;; Ensure that lines less indented than first one
18773 ;; still get included in item body.
18774 (funcall shift-text
18775 (+ ref-ind bul-len)
18776 (min end (save-excursion (or (outline-next-heading)
18777 (point)))))
18778 (forward-line)))))))))
18780 (defun org-toggle-heading (&optional nstars)
18781 "Convert headings to normal text, or items or text to headings.
18782 If there is no active region, only the current line is considered.
18784 If the first non blank line is an headline, remove the stars from
18785 all headlines in the region.
18787 If it is a plain list item, turn all plain list items into headings.
18789 If it is a normal line, turn each and every normal line (i.e. not
18790 an heading or an item) in the region into a heading.
18792 When converting a line into a heading, the number of stars is chosen
18793 such that the lines become children of the current entry. However,
18794 when a prefix argument is given, its value determines the number of
18795 stars to add."
18796 (interactive "P")
18797 (let ((skip-blanks
18798 (function
18799 ;; Return beginning of first non-blank line, starting from
18800 ;; line at POS.
18801 (lambda (pos)
18802 (save-excursion
18803 (goto-char pos)
18804 (skip-chars-forward " \r\t\n")
18805 (point-at-bol)))))
18806 beg end)
18807 ;; Determine boundaries of changes. If region ends at a bol, do
18808 ;; not consider the last line to be in the region.
18809 (if (org-region-active-p)
18810 (setq beg (funcall skip-blanks (region-beginning))
18811 end (copy-marker (save-excursion
18812 (goto-char (region-end))
18813 (if (bolp) (point) (point-at-eol)))))
18814 (setq beg (funcall skip-blanks (point-at-bol))
18815 end (copy-marker (point-at-eol))))
18816 ;; Ensure inline tasks don't count as headings.
18817 (org-with-limited-levels
18818 (save-excursion
18819 (goto-char beg)
18820 (cond
18821 ;; Case 1. Started at an heading: de-star headings.
18822 ((org-at-heading-p)
18823 (while (< (point) end)
18824 (when (org-at-heading-p t)
18825 (looking-at org-outline-regexp) (replace-match ""))
18826 (forward-line)))
18827 ;; Case 2. Started at an item: change items into headlines.
18828 ;; One star will be added by `org-list-to-subtree'.
18829 ((org-at-item-p)
18830 (let* ((stars (make-string
18831 (if nstars
18832 ;; subtract the star that will be added again by
18833 ;; `org-list-to-subtree'
18834 (1- (prefix-numeric-value current-prefix-arg))
18835 (or (org-current-level) 0))
18836 ?*))
18837 (add-stars
18838 (cond (nstars "") ; stars from prefix only
18839 ((equal stars "") "") ; before first heading
18840 (org-odd-levels-only "*") ; inside heading, odd
18841 (t "")))) ; inside heading, oddeven
18842 (while (< (point) end)
18843 (when (org-at-item-p)
18844 ;; Pay attention to cases when region ends before list.
18845 (let* ((struct (org-list-struct))
18846 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18847 (save-restriction
18848 (narrow-to-region (point) list-end)
18849 (insert
18850 (org-list-to-subtree
18851 (org-list-parse-list t)
18852 '(:istart (concat stars add-stars (funcall get-stars depth))
18853 :icount (concat stars add-stars (funcall get-stars depth))))))))
18854 (forward-line))))
18855 ;; Case 3. Started at normal text: make every line an heading,
18856 ;; skipping headlines and items.
18857 (t (let* ((stars (make-string
18858 (if nstars
18859 (prefix-numeric-value current-prefix-arg)
18860 (or (org-current-level) 0))
18861 ?*))
18862 (add-stars
18863 (cond (nstars "") ; stars from prefix only
18864 ((equal stars "") "*") ; before first heading
18865 (org-odd-levels-only "**") ; inside heading, odd
18866 (t "*"))) ; inside heading, oddeven
18867 (rpl (concat stars add-stars " ")))
18868 (while (< (point) end)
18869 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18870 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18871 (replace-match (concat rpl (match-string 2))))
18872 (forward-line)))))))))
18874 (defun org-meta-return (&optional arg)
18875 "Insert a new heading or wrap a region in a table.
18876 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18877 See the individual commands for more information."
18878 (interactive "P")
18879 (cond
18880 ((run-hook-with-args-until-success 'org-metareturn-hook))
18881 ((org-at-table-p)
18882 (call-interactively 'org-table-wrap-region))
18883 (t (call-interactively 'org-insert-heading))))
18885 ;;; Menu entries
18887 ;; Define the Org-mode menus
18888 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18889 '("Tbl"
18890 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18891 ["Next Field" org-cycle (org-at-table-p)]
18892 ["Previous Field" org-shifttab (org-at-table-p)]
18893 ["Next Row" org-return (org-at-table-p)]
18894 "--"
18895 ["Blank Field" org-table-blank-field (org-at-table-p)]
18896 ["Edit Field" org-table-edit-field (org-at-table-p)]
18897 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18898 "--"
18899 ("Column"
18900 ["Move Column Left" org-metaleft (org-at-table-p)]
18901 ["Move Column Right" org-metaright (org-at-table-p)]
18902 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18903 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18904 ("Row"
18905 ["Move Row Up" org-metaup (org-at-table-p)]
18906 ["Move Row Down" org-metadown (org-at-table-p)]
18907 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18908 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18909 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18910 "--"
18911 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18912 ("Rectangle"
18913 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18914 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18915 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18916 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18917 "--"
18918 ("Calculate"
18919 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18920 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18921 ["Edit Formulas" org-edit-special (org-at-table-p)]
18922 "--"
18923 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18924 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18925 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18926 "--"
18927 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18928 "--"
18929 ["Sum Column/Rectangle" org-table-sum
18930 (or (org-at-table-p) (org-region-active-p))]
18931 ["Which Column?" org-table-current-column (org-at-table-p)])
18932 ["Debug Formulas"
18933 org-table-toggle-formula-debugger
18934 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18935 ["Show Col/Row Numbers"
18936 org-table-toggle-coordinate-overlays
18937 :style toggle
18938 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18939 "--"
18940 ["Create" org-table-create (and (not (org-at-table-p))
18941 org-enable-table-editor)]
18942 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18943 ["Import from File" org-table-import (not (org-at-table-p))]
18944 ["Export to File" org-table-export (org-at-table-p)]
18945 "--"
18946 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18948 (easy-menu-define org-org-menu org-mode-map "Org menu"
18949 '("Org"
18950 ("Show/Hide"
18951 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18952 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18953 ["Sparse Tree..." org-sparse-tree t]
18954 ["Reveal Context" org-reveal t]
18955 ["Show All" show-all t]
18956 "--"
18957 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18958 "--"
18959 ["New Heading" org-insert-heading t]
18960 ("Navigate Headings"
18961 ["Up" outline-up-heading t]
18962 ["Next" outline-next-visible-heading t]
18963 ["Previous" outline-previous-visible-heading t]
18964 ["Next Same Level" outline-forward-same-level t]
18965 ["Previous Same Level" outline-backward-same-level t]
18966 "--"
18967 ["Jump" org-goto t])
18968 ("Edit Structure"
18969 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18970 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18971 "--"
18972 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18973 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18974 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18975 "--"
18976 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18977 "--"
18978 ["Copy visible text" org-copy-visible t]
18979 "--"
18980 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18981 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18982 ["Demote Heading" org-metaright (not (org-at-table-p))]
18983 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18984 "--"
18985 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18986 "--"
18987 ["Convert to odd levels" org-convert-to-odd-levels t]
18988 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18989 ("Editing"
18990 ["Emphasis..." org-emphasize t]
18991 ["Edit Source Example" org-edit-special t]
18992 "--"
18993 ["Footnote new/jump" org-footnote-action t]
18994 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18995 ("Archive"
18996 ["Archive (default method)" org-archive-subtree-default t]
18997 "--"
18998 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18999 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19000 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19002 "--"
19003 ("Hyperlinks"
19004 ["Store Link (Global)" org-store-link t]
19005 ["Find existing link to here" org-occur-link-in-agenda-files t]
19006 ["Insert Link" org-insert-link t]
19007 ["Follow Link" org-open-at-point t]
19008 "--"
19009 ["Next link" org-next-link t]
19010 ["Previous link" org-previous-link t]
19011 "--"
19012 ["Descriptive Links"
19013 org-toggle-link-display
19014 :style radio
19015 :selected org-descriptive-links
19017 ["Literal Links"
19018 org-toggle-link-display
19019 :style radio
19020 :selected (not org-descriptive-links)])
19021 "--"
19022 ("TODO Lists"
19023 ["TODO/DONE/-" org-todo t]
19024 ("Select keyword"
19025 ["Next keyword" org-shiftright (org-at-heading-p)]
19026 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19027 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19028 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19029 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19030 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19031 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19032 "--"
19033 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19034 :selected org-enforce-todo-dependencies :style toggle :active t]
19035 "Settings for tree at point"
19036 ["Do Children sequentially" org-toggle-ordered-property :style radio
19037 :selected (org-entry-get nil "ORDERED")
19038 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19039 ["Do Children parallel" org-toggle-ordered-property :style radio
19040 :selected (not (org-entry-get nil "ORDERED"))
19041 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19042 "--"
19043 ["Set Priority" org-priority t]
19044 ["Priority Up" org-shiftup t]
19045 ["Priority Down" org-shiftdown t]
19046 "--"
19047 ["Get news from all feeds" org-feed-update-all t]
19048 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19049 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19050 ("TAGS and Properties"
19051 ["Set Tags" org-set-tags-command t]
19052 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19053 "--"
19054 ["Set property" org-set-property t]
19055 ["Column view of properties" org-columns t]
19056 ["Insert Column View DBlock" org-insert-columns-dblock t])
19057 ("Dates and Scheduling"
19058 ["Timestamp" org-time-stamp t]
19059 ["Timestamp (inactive)" org-time-stamp-inactive t]
19060 ("Change Date"
19061 ["1 Day Later" org-shiftright t]
19062 ["1 Day Earlier" org-shiftleft t]
19063 ["1 ... Later" org-shiftup t]
19064 ["1 ... Earlier" org-shiftdown t])
19065 ["Compute Time Range" org-evaluate-time-range t]
19066 ["Schedule Item" org-schedule t]
19067 ["Deadline" org-deadline t]
19068 "--"
19069 ["Custom time format" org-toggle-time-stamp-overlays
19070 :style radio :selected org-display-custom-times]
19071 "--"
19072 ["Goto Calendar" org-goto-calendar t]
19073 ["Date from Calendar" org-date-from-calendar t]
19074 "--"
19075 ["Start/Restart Timer" org-timer-start t]
19076 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19077 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19078 ["Insert Timer String" org-timer t]
19079 ["Insert Timer Item" org-timer-item t])
19080 ("Logging work"
19081 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19082 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19083 ["Clock out" org-clock-out t]
19084 ["Clock cancel" org-clock-cancel t]
19085 "--"
19086 ["Mark as default task" org-clock-mark-default-task t]
19087 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19088 ["Goto running clock" org-clock-goto t]
19089 "--"
19090 ["Display times" org-clock-display t]
19091 ["Create clock table" org-clock-report t]
19092 "--"
19093 ["Record DONE time"
19094 (progn (setq org-log-done (not org-log-done))
19095 (message "Switching to %s will %s record a timestamp"
19096 (car org-done-keywords)
19097 (if org-log-done "automatically" "not")))
19098 :style toggle :selected org-log-done])
19099 "--"
19100 ["Agenda Command..." org-agenda t]
19101 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19102 ("File List for Agenda")
19103 ("Special views current file"
19104 ["TODO Tree" org-show-todo-tree t]
19105 ["Check Deadlines" org-check-deadlines t]
19106 ["Timeline" org-timeline t]
19107 ["Tags/Property tree" org-match-sparse-tree t])
19108 "--"
19109 ["Export/Publish..." org-export t]
19110 ("LaTeX"
19111 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19112 :selected org-cdlatex-mode]
19113 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19114 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19115 ["Modify math symbol" org-cdlatex-math-modify
19116 (org-inside-LaTeX-fragment-p)]
19117 ["Insert citation" org-reftex-citation t]
19118 "--"
19119 ["Template for BEAMER" (progn (require 'org-beamer)
19120 (org-insert-beamer-options-template)) t])
19121 "--"
19122 ("MobileOrg"
19123 ["Push Files and Views" org-mobile-push t]
19124 ["Get Captured and Flagged" org-mobile-pull t]
19125 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19126 "--"
19127 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19128 "--"
19129 ("Documentation"
19130 ["Show Version" org-version t]
19131 ["Info Documentation" org-info t])
19132 ("Customize"
19133 ["Browse Org Group" org-customize t]
19134 "--"
19135 ["Expand This Menu" org-create-customize-menu
19136 (fboundp 'customize-menu-create)])
19137 ["Send bug report" org-submit-bug-report t]
19138 "--"
19139 ("Refresh/Reload"
19140 ["Refresh setup current buffer" org-mode-restart t]
19141 ["Reload Org (after update)" org-reload t]
19142 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19145 (defun org-info (&optional node)
19146 "Read documentation for Org-mode in the info system.
19147 With optional NODE, go directly to that node."
19148 (interactive)
19149 (info (format "(org)%s" (or node ""))))
19151 ;;;###autoload
19152 (defun org-submit-bug-report ()
19153 "Submit a bug report on Org-mode via mail.
19155 Don't hesitate to report any problems or inaccurate documentation.
19157 If you don't have setup sending mail from (X)Emacs, please copy the
19158 output buffer into your mail program, as it gives us important
19159 information about your Org-mode version and configuration."
19160 (interactive)
19161 (require 'reporter)
19162 (org-load-modules-maybe)
19163 (org-require-autoloaded-modules)
19164 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19165 (reporter-submit-bug-report
19166 "emacs-orgmode@gnu.org"
19167 (org-version)
19168 (let (list)
19169 (save-window-excursion
19170 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19171 (delete-other-windows)
19172 (erase-buffer)
19173 (insert "You are about to submit a bug report to the Org-mode mailing list.
19175 We would like to add your full Org-mode and Outline configuration to the
19176 bug report. This greatly simplifies the work of the maintainer and
19177 other experts on the mailing list.
19179 HOWEVER, some variables you have customized may contain private
19180 information. The names of customers, colleagues, or friends, might
19181 appear in the form of file names, tags, todo states, or search strings.
19182 If you answer yes to the prompt, you might want to check and remove
19183 such private information before sending the email.")
19184 (add-text-properties (point-min) (point-max) '(face org-warning))
19185 (when (yes-or-no-p "Include your Org-mode configuration ")
19186 (mapatoms
19187 (lambda (v)
19188 (and (boundp v)
19189 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19190 (or (and (symbol-value v)
19191 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19192 (and
19193 (get v 'custom-type) (get v 'standard-value)
19194 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19195 (push v list)))))
19196 (kill-buffer (get-buffer "*Warn about privacy*"))
19197 list))
19198 nil nil
19199 "Remember to cover the basics, that is, what you expected to happen and
19200 what in fact did happen. You don't know how to make a good report? See
19202 http://orgmode.org/manual/Feedback.html#Feedback
19204 Your bug report will be posted to the Org-mode mailing list.
19205 ------------------------------------------------------------------------")
19206 (save-excursion
19207 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19208 (replace-match "\\1Bug: \\3 [\\2]")))))
19211 (defun org-install-agenda-files-menu ()
19212 (let ((bl (buffer-list)))
19213 (save-excursion
19214 (while bl
19215 (set-buffer (pop bl))
19216 (if (eq major-mode 'org-mode) (setq bl nil)))
19217 (when (eq major-mode 'org-mode)
19218 (easy-menu-change
19219 '("Org") "File List for Agenda"
19220 (append
19221 (list
19222 ["Edit File List" (org-edit-agenda-file-list) t]
19223 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19224 ["Remove Current File from List" org-remove-file t]
19225 ["Cycle through agenda files" org-cycle-agenda-files t]
19226 ["Occur in all agenda files" org-occur-in-agenda-files t]
19227 "--")
19228 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19230 ;;;; Documentation
19232 ;;;###autoload
19233 (defun org-require-autoloaded-modules ()
19234 (interactive)
19235 (mapc 'require
19236 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19237 org-docbook org-exp org-html org-icalendar
19238 org-id org-latex
19239 org-publish org-remember org-table
19240 org-timer org-xoxo)))
19242 ;;;###autoload
19243 (defun org-reload (&optional uncompiled)
19244 "Reload all org lisp files.
19245 With prefix arg UNCOMPILED, load the uncompiled versions."
19246 (interactive "P")
19247 (require 'find-func)
19248 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19249 (dir-org (file-name-directory (org-find-library-name "org")))
19250 (dir-org-contrib (ignore-errors
19251 (file-name-directory
19252 (org-find-library-name "org-contribdir"))))
19253 (babel-files
19254 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19255 (append (list nil "comint" "eval" "exp" "keys"
19256 "lob" "ref" "table" "tangle")
19257 (delq nil
19258 (mapcar
19259 (lambda (lang)
19260 (when (cdr lang) (symbol-name (car lang))))
19261 org-babel-load-languages)))))
19262 (files
19263 (append (directory-files dir-org t file-re)
19264 babel-files
19265 (and dir-org-contrib
19266 (directory-files dir-org-contrib t file-re))))
19267 (remove-re (concat (if (featurep 'xemacs)
19268 "org-colview" "org-colview-xemacs")
19269 "\\'")))
19270 (setq files (mapcar 'file-name-sans-extension files))
19271 (setq files (mapcar
19272 (lambda (x) (if (string-match remove-re x) nil x))
19273 files))
19274 (setq files (delq nil files))
19275 (mapc
19276 (lambda (f)
19277 (when (featurep (intern (file-name-nondirectory f)))
19278 (if (and (not uncompiled)
19279 (file-exists-p (concat f ".elc")))
19280 (load (concat f ".elc") nil nil t)
19281 (load (concat f ".el") nil nil t))))
19282 files))
19283 (org-version))
19285 ;;;###autoload
19286 (defun org-customize ()
19287 "Call the customize function with org as argument."
19288 (interactive)
19289 (org-load-modules-maybe)
19290 (org-require-autoloaded-modules)
19291 (customize-browse 'org))
19293 (defun org-create-customize-menu ()
19294 "Create a full customization menu for Org-mode, insert it into the menu."
19295 (interactive)
19296 (org-load-modules-maybe)
19297 (org-require-autoloaded-modules)
19298 (if (fboundp 'customize-menu-create)
19299 (progn
19300 (easy-menu-change
19301 '("Org") "Customize"
19302 `(["Browse Org group" org-customize t]
19303 "--"
19304 ,(customize-menu-create 'org)
19305 ["Set" Custom-set t]
19306 ["Save" Custom-save t]
19307 ["Reset to Current" Custom-reset-current t]
19308 ["Reset to Saved" Custom-reset-saved t]
19309 ["Reset to Standard Settings" Custom-reset-standard t]))
19310 (message "\"Org\"-menu now contains full customization menu"))
19311 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19313 ;;;; Miscellaneous stuff
19315 ;;; Generally useful functions
19317 (defun org-get-at-bol (property)
19318 "Get text property PROPERTY at beginning of line."
19319 (get-text-property (point-at-bol) property))
19321 (defun org-find-text-property-in-string (prop s)
19322 "Return the first non-nil value of property PROP in string S."
19323 (or (get-text-property 0 prop s)
19324 (get-text-property (or (next-single-property-change 0 prop s) 0)
19325 prop s)))
19327 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19328 "Display the given MESSAGE as a warning."
19329 (if (fboundp 'display-warning)
19330 (display-warning 'org message
19331 (if (featurep 'xemacs) 'warning :warning))
19332 (let ((buf (get-buffer-create "*Org warnings*")))
19333 (with-current-buffer buf
19334 (goto-char (point-max))
19335 (insert "Warning (Org): " message)
19336 (unless (bolp)
19337 (newline)))
19338 (display-buffer buf)
19339 (sit-for 0))))
19341 (defun org-eval (form)
19342 "Eval FORM and return result."
19343 (condition-case error
19344 (eval form)
19345 (error (format "%%![Error: %s]" error))))
19347 (defun org-in-clocktable-p ()
19348 "Check if the cursor is in a clocktable."
19349 (let ((pos (point)) start)
19350 (save-excursion
19351 (end-of-line 1)
19352 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19353 (setq start (match-beginning 0))
19354 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19355 (>= (match-end 0) pos)
19356 start))))
19358 (defun org-in-commented-line ()
19359 "Is point in a line starting with `#'?"
19360 (equal (char-after (point-at-bol)) ?#))
19362 (defun org-in-indented-comment-line ()
19363 "Is point in a line starting with `#' after some white space?"
19364 (save-excursion
19365 (save-match-data
19366 (goto-char (point-at-bol))
19367 (looking-at "[ \t]*#"))))
19369 (defun org-in-verbatim-emphasis ()
19370 (save-match-data
19371 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19373 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19374 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19375 (if (and marker (marker-buffer marker)
19376 (buffer-live-p (marker-buffer marker)))
19377 (progn
19378 (org-pop-to-buffer-same-window (marker-buffer marker))
19379 (if (or (> marker (point-max)) (< marker (point-min)))
19380 (widen))
19381 (goto-char marker)
19382 (org-show-context 'org-goto))
19383 (if bookmark
19384 (bookmark-jump bookmark)
19385 (error "Cannot find location"))))
19387 (defun org-quote-csv-field (s)
19388 "Quote field for inclusion in CSV material."
19389 (if (string-match "[\",]" s)
19390 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19393 (defun org-force-self-insert (N)
19394 "Needed to enforce self-insert under remapping."
19395 (interactive "p")
19396 (self-insert-command N))
19398 (defun org-string-width (s)
19399 "Compute width of string, ignoring invisible characters.
19400 This ignores character with invisibility property `org-link', and also
19401 characters with property `org-cwidth', because these will become invisible
19402 upon the next fontification round."
19403 (let (b l)
19404 (when (or (eq t buffer-invisibility-spec)
19405 (assq 'org-link buffer-invisibility-spec))
19406 (while (setq b (text-property-any 0 (length s)
19407 'invisible 'org-link s))
19408 (setq s (concat (substring s 0 b)
19409 (substring s (or (next-single-property-change
19410 b 'invisible s) (length s)))))))
19411 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19412 (setq s (concat (substring s 0 b)
19413 (substring s (or (next-single-property-change
19414 b 'org-cwidth s) (length s))))))
19415 (setq l (string-width s) b -1)
19416 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19417 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19420 (defun org-shorten-string (s maxlength)
19421 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19422 If the string is shorter or has length MAXLENGTH, just return the
19423 original string. If it is longer, the functions finds a space in the
19424 string, breaks this string off at that locations and adds three dots
19425 as ellipsis. Including the ellipsis, the string will not be longer
19426 than MAXLENGTH. If finding a good breaking point in the string does
19427 not work, the string is just chopped off in the middle of a word
19428 if necessary."
19429 (if (<= (length s) maxlength)
19431 (let* ((n (max (- maxlength 4) 1))
19432 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19433 (if (string-match re s)
19434 (concat (match-string 1 s) "...")
19435 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19437 (defun org-get-indentation (&optional line)
19438 "Get the indentation of the current line, interpreting tabs.
19439 When LINE is given, assume it represents a line and compute its indentation."
19440 (if line
19441 (if (string-match "^ *" (org-remove-tabs line))
19442 (match-end 0))
19443 (save-excursion
19444 (beginning-of-line 1)
19445 (skip-chars-forward " \t")
19446 (current-column))))
19448 (defun org-get-string-indentation (s)
19449 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19450 (let ((n -1) (i 0) (w tab-width) c)
19451 (catch 'exit
19452 (while (< (setq n (1+ n)) (length s))
19453 (setq c (aref s n))
19454 (cond ((= c ?\ ) (setq i (1+ i)))
19455 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19456 (t (throw 'exit t)))))
19459 (defun org-remove-tabs (s &optional width)
19460 "Replace tabulators in S with spaces.
19461 Assumes that s is a single line, starting in column 0."
19462 (setq width (or width tab-width))
19463 (while (string-match "\t" s)
19464 (setq s (replace-match
19465 (make-string
19466 (- (* width (/ (+ (match-beginning 0) width) width))
19467 (match-beginning 0)) ?\ )
19468 t t s)))
19471 (defun org-fix-indentation (line ind)
19472 "Fix indentation in LINE.
19473 IND is a cons cell with target and minimum indentation.
19474 If the current indentation in LINE is smaller than the minimum,
19475 leave it alone. If it is larger than ind, set it to the target."
19476 (let* ((l (org-remove-tabs line))
19477 (i (org-get-indentation l))
19478 (i1 (car ind)) (i2 (cdr ind)))
19479 (if (>= i i2) (setq l (substring line i2)))
19480 (if (> i1 0)
19481 (concat (make-string i1 ?\ ) l)
19482 l)))
19484 (defun org-remove-indentation (code &optional n)
19485 "Remove the maximum common indentation from the lines in CODE.
19486 N may optionally be the number of spaces to remove."
19487 (with-temp-buffer
19488 (insert code)
19489 (org-do-remove-indentation n)
19490 (buffer-string)))
19492 (defun org-do-remove-indentation (&optional n)
19493 "Remove the maximum common indentation from the buffer."
19494 (untabify (point-min) (point-max))
19495 (let ((min 10000) re)
19496 (if n
19497 (setq min n)
19498 (goto-char (point-min))
19499 (while (re-search-forward "^ *[^ \n]" nil t)
19500 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19501 (unless (or (= min 0) (= min 10000))
19502 (setq re (format "^ \\{%d\\}" min))
19503 (goto-char (point-min))
19504 (while (re-search-forward re nil t)
19505 (replace-match "")
19506 (end-of-line 1))
19507 min)))
19509 (defun org-fill-template (template alist)
19510 "Find each %key of ALIST in TEMPLATE and replace it."
19511 (let ((case-fold-search nil)
19512 entry key value)
19513 (setq alist (sort (copy-sequence alist)
19514 (lambda (a b) (< (length (car a)) (length (car b))))))
19515 (while (setq entry (pop alist))
19516 (setq template
19517 (replace-regexp-in-string
19518 (concat "%" (regexp-quote (car entry)))
19519 (cdr entry) template t t)))
19520 template))
19522 (defun org-base-buffer (buffer)
19523 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19524 (if (not buffer)
19525 buffer
19526 (or (buffer-base-buffer buffer)
19527 buffer)))
19529 (defun org-trim (s)
19530 "Remove whitespace at beginning and end of string."
19531 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19532 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19535 (defun org-wrap (string &optional width lines)
19536 "Wrap string to either a number of lines, or a width in characters.
19537 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19538 that costs. If there is a word longer than WIDTH, the text is actually
19539 wrapped to the length of that word.
19540 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19541 many lines, whatever width that takes.
19542 The return value is a list of lines, without newlines at the end."
19543 (let* ((words (org-split-string string "[ \t\n]+"))
19544 (maxword (apply 'max (mapcar 'org-string-width words)))
19545 w ll)
19546 (cond (width
19547 (org-do-wrap words (max maxword width)))
19548 (lines
19549 (setq w maxword)
19550 (setq ll (org-do-wrap words maxword))
19551 (if (<= (length ll) lines)
19553 (setq ll words)
19554 (while (> (length ll) lines)
19555 (setq w (1+ w))
19556 (setq ll (org-do-wrap words w)))
19557 ll))
19558 (t (error "Cannot wrap this")))))
19560 (defun org-do-wrap (words width)
19561 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19562 (let (lines line)
19563 (while words
19564 (setq line (pop words))
19565 (while (and words (< (+ (length line) (length (car words))) width))
19566 (setq line (concat line " " (pop words))))
19567 (setq lines (push line lines)))
19568 (nreverse lines)))
19570 (defun org-split-string (string &optional separators)
19571 "Splits STRING into substrings at SEPARATORS.
19572 No empty strings are returned if there are matches at the beginning
19573 and end of string."
19574 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19575 (start 0)
19576 notfirst
19577 (list nil))
19578 (while (and (string-match rexp string
19579 (if (and notfirst
19580 (= start (match-beginning 0))
19581 (< start (length string)))
19582 (1+ start) start))
19583 (< (match-beginning 0) (length string)))
19584 (setq notfirst t)
19585 (or (eq (match-beginning 0) 0)
19586 (and (eq (match-beginning 0) (match-end 0))
19587 (eq (match-beginning 0) start))
19588 (setq list
19589 (cons (substring string start (match-beginning 0))
19590 list)))
19591 (setq start (match-end 0)))
19592 (or (eq start (length string))
19593 (setq list
19594 (cons (substring string start)
19595 list)))
19596 (nreverse list)))
19598 (defun org-quote-vert (s)
19599 "Replace \"|\" with \"\\vert\"."
19600 (while (string-match "|" s)
19601 (setq s (replace-match "\\vert" t t s)))
19604 (defun org-uuidgen-p (s)
19605 "Is S an ID created by UUIDGEN?"
19606 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19608 (defun org-context ()
19609 "Return a list of contexts of the current cursor position.
19610 If several contexts apply, all are returned.
19611 Each context entry is a list with a symbol naming the context, and
19612 two positions indicating start and end of the context. Possible
19613 contexts are:
19615 :headline anywhere in a headline
19616 :headline-stars on the leading stars in a headline
19617 :todo-keyword on a TODO keyword (including DONE) in a headline
19618 :tags on the TAGS in a headline
19619 :priority on the priority cookie in a headline
19620 :item on the first line of a plain list item
19621 :item-bullet on the bullet/number of a plain list item
19622 :checkbox on the checkbox in a plain list item
19623 :table in an org-mode table
19624 :table-special on a special filed in a table
19625 :table-table in a table.el table
19626 :link on a hyperlink
19627 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19628 :target on a <<target>>
19629 :radio-target on a <<<radio-target>>>
19630 :latex-fragment on a LaTeX fragment
19631 :latex-preview on a LaTeX fragment with overlaid preview image
19633 This function expects the position to be visible because it uses font-lock
19634 faces as a help to recognize the following contexts: :table-special, :link,
19635 and :keyword."
19636 (let* ((f (get-text-property (point) 'face))
19637 (faces (if (listp f) f (list f)))
19638 (p (point)) clist o)
19639 ;; First the large context
19640 (cond
19641 ((org-at-heading-p t)
19642 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19643 (when (progn
19644 (beginning-of-line 1)
19645 (looking-at org-todo-line-tags-regexp))
19646 (push (org-point-in-group p 1 :headline-stars) clist)
19647 (push (org-point-in-group p 2 :todo-keyword) clist)
19648 (push (org-point-in-group p 4 :tags) clist))
19649 (goto-char p)
19650 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19651 (if (looking-at "\\[#[A-Z0-9]\\]")
19652 (push (org-point-in-group p 0 :priority) clist)))
19654 ((org-at-item-p)
19655 (push (org-point-in-group p 2 :item-bullet) clist)
19656 (push (list :item (point-at-bol)
19657 (save-excursion (org-end-of-item) (point)))
19658 clist)
19659 (and (org-at-item-checkbox-p)
19660 (push (org-point-in-group p 0 :checkbox) clist)))
19662 ((org-at-table-p)
19663 (push (list :table (org-table-begin) (org-table-end)) clist)
19664 (if (memq 'org-formula faces)
19665 (push (list :table-special
19666 (previous-single-property-change p 'face)
19667 (next-single-property-change p 'face)) clist)))
19668 ((org-at-table-p 'any)
19669 (push (list :table-table) clist)))
19670 (goto-char p)
19672 ;; Now the small context
19673 (cond
19674 ((org-at-timestamp-p)
19675 (push (org-point-in-group p 0 :timestamp) clist))
19676 ((memq 'org-link faces)
19677 (push (list :link
19678 (previous-single-property-change p 'face)
19679 (next-single-property-change p 'face)) clist))
19680 ((memq 'org-special-keyword faces)
19681 (push (list :keyword
19682 (previous-single-property-change p 'face)
19683 (next-single-property-change p 'face)) clist))
19684 ((org-at-target-p)
19685 (push (org-point-in-group p 0 :target) clist)
19686 (goto-char (1- (match-beginning 0)))
19687 (if (looking-at org-radio-target-regexp)
19688 (push (org-point-in-group p 0 :radio-target) clist))
19689 (goto-char p))
19690 ((setq o (car (delq nil
19691 (mapcar
19692 (lambda (x)
19693 (if (memq x org-latex-fragment-image-overlays) x))
19694 (overlays-at (point))))))
19695 (push (list :latex-fragment
19696 (overlay-start o) (overlay-end o)) clist)
19697 (push (list :latex-preview
19698 (overlay-start o) (overlay-end o)) clist))
19699 ((org-inside-LaTeX-fragment-p)
19700 ;; FIXME: positions wrong.
19701 (push (list :latex-fragment (point) (point)) clist)))
19703 (setq clist (nreverse (delq nil clist)))
19704 clist))
19706 ;; FIXME: Compare with at-regexp-p Do we need both?
19707 (defun org-in-regexp (re &optional nlines visually)
19708 "Check if point is inside a match of regexp.
19709 Normally only the current line is checked, but you can include NLINES extra
19710 lines both before and after point into the search.
19711 If VISUALLY is set, require that the cursor is not after the match but
19712 really on, so that the block visually is on the match."
19713 (catch 'exit
19714 (let ((pos (point))
19715 (eol (point-at-eol (+ 1 (or nlines 0))))
19716 (inc (if visually 1 0)))
19717 (save-excursion
19718 (beginning-of-line (- 1 (or nlines 0)))
19719 (while (re-search-forward re eol t)
19720 (if (and (<= (match-beginning 0) pos)
19721 (>= (+ inc (match-end 0)) pos))
19722 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19724 (defun org-at-regexp-p (regexp)
19725 "Is point inside a match of REGEXP in the current line?"
19726 (catch 'exit
19727 (save-excursion
19728 (let ((pos (point)) (end (point-at-eol)))
19729 (beginning-of-line 1)
19730 (while (re-search-forward regexp end t)
19731 (if (and (<= (match-beginning 0) pos)
19732 (>= (match-end 0) pos))
19733 (throw 'exit t)))
19734 nil))))
19736 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19737 "Non-nil when point is between matches of START-RE and END-RE.
19739 Also return a non-nil value when point is on one of the matches.
19741 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19742 buffer positions. Default values are the positions of headlines
19743 surrounding the point.
19745 The functions returns a cons cell whose car (resp. cdr) is the
19746 position before START-RE (resp. after END-RE)."
19747 (save-match-data
19748 (let ((pos (point))
19749 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19750 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19751 beg end)
19752 (save-excursion
19753 ;; Point is on a block when on START-RE or if START-RE can be
19754 ;; found before it...
19755 (and (or (org-at-regexp-p start-re)
19756 (re-search-backward start-re limit-up t))
19757 (setq beg (match-beginning 0))
19758 ;; ... and END-RE after it...
19759 (goto-char (match-end 0))
19760 (re-search-forward end-re limit-down t)
19761 (> (setq end (match-end 0)) pos)
19762 ;; ... without another START-RE in-between.
19763 (goto-char (match-beginning 0))
19764 (not (re-search-backward start-re (1+ beg) t))
19765 ;; Return value.
19766 (cons beg end))))))
19768 (defun org-in-block-p (names)
19769 "Non-nil when point belongs to a block whose name belongs to NAMES.
19771 NAMES is a list of strings containing names of blocks.
19773 Return first block name matched, or nil. Beware that in case of
19774 nested blocks, the returned name may not belong to the closest
19775 block from point."
19776 (save-match-data
19777 (catch 'exit
19778 (let ((case-fold-search t)
19779 (lim-up (save-excursion (outline-previous-heading)))
19780 (lim-down (save-excursion (outline-next-heading))))
19781 (mapc (lambda (name)
19782 (let ((n (regexp-quote name)))
19783 (when (org-between-regexps-p
19784 (concat "^[ \t]*#\\+begin_" n)
19785 (concat "^[ \t]*#\\+end_" n)
19786 lim-up lim-down)
19787 (throw 'exit n))))
19788 names))
19789 nil)))
19791 (defun org-occur-in-agenda-files (regexp &optional nlines)
19792 "Call `multi-occur' with buffers for all agenda files."
19793 (interactive "sOrg-files matching: \np")
19794 (let* ((files (org-agenda-files))
19795 (tnames (mapcar 'file-truename files))
19796 (extra org-agenda-text-search-extra-files)
19798 (when (eq (car extra) 'agenda-archives)
19799 (setq extra (cdr extra))
19800 (setq files (org-add-archive-files files)))
19801 (while (setq f (pop extra))
19802 (unless (member (file-truename f) tnames)
19803 (add-to-list 'files f 'append)
19804 (add-to-list 'tnames (file-truename f) 'append)))
19805 (multi-occur
19806 (mapcar (lambda (x)
19807 (with-current-buffer
19808 (or (get-file-buffer x) (find-file-noselect x))
19809 (widen)
19810 (current-buffer)))
19811 files)
19812 regexp)))
19814 (if (boundp 'occur-mode-find-occurrence-hook)
19815 ;; Emacs 23
19816 (add-hook 'occur-mode-find-occurrence-hook
19817 (lambda ()
19818 (when (eq major-mode 'org-mode)
19819 (org-reveal))))
19820 ;; Emacs 22
19821 (defadvice occur-mode-goto-occurrence
19822 (after org-occur-reveal activate)
19823 (and (eq major-mode 'org-mode) (org-reveal)))
19824 (defadvice occur-mode-goto-occurrence-other-window
19825 (after org-occur-reveal activate)
19826 (and (eq major-mode 'org-mode) (org-reveal)))
19827 (defadvice occur-mode-display-occurrence
19828 (after org-occur-reveal activate)
19829 (when (eq major-mode 'org-mode)
19830 (let ((pos (occur-mode-find-occurrence)))
19831 (with-current-buffer (marker-buffer pos)
19832 (save-excursion
19833 (goto-char pos)
19834 (org-reveal)))))))
19836 (defun org-occur-link-in-agenda-files ()
19837 "Create a link and search for it in the agendas.
19838 The link is not stored in `org-stored-links', it is just created
19839 for the search purpose."
19840 (interactive)
19841 (let ((link (condition-case nil
19842 (org-store-link nil)
19843 (error "Unable to create a link to here"))))
19844 (org-occur-in-agenda-files (regexp-quote link))))
19846 (defun org-uniquify (list)
19847 "Remove duplicate elements from LIST."
19848 (let (res)
19849 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19850 res))
19852 (defun org-delete-all (elts list)
19853 "Remove all elements in ELTS from LIST."
19854 (while elts
19855 (setq list (delete (pop elts) list)))
19856 list)
19858 (defun org-count (cl-item cl-seq)
19859 "Count the number of occurrences of ITEM in SEQ.
19860 Taken from `count' in cl-seq.el with all keyword arguments removed."
19861 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19862 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19863 (while (< cl-start cl-end)
19864 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19865 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19866 (setq cl-start (1+ cl-start)))
19867 cl-count))
19869 (defun org-remove-if (predicate seq)
19870 "Remove everything from SEQ that fulfills PREDICATE."
19871 (let (res e)
19872 (while seq
19873 (setq e (pop seq))
19874 (if (not (funcall predicate e)) (push e res)))
19875 (nreverse res)))
19877 (defun org-remove-if-not (predicate seq)
19878 "Remove everything from SEQ that does not fulfill PREDICATE."
19879 (let (res e)
19880 (while seq
19881 (setq e (pop seq))
19882 (if (funcall predicate e) (push e res)))
19883 (nreverse res)))
19885 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19886 "Reduce two-argument FUNCTION across SEQ.
19887 Taken from `reduce' in cl-seq.el with all keyword arguments but
19888 \":initial-value\" removed."
19889 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19890 (cadr (memq :initial-value cl-keys)))
19891 (cl-seq (pop cl-seq))
19892 (t (funcall cl-func)))))
19893 (while cl-seq
19894 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19895 cl-accum))
19897 (defun org-back-over-empty-lines ()
19898 "Move backwards over whitespace, to the beginning of the first empty line.
19899 Returns the number of empty lines passed."
19900 (let ((pos (point)))
19901 (if (cdr (assoc 'heading org-blank-before-new-entry))
19902 (skip-chars-backward " \t\n\r")
19903 (unless (eobp)
19904 (forward-line -1)))
19905 (beginning-of-line 2)
19906 (goto-char (min (point) pos))
19907 (count-lines (point) pos)))
19909 (defun org-skip-whitespace ()
19910 (skip-chars-forward " \t\n\r"))
19912 (defun org-point-in-group (point group &optional context)
19913 "Check if POINT is in match-group GROUP.
19914 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19915 match. If the match group does not exist or point is not inside it,
19916 return nil."
19917 (and (match-beginning group)
19918 (>= point (match-beginning group))
19919 (<= point (match-end group))
19920 (if context
19921 (list context (match-beginning group) (match-end group))
19922 t)))
19924 (defun org-switch-to-buffer-other-window (&rest args)
19925 "Switch to buffer in a second window on the current frame.
19926 In particular, do not allow pop-up frames.
19927 Returns the newly created buffer."
19928 (let (pop-up-frames special-display-buffer-names special-display-regexps
19929 special-display-function)
19930 (apply 'switch-to-buffer-other-window args)))
19932 (defun org-combine-plists (&rest plists)
19933 "Create a single property list from all plists in PLISTS.
19934 The process starts by copying the first list, and then setting properties
19935 from the other lists. Settings in the last list are the most significant
19936 ones and overrule settings in the other lists."
19937 (let ((rtn (copy-sequence (pop plists)))
19938 p v ls)
19939 (while plists
19940 (setq ls (pop plists))
19941 (while ls
19942 (setq p (pop ls) v (pop ls))
19943 (setq rtn (plist-put rtn p v))))
19944 rtn))
19946 (defun org-move-line-down (arg)
19947 "Move the current line down. With prefix argument, move it past ARG lines."
19948 (interactive "p")
19949 (let ((col (current-column))
19950 beg end pos)
19951 (beginning-of-line 1) (setq beg (point))
19952 (beginning-of-line 2) (setq end (point))
19953 (beginning-of-line (+ 1 arg))
19954 (setq pos (move-marker (make-marker) (point)))
19955 (insert (delete-and-extract-region beg end))
19956 (goto-char pos)
19957 (org-move-to-column col)))
19959 (defun org-move-line-up (arg)
19960 "Move the current line up. With prefix argument, move it past ARG lines."
19961 (interactive "p")
19962 (let ((col (current-column))
19963 beg end pos)
19964 (beginning-of-line 1) (setq beg (point))
19965 (beginning-of-line 2) (setq end (point))
19966 (beginning-of-line (- arg))
19967 (setq pos (move-marker (make-marker) (point)))
19968 (insert (delete-and-extract-region beg end))
19969 (goto-char pos)
19970 (org-move-to-column col)))
19972 (defun org-replace-escapes (string table)
19973 "Replace %-escapes in STRING with values in TABLE.
19974 TABLE is an association list with keys like \"%a\" and string values.
19975 The sequences in STRING may contain normal field width and padding information,
19976 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19977 so values can contain further %-escapes if they are define later in TABLE."
19978 (let ((tbl (copy-alist table))
19979 (case-fold-search nil)
19980 (pchg 0)
19981 e re rpl)
19982 (while (setq e (pop tbl))
19983 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19984 (when (and (cdr e) (string-match re (cdr e)))
19985 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19986 (safe "SREF"))
19987 (add-text-properties 0 3 (list 'sref sref) safe)
19988 (setcdr e (replace-match safe t t (cdr e)))))
19989 (while (string-match re string)
19990 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19991 (cdr e)))
19992 (setq string (replace-match rpl t t string))))
19993 (while (setq pchg (next-property-change pchg string))
19994 (let ((sref (get-text-property pchg 'sref string)))
19995 (when (and sref (string-match "SREF" string pchg))
19996 (setq string (replace-match sref t t string)))))
19997 string))
19999 (defun org-sublist (list start end)
20000 "Return a section of LIST, from START to END.
20001 Counting starts at 1."
20002 (let (rtn (c start))
20003 (setq list (nthcdr (1- start) list))
20004 (while (and list (<= c end))
20005 (push (pop list) rtn)
20006 (setq c (1+ c)))
20007 (nreverse rtn)))
20009 (defun org-find-base-buffer-visiting (file)
20010 "Like `find-buffer-visiting' but always return the base buffer and
20011 not an indirect buffer."
20012 (let ((buf (or (get-file-buffer file)
20013 (find-buffer-visiting file))))
20014 (if buf
20015 (or (buffer-base-buffer buf) buf)
20016 nil)))
20018 (defun org-image-file-name-regexp (&optional extensions)
20019 "Return regexp matching the file names of images.
20020 If EXTENSIONS is given, only match these."
20021 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20022 (image-file-name-regexp)
20023 (let ((image-file-name-extensions
20024 (or extensions
20025 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20026 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20027 (concat "\\."
20028 (regexp-opt (nconc (mapcar 'upcase
20029 image-file-name-extensions)
20030 image-file-name-extensions)
20032 "\\'"))))
20034 (defun org-file-image-p (file &optional extensions)
20035 "Return non-nil if FILE is an image."
20036 (save-match-data
20037 (string-match (org-image-file-name-regexp extensions) file)))
20039 (defun org-get-cursor-date ()
20040 "Return the date at cursor in as a time.
20041 This works in the calendar and in the agenda, anywhere else it just
20042 returns the current time."
20043 (let (date day defd)
20044 (cond
20045 ((eq major-mode 'calendar-mode)
20046 (setq date (calendar-cursor-to-date)
20047 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20048 ((eq major-mode 'org-agenda-mode)
20049 (setq day (get-text-property (point) 'day))
20050 (if day
20051 (setq date (calendar-gregorian-from-absolute day)
20052 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20053 (nth 2 date))))))
20054 (or defd (current-time))))
20056 (defvar org-agenda-action-marker (make-marker)
20057 "Marker pointing to the entry for the next agenda action.")
20059 (defun org-mark-entry-for-agenda-action ()
20060 "Mark the current entry as target of an agenda action.
20061 Agenda actions are actions executed from the agenda with the key `k',
20062 which make use of the date at the cursor."
20063 (interactive)
20064 (move-marker org-agenda-action-marker
20065 (save-excursion (org-back-to-heading t) (point))
20066 (current-buffer))
20067 (message
20068 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20070 (defun org-mark-subtree ()
20071 "Mark the current subtree.
20072 This puts point at the start of the current subtree, and mark at the end.
20074 If point is in an inline task, mark that task instead."
20075 (interactive)
20076 (let ((inline-task-p
20077 (and (featurep 'org-inlinetask)
20078 (org-inlinetask-in-task-p)))
20079 (beg))
20080 ;; Get beginning of subtree
20081 (cond
20082 (inline-task-p (org-inlinetask-goto-beginning))
20083 ((org-at-heading-p) (beginning-of-line))
20084 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20085 (setq beg (point))
20086 ;; Get end of it
20087 (if inline-task-p
20088 (org-inlinetask-goto-end)
20089 (org-end-of-subtree))
20090 ;; Mark zone
20091 (push-mark (point) nil t)
20092 (goto-char beg)))
20094 ;;; Paragraph filling stuff.
20095 ;; We want this to be just right, so use the full arsenal.
20097 (defun org-indent-line-function ()
20098 "Indent line depending on context."
20099 (interactive)
20100 (let* ((pos (point))
20101 (itemp (org-at-item-p))
20102 (case-fold-search t)
20103 (org-drawer-regexp (or org-drawer-regexp "\000"))
20104 (inline-task-p (and (featurep 'org-inlinetask)
20105 (org-inlinetask-in-task-p)))
20106 (inline-re (and inline-task-p
20107 (org-inlinetask-outline-regexp)))
20108 column)
20109 (beginning-of-line 1)
20110 (cond
20111 ;; Comments
20112 ((looking-at "# ") (setq column 0))
20113 ;; Headings
20114 ((looking-at org-outline-regexp) (setq column 0))
20115 ;; Included files
20116 ((looking-at "#\\+include:") (setq column 0))
20117 ;; Footnote definition
20118 ((looking-at org-footnote-definition-re) (setq column 0))
20119 ;; Literal examples
20120 ((looking-at "[ \t]*:\\( \\|$\\)")
20121 (setq column (org-get-indentation))) ; do nothing
20122 ;; Lists
20123 ((ignore-errors (goto-char (org-in-item-p)))
20124 (setq column (if itemp
20125 (org-get-indentation)
20126 (org-list-item-body-column (point))))
20127 (goto-char pos))
20128 ;; Drawers
20129 ((and (looking-at "[ \t]*:END:")
20130 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20131 (save-excursion
20132 (goto-char (1- (match-beginning 1)))
20133 (setq column (current-column))))
20134 ;; Special blocks
20135 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20136 (save-excursion
20137 (re-search-backward
20138 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20139 (setq column (org-get-indentation (match-string 0))))
20140 ((and (not (looking-at "[ \t]*#\\+begin_"))
20141 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20142 (save-excursion
20143 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20144 (setq column
20145 (cond ((equal (downcase (match-string 1)) "src")
20146 ;; src blocks: let `org-edit-src-exit' handle them
20147 (org-get-indentation))
20148 ((equal (downcase (match-string 1)) "example")
20149 (max (org-get-indentation)
20150 (org-get-indentation (match-string 0))))
20152 (org-get-indentation (match-string 0))))))
20153 ;; This line has nothing special, look at the previous relevant
20154 ;; line to compute indentation
20156 (beginning-of-line 0)
20157 (while (and (not (bobp))
20158 (not (looking-at org-drawer-regexp))
20159 ;; When point started in an inline task, do not move
20160 ;; above task starting line.
20161 (not (and inline-task-p (looking-at inline-re)))
20162 ;; Skip drawers, blocks, empty lines, verbatim,
20163 ;; comments, tables, footnotes definitions, lists,
20164 ;; inline tasks.
20165 (or (and (looking-at "[ \t]*:END:")
20166 (re-search-backward org-drawer-regexp nil t))
20167 (and (looking-at "[ \t]*#\\+end_")
20168 (re-search-backward "[ \t]*#\\+begin_"nil t))
20169 (looking-at "[ \t]*[\n:#|]")
20170 (looking-at org-footnote-definition-re)
20171 (and (ignore-errors (goto-char (org-in-item-p)))
20172 (goto-char
20173 (org-list-get-top-point (org-list-struct))))
20174 (and (not inline-task-p)
20175 (featurep 'org-inlinetask)
20176 (org-inlinetask-in-task-p)
20177 (or (org-inlinetask-goto-beginning) t))))
20178 (beginning-of-line 0))
20179 (cond
20180 ;; There was an heading above.
20181 ((looking-at "\\*+[ \t]+")
20182 (if (not org-adapt-indentation)
20183 (setq column 0)
20184 (goto-char (match-end 0))
20185 (setq column (current-column))))
20186 ;; A drawer had started and is unfinished
20187 ((looking-at org-drawer-regexp)
20188 (goto-char (1- (match-beginning 1)))
20189 (setq column (current-column)))
20190 ;; Else, nothing noticeable found: get indentation and go on.
20191 (t (setq column (org-get-indentation))))))
20192 ;; Now apply indentation and move cursor accordingly
20193 (goto-char pos)
20194 (if (<= (current-column) (current-indentation))
20195 (org-indent-line-to column)
20196 (save-excursion (org-indent-line-to column)))
20197 ;; Special polishing for properties, see `org-property-format'
20198 (setq column (current-column))
20199 (beginning-of-line 1)
20200 (if (looking-at
20201 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20202 (replace-match (concat (match-string 1)
20203 (format org-property-format
20204 (match-string 2) (match-string 3)))
20205 t t))
20206 (org-move-to-column column)))
20208 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20209 "Variable to store copy of `adaptive-fill-regexp'.
20210 Since `adaptive-fill-regexp' is set to never match, we need to
20211 store a backup of its value before entering `org-mode' so that
20212 the functionality can be provided as a fall-back.")
20214 (defun org-set-autofill-regexps ()
20215 (interactive)
20216 ;; In the paragraph separator we include headlines, because filling
20217 ;; text in a line directly attached to a headline would otherwise
20218 ;; fill the headline as well.
20219 (org-set-local 'comment-start-skip "^#+[ \t]*")
20220 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20221 ;; The paragraph starter includes hand-formatted lists.
20222 (org-set-local
20223 'paragraph-start
20224 (concat
20225 "\f" "\\|"
20226 "[ ]*$" "\\|"
20227 org-outline-regexp "\\|"
20228 "[ \t]*#" "\\|"
20229 (org-item-re) "\\|"
20230 "[ \t]*[:|]" "\\|"
20231 "\\$\\$" "\\|"
20232 "\\\\\\(begin\\|end\\|[][]\\)"))
20233 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20234 ;; But only if the user has not turned off tables or fixed-width regions
20235 (org-set-local
20236 'auto-fill-inhibit-regexp
20237 (concat org-outline-regexp
20238 "\\|#\\+"
20239 "\\|[ \t]*" org-keyword-time-regexp
20240 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20241 (concat
20242 "\\|[ \t]*["
20243 (if org-enable-table-editor "|" "")
20244 (if org-enable-fixed-width-editor ":" "")
20245 "]"))))
20246 ;; We use our own fill-paragraph function, to make sure that tables
20247 ;; and fixed-width regions are not wrapped. That function will pass
20248 ;; through to `fill-paragraph' when appropriate.
20249 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20250 ;; Prevent auto-fill from inserting unwanted new items.
20251 (if (boundp 'fill-nobreak-predicate)
20252 (org-set-local 'fill-nobreak-predicate
20253 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20254 fill-nobreak-predicate
20255 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20256 ;; Adaptive filling: To get full control, first make sure that
20257 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20258 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20259 (org-set-local 'org-adaptive-fill-regexp-backup
20260 adaptive-fill-regexp))
20261 (org-set-local 'adaptive-fill-regexp "\000")
20262 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20263 (org-set-local 'adaptive-fill-function
20264 'org-adaptive-fill-function)
20265 (org-set-local
20266 'align-mode-rules-list
20267 '((org-in-buffer-settings
20268 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20269 (modes . '(org-mode))))))
20271 (defun org-fill-item-nobreak-p ()
20272 "Non-nil when a line break at point would insert a new item."
20273 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20275 (defun org-fill-paragraph (&optional justify)
20276 "Re-align a table, pass through to fill-paragraph if no table."
20277 (let ((table-p (org-at-table-p))
20278 (table.el-p (org-at-table.el-p))
20279 (itemp (org-in-item-p)))
20280 (cond ((and (equal (char-after (point-at-bol)) ?*)
20281 (save-excursion (goto-char (point-at-bol))
20282 (looking-at org-outline-regexp)))
20283 t) ; skip headlines
20284 (table.el-p t) ; skip table.el tables
20285 (table-p (org-table-align) t) ; align Org tables
20286 (itemp ; align text in items
20287 (let* ((struct (save-excursion (goto-char itemp)
20288 (org-list-struct)))
20289 (parents (org-list-parents-alist struct))
20290 (children (org-list-get-children itemp struct parents))
20291 beg end prev next prefix)
20292 ;; Determine in which part of item point is: before
20293 ;; first child, after last child, between two
20294 ;; sub-lists, or simply in item if there's no child.
20295 (cond
20296 ((not children)
20297 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20298 beg itemp
20299 end (org-list-get-item-end itemp struct)))
20300 ((< (point) (setq next (car children)))
20301 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20302 beg itemp
20303 end next))
20304 ((> (point) (setq prev (car (last children))))
20305 (setq beg (org-list-get-item-end prev struct)
20306 end (org-list-get-item-end itemp struct)
20307 prefix (save-excursion
20308 (goto-char beg)
20309 (skip-chars-forward " \t")
20310 (make-string (current-column) ?\ ))))
20311 (t (catch 'exit
20312 (while (setq next (pop children))
20313 (if (> (point) next)
20314 (setq prev next)
20315 (setq beg (org-list-get-item-end prev struct)
20316 end next
20317 prefix (save-excursion
20318 (goto-char beg)
20319 (skip-chars-forward " \t")
20320 (make-string (current-column) ?\ )))
20321 (throw 'exit nil))))))
20322 ;; Use `fill-paragraph' with buffer narrowed to item
20323 ;; without any child, and with our computed PREFIX.
20324 (flet ((fill-context-prefix (from to &optional flr) prefix))
20325 (save-restriction
20326 (narrow-to-region beg end)
20327 (save-excursion (fill-paragraph justify)))) t))
20328 ;; Special case where point is not in a list but is on
20329 ;; a paragraph adjacent to a list: make sure this paragraph
20330 ;; doesn't get merged with the end of the list by narrowing
20331 ;; buffer first.
20332 ((save-excursion (forward-paragraph -1)
20333 (setq itemp (org-in-item-p)))
20334 (let ((struct (save-excursion (goto-char itemp)
20335 (org-list-struct))))
20336 (save-restriction
20337 (narrow-to-region (org-list-get-bottom-point struct)
20338 (save-excursion (forward-paragraph 1)
20339 (point)))
20340 (fill-paragraph justify) t)))
20341 ;; Else simply call `fill-paragraph'.
20342 (t nil))))
20344 ;; For reference, this is the default value of adaptive-fill-regexp
20345 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20347 (defun org-adaptive-fill-function ()
20348 "Return a fill prefix for org-mode files."
20349 (let (itemp)
20350 (save-excursion
20351 (cond
20352 ;; Comment line
20353 ((looking-at "#[ \t]+")
20354 (match-string-no-properties 0))
20355 ;; Plain list item
20356 ((org-at-item-p)
20357 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20358 ;; Point is in a list after `backward-paragraph': original
20359 ;; point wasn't in the list, or filling would have been taken
20360 ;; care of by `org-auto-fill-function', but the list and the
20361 ;; real paragraph are not separated by a blank line. Thus, move
20362 ;; point after the list to go back to real paragraph and
20363 ;; determine fill-prefix.
20364 ((setq itemp (org-in-item-p))
20365 (goto-char itemp)
20366 (let* ((struct (org-list-struct))
20367 (bottom (org-list-get-bottom-point struct)))
20368 (goto-char bottom)
20369 (make-string (org-get-indentation) ?\ )))
20370 ;; Other text
20371 ((looking-at org-adaptive-fill-regexp-backup)
20372 (match-string-no-properties 0))))))
20374 (defun org-auto-fill-function ()
20375 "Auto-fill function."
20376 (let (itemp prefix)
20377 ;; When in a list, compute an appropriate fill-prefix and make
20378 ;; sure it will be used by `do-auto-fill'.
20379 (if (setq itemp (org-in-item-p))
20380 (progn
20381 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20382 (flet ((fill-context-prefix (from to &optional flr) prefix))
20383 (do-auto-fill)))
20384 ;; Else just use `do-auto-fill'.
20385 (do-auto-fill))))
20387 ;;; Other stuff.
20389 (defun org-toggle-fixed-width-section (arg)
20390 "Toggle the fixed-width export.
20391 If there is no active region, the QUOTE keyword at the current headline is
20392 inserted or removed. When present, it causes the text between this headline
20393 and the next to be exported as fixed-width text, and unmodified.
20394 If there is an active region, this command adds or removes a colon as the
20395 first character of this line. If the first character of a line is a colon,
20396 this line is also exported in fixed-width font."
20397 (interactive "P")
20398 (let* ((cc 0)
20399 (regionp (org-region-active-p))
20400 (beg (if regionp (region-beginning) (point)))
20401 (end (if regionp (region-end)))
20402 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20403 (case-fold-search nil)
20404 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20405 off)
20406 (if regionp
20407 (save-excursion
20408 (goto-char beg)
20409 (setq cc (current-column))
20410 (beginning-of-line 1)
20411 (setq off (looking-at re))
20412 (while (> nlines 0)
20413 (setq nlines (1- nlines))
20414 (beginning-of-line 1)
20415 (cond
20416 (arg
20417 (org-move-to-column cc t)
20418 (insert ": \n")
20419 (forward-line -1))
20420 ((and off (looking-at re))
20421 (replace-match "" t t nil 1))
20422 ((not off) (org-move-to-column cc t) (insert ": ")))
20423 (forward-line 1)))
20424 (save-excursion
20425 (org-back-to-heading)
20426 (cond
20427 ((looking-at (format org-heading-keyword-regexp-format
20428 org-quote-string))
20429 (goto-char (match-end 1))
20430 (looking-at (concat " +" org-quote-string))
20431 (replace-match "" t t)
20432 (when (eolp) (insert " ")))
20433 ((looking-at org-outline-regexp)
20434 (goto-char (match-end 0))
20435 (insert org-quote-string " ")))))))
20437 (defun org-reftex-citation ()
20438 "Use reftex-citation to insert a citation into the buffer.
20439 This looks for a line like
20441 #+BIBLIOGRAPHY: foo plain option:-d
20443 and derives from it that foo.bib is the bibliography file relevant
20444 for this document. It then installs the necessary environment for RefTeX
20445 to work in this buffer and calls `reftex-citation' to insert a citation
20446 into the buffer.
20448 Export of such citations to both LaTeX and HTML is handled by the contributed
20449 package org-exp-bibtex by Taru Karttunen."
20450 (interactive)
20451 (let ((reftex-docstruct-symbol 'rds)
20452 (reftex-cite-format "\\cite{%l}")
20453 rds bib)
20454 (save-excursion
20455 (save-restriction
20456 (widen)
20457 (let ((case-fold-search t)
20458 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20459 (if (not (save-excursion
20460 (or (re-search-forward re nil t)
20461 (re-search-backward re nil t))))
20462 (error "No bibliography defined in file")
20463 (setq bib (concat (match-string 1) ".bib")
20464 rds (list (list 'bib bib)))))))
20465 (call-interactively 'reftex-citation)))
20467 ;;;; Functions extending outline functionality
20469 (defun org-beginning-of-line (&optional arg)
20470 "Go to the beginning of the current line. If that is invisible, continue
20471 to a visible line beginning. This makes the function of C-a more intuitive.
20472 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20473 first attempt, and only move to after the tags when the cursor is already
20474 beyond the end of the headline."
20475 (interactive "P")
20476 (let ((pos (point))
20477 (special (if (consp org-special-ctrl-a/e)
20478 (car org-special-ctrl-a/e)
20479 org-special-ctrl-a/e))
20480 refpos)
20481 (if (org-bound-and-true-p line-move-visual)
20482 (beginning-of-visual-line 1)
20483 (beginning-of-line 1))
20484 (if (and arg (fboundp 'move-beginning-of-line))
20485 (call-interactively 'move-beginning-of-line)
20486 (if (bobp)
20488 (backward-char 1)
20489 (if (org-truely-invisible-p)
20490 (while (and (not (bobp)) (org-truely-invisible-p))
20491 (backward-char 1)
20492 (beginning-of-line 1))
20493 (forward-char 1))))
20494 (when special
20495 (cond
20496 ((and (looking-at org-complex-heading-regexp)
20497 (= (char-after (match-end 1)) ?\ ))
20498 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20499 (point-at-eol)))
20500 (goto-char
20501 (if (eq special t)
20502 (cond ((> pos refpos) refpos)
20503 ((= pos (point)) refpos)
20504 (t (point)))
20505 (cond ((> pos (point)) (point))
20506 ((not (eq last-command this-command)) (point))
20507 (t refpos)))))
20508 ((org-at-item-p)
20509 ;; Being at an item and not looking at an the item means point
20510 ;; was previously moved to beginning of a visual line, which
20511 ;; doesn't contain the item. Therefore, do nothing special,
20512 ;; just stay here.
20513 (when (looking-at org-list-full-item-re)
20514 ;; Set special position at first white space character after
20515 ;; bullet, and check-box, if any.
20516 (let ((after-bullet
20517 (let ((box (match-end 3)))
20518 (if (not box) (match-end 1)
20519 (let ((after (char-after box)))
20520 (if (and after (= after ? )) (1+ box) box))))))
20521 ;; Special case: Move point to special position when
20522 ;; currently after it or at beginning of line.
20523 (if (eq special t)
20524 (when (or (> pos after-bullet) (= (point) pos))
20525 (goto-char after-bullet))
20526 ;; Reversed case: Move point to special position when
20527 ;; point was already at beginning of line and command is
20528 ;; repeated.
20529 (when (and (= (point) pos) (eq last-command this-command))
20530 (goto-char after-bullet))))))))
20531 (org-no-warnings
20532 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20534 (defun org-end-of-line (&optional arg)
20535 "Go to the end of the line.
20536 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20537 first attempt, and only move to after the tags when the cursor is already
20538 beyond the end of the headline."
20539 (interactive "P")
20540 (let ((special (if (consp org-special-ctrl-a/e)
20541 (cdr org-special-ctrl-a/e)
20542 org-special-ctrl-a/e)))
20543 (cond
20544 ((or (not special) arg
20545 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20546 (call-interactively
20547 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20548 ((fboundp 'move-end-of-line) 'move-end-of-line)
20549 (t 'end-of-line))))
20550 ((org-at-heading-p)
20551 (let ((pos (point)))
20552 (beginning-of-line 1)
20553 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20554 (if (eq special t)
20555 (if (or (< pos (match-beginning 1))
20556 (= pos (match-end 0)))
20557 (goto-char (match-beginning 1))
20558 (goto-char (match-end 0)))
20559 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20560 (goto-char (match-end 0))
20561 (goto-char (match-beginning 1))))
20562 (call-interactively (if (fboundp 'move-end-of-line)
20563 'move-end-of-line
20564 'end-of-line)))))
20565 ((org-at-drawer-p)
20566 (move-end-of-line 1)
20567 (when (overlays-at (1- (point))) (backward-char 1)))
20568 ;; At an item: Move before any hidden text.
20569 (t (call-interactively
20570 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20571 ((fboundp 'move-end-of-line) 'move-end-of-line)
20572 (t 'end-of-line)))))
20573 (org-no-warnings
20574 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20576 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20577 (define-key org-mode-map "\C-e" 'org-end-of-line)
20579 (defun org-backward-sentence (&optional arg)
20580 "Go to beginning of sentence, or beginning of table field.
20581 This will call `backward-sentence' or `org-table-beginning-of-field',
20582 depending on context."
20583 (interactive "P")
20584 (cond
20585 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20586 (t (call-interactively 'backward-sentence))))
20588 (defun org-forward-sentence (&optional arg)
20589 "Go to end of sentence, or end of table field.
20590 This will call `forward-sentence' or `org-table-end-of-field',
20591 depending on context."
20592 (interactive "P")
20593 (cond
20594 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20595 (t (call-interactively 'forward-sentence))))
20597 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20598 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20600 (defun org-kill-line (&optional arg)
20601 "Kill line, to tags or end of line."
20602 (interactive "P")
20603 (cond
20604 ((or (not org-special-ctrl-k)
20605 (bolp)
20606 (not (org-at-heading-p)))
20607 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20608 org-ctrl-k-protect-subtree)
20609 (if (or (eq org-ctrl-k-protect-subtree 'error)
20610 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20611 (error "C-k aborted - would kill hidden subtree")))
20612 (call-interactively 'kill-line))
20613 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20614 (kill-region (point) (match-beginning 1))
20615 (org-set-tags nil t))
20616 (t (kill-region (point) (point-at-eol)))))
20618 (define-key org-mode-map "\C-k" 'org-kill-line)
20620 (defun org-yank (&optional arg)
20621 "Yank. If the kill is a subtree, treat it specially.
20622 This command will look at the current kill and check if is a single
20623 subtree, or a series of subtrees[1]. If it passes the test, and if the
20624 cursor is at the beginning of a line or after the stars of a currently
20625 empty headline, then the yank is handled specially. How exactly depends
20626 on the value of the following variables, both set by default.
20628 org-yank-folded-subtrees
20629 When set, the subtree(s) will be folded after insertion, but only
20630 if doing so would now swallow text after the yanked text.
20632 org-yank-adjusted-subtrees
20633 When set, the subtree will be promoted or demoted in order to
20634 fit into the local outline tree structure, which means that the level
20635 will be adjusted so that it becomes the smaller one of the two
20636 *visible* surrounding headings.
20638 Any prefix to this command will cause `yank' to be called directly with
20639 no special treatment. In particular, a simple \\[universal-argument] prefix \
20640 will just
20641 plainly yank the text as it is.
20643 \[1] The test checks if the first non-white line is a heading
20644 and if there are no other headings with fewer stars."
20645 (interactive "P")
20646 (org-yank-generic 'yank arg))
20648 (defun org-yank-generic (command arg)
20649 "Perform some yank-like command.
20651 This function implements the behavior described in the `org-yank'
20652 documentation. However, it has been generalized to work for any
20653 interactive command with similar behavior."
20655 ;; pretend to be command COMMAND
20656 (setq this-command command)
20658 (if arg
20659 (call-interactively command)
20661 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20662 (and (org-kill-is-subtree-p)
20663 (or (bolp)
20664 (and (looking-at "[ \t]*$")
20665 (string-match
20666 "\\`\\*+\\'"
20667 (buffer-substring (point-at-bol) (point)))))))
20668 swallowp)
20669 (cond
20670 ((and subtreep org-yank-folded-subtrees)
20671 (let ((beg (point))
20672 end)
20673 (if (and subtreep org-yank-adjusted-subtrees)
20674 (org-paste-subtree nil nil 'for-yank)
20675 (call-interactively command))
20677 (setq end (point))
20678 (goto-char beg)
20679 (when (and (bolp) subtreep
20680 (not (setq swallowp
20681 (org-yank-folding-would-swallow-text beg end))))
20682 (org-with-limited-levels
20683 (or (looking-at org-outline-regexp)
20684 (re-search-forward org-outline-regexp-bol end t))
20685 (while (and (< (point) end) (looking-at org-outline-regexp))
20686 (hide-subtree)
20687 (org-cycle-show-empty-lines 'folded)
20688 (condition-case nil
20689 (outline-forward-same-level 1)
20690 (error (goto-char end))))))
20691 (when swallowp
20692 (message
20693 "Inserted text not folded because that would swallow text"))
20695 (goto-char end)
20696 (skip-chars-forward " \t\n\r")
20697 (beginning-of-line 1)
20698 (push-mark beg 'nomsg)))
20699 ((and subtreep org-yank-adjusted-subtrees)
20700 (let ((beg (point-at-bol)))
20701 (org-paste-subtree nil nil 'for-yank)
20702 (push-mark beg 'nomsg)))
20704 (call-interactively command))))))
20706 (defun org-yank-folding-would-swallow-text (beg end)
20707 "Would hide-subtree at BEG swallow any text after END?"
20708 (let (level)
20709 (org-with-limited-levels
20710 (save-excursion
20711 (goto-char beg)
20712 (when (or (looking-at org-outline-regexp)
20713 (re-search-forward org-outline-regexp-bol end t))
20714 (setq level (org-outline-level)))
20715 (goto-char end)
20716 (skip-chars-forward " \t\r\n\v\f")
20717 (if (or (eobp)
20718 (and (bolp) (looking-at org-outline-regexp)
20719 (<= (org-outline-level) level)))
20720 nil ; Nothing would be swallowed
20721 t))))) ; something would swallow
20723 (define-key org-mode-map "\C-y" 'org-yank)
20725 (defun org-truely-invisible-p ()
20726 "Check if point is at a character currently not visible.
20727 This version does not only check the character property, but also
20728 `visible-mode'."
20729 ;; Early versions of noutline don't have `outline-invisible-p'.
20730 (if (org-bound-and-true-p visible-mode)
20732 (outline-invisible-p)))
20734 (defun org-invisible-p2 ()
20735 "Check if point is at a character currently not visible."
20736 (save-excursion
20737 (if (and (eolp) (not (bobp))) (backward-char 1))
20738 ;; Early versions of noutline don't have `outline-invisible-p'.
20739 (outline-invisible-p)))
20741 (defun org-back-to-heading (&optional invisible-ok)
20742 "Call `outline-back-to-heading', but provide a better error message."
20743 (condition-case nil
20744 (outline-back-to-heading invisible-ok)
20745 (error (error "Before first headline at position %d in buffer %s"
20746 (point) (current-buffer)))))
20748 (defun org-beginning-of-defun ()
20749 "Go to the beginning of the subtree, i.e. back to the heading."
20750 (org-back-to-heading))
20751 (defun org-end-of-defun ()
20752 "Go to the end of the subtree."
20753 (org-end-of-subtree nil t))
20755 (defun org-before-first-heading-p ()
20756 "Before first heading?"
20757 (save-excursion
20758 (end-of-line)
20759 (null (re-search-backward org-outline-regexp-bol nil t))))
20761 (defun org-at-heading-p (&optional ignored)
20762 (outline-on-heading-p t))
20763 ;; Compatibility alias with Org versions < 7.8.03
20764 (defalias 'org-on-heading-p 'org-at-heading-p)
20766 (defun org-at-drawer-p nil
20767 "Whether point is at a drawer."
20768 (save-excursion
20769 (move-beginning-of-line 1)
20770 (looking-at org-drawer-regexp)))
20772 (defun org-point-at-end-of-empty-headline ()
20773 "If point is at the end of an empty headline, return t, else nil.
20774 If the heading only contains a TODO keyword, it is still still considered
20775 empty."
20776 (and (looking-at "[ \t]*$")
20777 (when org-todo-line-regexp
20778 (save-excursion
20779 (beginning-of-line 1)
20780 (let ((case-fold-search nil))
20781 (looking-at org-todo-line-regexp)
20782 (string= (match-string 3) ""))))))
20784 (defun org-at-heading-or-item-p ()
20785 (or (org-at-heading-p) (org-at-item-p)))
20787 (defun org-at-target-p ()
20788 (or (org-in-regexp org-radio-target-regexp)
20789 (org-in-regexp org-target-regexp)))
20790 ;; Compatibility alias with Org versions < 7.8.03
20791 (defalias 'org-on-target-p 'org-at-target-p)
20793 (defun org-up-heading-all (arg)
20794 "Move to the heading line of which the present line is a subheading.
20795 This function considers both visible and invisible heading lines.
20796 With argument, move up ARG levels."
20797 (if (fboundp 'outline-up-heading-all)
20798 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20799 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20801 (defun org-up-heading-safe ()
20802 "Move to the heading line of which the present line is a subheading.
20803 This version will not throw an error. It will return the level of the
20804 headline found, or nil if no higher level is found.
20806 Also, this function will be a lot faster than `outline-up-heading',
20807 because it relies on stars being the outline starters. This can really
20808 make a significant difference in outlines with very many siblings."
20809 (let (start-level re)
20810 (org-back-to-heading t)
20811 (setq start-level (funcall outline-level))
20812 (if (equal start-level 1)
20814 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20815 (if (re-search-backward re nil t)
20816 (funcall outline-level)))))
20818 (defun org-first-sibling-p ()
20819 "Is this heading the first child of its parents?"
20820 (interactive)
20821 (let ((re org-outline-regexp-bol)
20822 level l)
20823 (unless (org-at-heading-p t)
20824 (error "Not at a heading"))
20825 (setq level (funcall outline-level))
20826 (save-excursion
20827 (if (not (re-search-backward re nil t))
20829 (setq l (funcall outline-level))
20830 (< l level)))))
20832 (defun org-goto-sibling (&optional previous)
20833 "Goto the next sibling, even if it is invisible.
20834 When PREVIOUS is set, go to the previous sibling instead. Returns t
20835 when a sibling was found. When none is found, return nil and don't
20836 move point."
20837 (let ((fun (if previous 're-search-backward 're-search-forward))
20838 (pos (point))
20839 (re org-outline-regexp-bol)
20840 level l)
20841 (when (condition-case nil (org-back-to-heading t) (error nil))
20842 (setq level (funcall outline-level))
20843 (catch 'exit
20844 (or previous (forward-char 1))
20845 (while (funcall fun re nil t)
20846 (setq l (funcall outline-level))
20847 (when (< l level) (goto-char pos) (throw 'exit nil))
20848 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20849 (goto-char pos)
20850 nil))))
20852 (defun org-show-siblings ()
20853 "Show all siblings of the current headline."
20854 (save-excursion
20855 (while (org-goto-sibling) (org-flag-heading nil)))
20856 (save-excursion
20857 (while (org-goto-sibling 'previous)
20858 (org-flag-heading nil))))
20860 (defun org-goto-first-child ()
20861 "Goto the first child, even if it is invisible.
20862 Return t when a child was found. Otherwise don't move point and
20863 return nil."
20864 (let (level (pos (point)) (re org-outline-regexp-bol))
20865 (when (condition-case nil (org-back-to-heading t) (error nil))
20866 (setq level (outline-level))
20867 (forward-char 1)
20868 (if (and (re-search-forward re nil t) (> (outline-level) level))
20869 (progn (goto-char (match-beginning 0)) t)
20870 (goto-char pos) nil))))
20872 (defun org-show-hidden-entry ()
20873 "Show an entry where even the heading is hidden."
20874 (save-excursion
20875 (org-show-entry)))
20877 (defun org-flag-heading (flag &optional entry)
20878 "Flag the current heading. FLAG non-nil means make invisible.
20879 When ENTRY is non-nil, show the entire entry."
20880 (save-excursion
20881 (org-back-to-heading t)
20882 ;; Check if we should show the entire entry
20883 (if entry
20884 (progn
20885 (org-show-entry)
20886 (save-excursion
20887 (and (outline-next-heading)
20888 (org-flag-heading nil))))
20889 (outline-flag-region (max (point-min) (1- (point)))
20890 (save-excursion (outline-end-of-heading) (point))
20891 flag))))
20893 (defun org-get-next-sibling ()
20894 "Move to next heading of the same level, and return point.
20895 If there is no such heading, return nil.
20896 This is like outline-next-sibling, but invisible headings are ok."
20897 (let ((level (funcall outline-level)))
20898 (outline-next-heading)
20899 (while (and (not (eobp)) (> (funcall outline-level) level))
20900 (outline-next-heading))
20901 (if (or (eobp) (< (funcall outline-level) level))
20903 (point))))
20905 (defun org-get-last-sibling ()
20906 "Move to previous heading of the same level, and return point.
20907 If there is no such heading, return nil."
20908 (let ((opoint (point))
20909 (level (funcall outline-level)))
20910 (outline-previous-heading)
20911 (when (and (/= (point) opoint) (outline-on-heading-p t))
20912 (while (and (> (funcall outline-level) level)
20913 (not (bobp)))
20914 (outline-previous-heading))
20915 (if (< (funcall outline-level) level)
20917 (point)))))
20919 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20920 ;; This contains an exact copy of the original function, but it uses
20921 ;; `org-back-to-heading', to make it work also in invisible
20922 ;; trees. And is uses an invisible-OK argument.
20923 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20924 ;; Furthermore, when used inside Org, finding the end of a large subtree
20925 ;; with many children and grandchildren etc, this can be much faster
20926 ;; than the outline version.
20927 (org-back-to-heading invisible-OK)
20928 (let ((first t)
20929 (level (funcall outline-level)))
20930 (if (and (eq major-mode 'org-mode) (< level 1000))
20931 ;; A true heading (not a plain list item), in Org-mode
20932 ;; This means we can easily find the end by looking
20933 ;; only for the right number of stars. Using a regexp to do
20934 ;; this is so much faster than using a Lisp loop.
20935 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20936 (forward-char 1)
20937 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20938 ;; something else, do it the slow way
20939 (while (and (not (eobp))
20940 (or first (> (funcall outline-level) level)))
20941 (setq first nil)
20942 (outline-next-heading)))
20943 (unless to-heading
20944 (if (memq (preceding-char) '(?\n ?\^M))
20945 (progn
20946 ;; Go to end of line before heading
20947 (forward-char -1)
20948 (if (memq (preceding-char) '(?\n ?\^M))
20949 ;; leave blank line before heading
20950 (forward-char -1))))))
20951 (point))
20953 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20954 "Use Org version in org-mode, for dramatic speed-up."
20955 (if (eq major-mode 'org-mode)
20956 (progn
20957 (org-end-of-subtree nil t)
20958 (unless (eobp) (backward-char 1)))
20959 ad-do-it))
20961 (defun org-end-of-meta-data-and-drawers ()
20962 "Jump to the first text after meta data and drawers in the current entry.
20963 This will move over empty lines, lines with planning time stamps,
20964 clocking lines, and drawers."
20965 (org-back-to-heading t)
20966 (let ((end (save-excursion (outline-next-heading) (point)))
20967 (re (concat "\\(" org-drawer-regexp "\\)"
20968 "\\|" "[ \t]*" org-keyword-time-regexp)))
20969 (forward-line 1)
20970 (while (re-search-forward re end t)
20971 (if (not (match-end 1))
20972 ;; empty or planning line
20973 (forward-line 1)
20974 ;; a drawer, find the end
20975 (re-search-forward "^[ \t]*:END:" end 'move)
20976 (forward-line 1)))
20977 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20978 (point)))
20980 (defun org-forward-same-level (arg &optional invisible-ok)
20981 "Move forward to the arg'th subheading at same level as this one.
20982 Stop at the first and last subheadings of a superior heading.
20983 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20984 it wil also look at invisible ones."
20985 (interactive "p")
20986 (org-back-to-heading invisible-ok)
20987 (org-at-heading-p)
20988 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20989 (re (format "^\\*\\{1,%d\\} " level))
20991 (forward-char 1)
20992 (while (> arg 0)
20993 (while (and (re-search-forward re nil 'move)
20994 (setq l (- (match-end 0) (match-beginning 0) 1))
20995 (= l level)
20996 (not invisible-ok)
20997 (progn (backward-char 1) (outline-invisible-p)))
20998 (if (< l level) (setq arg 1)))
20999 (setq arg (1- arg)))
21000 (beginning-of-line 1)))
21002 (defun org-backward-same-level (arg &optional invisible-ok)
21003 "Move backward to the arg'th subheading at same level as this one.
21004 Stop at the first and last subheadings of a superior heading."
21005 (interactive "p")
21006 (org-back-to-heading)
21007 (org-at-heading-p)
21008 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21009 (re (format "^\\*\\{1,%d\\} " level))
21011 (while (> arg 0)
21012 (while (and (re-search-backward re nil 'move)
21013 (setq l (- (match-end 0) (match-beginning 0) 1))
21014 (= l level)
21015 (not invisible-ok)
21016 (outline-invisible-p))
21017 (if (< l level) (setq arg 1)))
21018 (setq arg (1- arg)))))
21020 (defun org-show-subtree ()
21021 "Show everything after this heading at deeper levels."
21022 (interactive)
21023 (outline-flag-region
21024 (point)
21025 (save-excursion
21026 (org-end-of-subtree t t))
21027 nil))
21029 (defun org-show-entry ()
21030 "Show the body directly following this heading.
21031 Show the heading too, if it is currently invisible."
21032 (interactive)
21033 (save-excursion
21034 (condition-case nil
21035 (progn
21036 (org-back-to-heading t)
21037 (outline-flag-region
21038 (max (point-min) (1- (point)))
21039 (save-excursion
21040 (if (re-search-forward
21041 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21042 (match-beginning 1)
21043 (point-max)))
21044 nil)
21045 (org-cycle-hide-drawers 'children))
21046 (error nil))))
21048 (defun org-make-options-regexp (kwds &optional extra)
21049 "Make a regular expression for keyword lines."
21050 (concat
21052 "#?[ \t]*\\+\\("
21053 (mapconcat 'regexp-quote kwds "\\|")
21054 (if extra (concat "\\|" extra))
21055 "\\):[ \t]*"
21056 "\\(.*\\)"))
21058 ;; Make isearch reveal the necessary context
21059 (defun org-isearch-end ()
21060 "Reveal context after isearch exits."
21061 (when isearch-success ; only if search was successful
21062 (if (featurep 'xemacs)
21063 ;; Under XEmacs, the hook is run in the correct place,
21064 ;; we directly show the context.
21065 (org-show-context 'isearch)
21066 ;; In Emacs the hook runs *before* restoring the overlays.
21067 ;; So we have to use a one-time post-command-hook to do this.
21068 ;; (Emacs 22 has a special variable, see function `org-mode')
21069 (unless (and (boundp 'isearch-mode-end-hook-quit)
21070 isearch-mode-end-hook-quit)
21071 ;; Only when the isearch was not quitted.
21072 (org-add-hook 'post-command-hook 'org-isearch-post-command
21073 'append 'local)))))
21075 (defun org-isearch-post-command ()
21076 "Remove self from hook, and show context."
21077 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21078 (org-show-context 'isearch))
21081 ;;;; Integration with and fixes for other packages
21083 ;;; Imenu support
21085 (defvar org-imenu-markers nil
21086 "All markers currently used by Imenu.")
21087 (make-variable-buffer-local 'org-imenu-markers)
21089 (defun org-imenu-new-marker (&optional pos)
21090 "Return a new marker for use by Imenu, and remember the marker."
21091 (let ((m (make-marker)))
21092 (move-marker m (or pos (point)))
21093 (push m org-imenu-markers)
21096 (defun org-imenu-get-tree ()
21097 "Produce the index for Imenu."
21098 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21099 (setq org-imenu-markers nil)
21100 (let* ((n org-imenu-depth)
21101 (re (concat "^" (org-get-limited-outline-regexp)))
21102 (subs (make-vector (1+ n) nil))
21103 (last-level 0)
21104 m level head)
21105 (save-excursion
21106 (save-restriction
21107 (widen)
21108 (goto-char (point-max))
21109 (while (re-search-backward re nil t)
21110 (setq level (org-reduced-level (funcall outline-level)))
21111 (when (and (<= level n)
21112 (looking-at org-complex-heading-regexp))
21113 (setq head (org-link-display-format
21114 (org-match-string-no-properties 4))
21115 m (org-imenu-new-marker))
21116 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21117 (if (>= level last-level)
21118 (push (cons head m) (aref subs level))
21119 (push (cons head (aref subs (1+ level))) (aref subs level))
21120 (loop for i from (1+ level) to n do (aset subs i nil)))
21121 (setq last-level level)))))
21122 (aref subs 1)))
21124 (eval-after-load "imenu"
21125 '(progn
21126 (add-hook 'imenu-after-jump-hook
21127 (lambda ()
21128 (if (eq major-mode 'org-mode)
21129 (org-show-context 'org-goto))))))
21131 (defun org-link-display-format (link)
21132 "Replace a link with either the description, or the link target
21133 if no description is present"
21134 (save-match-data
21135 (if (string-match org-bracket-link-analytic-regexp link)
21136 (replace-match (if (match-end 5)
21137 (match-string 5 link)
21138 (concat (match-string 1 link)
21139 (match-string 3 link)))
21140 nil t link)
21141 link)))
21143 (defun org-toggle-link-display ()
21144 "Toggle the literal or descriptive display of links."
21145 (interactive)
21146 (if org-descriptive-links
21147 (progn (org-remove-from-invisibility-spec '(org-link))
21148 (org-restart-font-lock)
21149 (setq org-descriptive-links nil))
21150 (progn (add-to-invisibility-spec '(org-link))
21151 (org-restart-font-lock)
21152 (setq org-descriptive-links t))))
21154 ;; Speedbar support
21156 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21157 "Overlay marking the agenda restriction line in speedbar.")
21158 (overlay-put org-speedbar-restriction-lock-overlay
21159 'face 'org-agenda-restriction-lock)
21160 (overlay-put org-speedbar-restriction-lock-overlay
21161 'help-echo "Agendas are currently limited to this item.")
21162 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21164 (defun org-speedbar-set-agenda-restriction ()
21165 "Restrict future agenda commands to the location at point in speedbar.
21166 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21167 (interactive)
21168 (require 'org-agenda)
21169 (let (p m tp np dir txt)
21170 (cond
21171 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21172 'org-imenu t))
21173 (setq m (get-text-property p 'org-imenu-marker))
21174 (with-current-buffer (marker-buffer m)
21175 (goto-char m)
21176 (org-agenda-set-restriction-lock 'subtree)))
21177 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21178 'speedbar-function 'speedbar-find-file))
21179 (setq tp (previous-single-property-change
21180 (1+ p) 'speedbar-function)
21181 np (next-single-property-change
21182 tp 'speedbar-function)
21183 dir (speedbar-line-directory)
21184 txt (buffer-substring-no-properties (or tp (point-min))
21185 (or np (point-max))))
21186 (with-current-buffer (find-file-noselect
21187 (let ((default-directory dir))
21188 (expand-file-name txt)))
21189 (unless (eq major-mode 'org-mode)
21190 (error "Cannot restrict to non-Org-mode file"))
21191 (org-agenda-set-restriction-lock 'file)))
21192 (t (error "Don't know how to restrict Org-mode's agenda")))
21193 (move-overlay org-speedbar-restriction-lock-overlay
21194 (point-at-bol) (point-at-eol))
21195 (setq current-prefix-arg nil)
21196 (org-agenda-maybe-redo)))
21198 (eval-after-load "speedbar"
21199 '(progn
21200 (speedbar-add-supported-extension ".org")
21201 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21202 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21203 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21204 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21205 (add-hook 'speedbar-visiting-tag-hook
21206 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21208 ;;; Fixes and Hacks for problems with other packages
21210 ;; Make flyspell not check words in links, to not mess up our keymap
21211 (defun org-mode-flyspell-verify ()
21212 "Don't let flyspell put overlays at active buttons, or on
21213 {todo,all-time,additional-option-like}-keywords."
21214 (let ((pos (max (1- (point)) (point-min)))
21215 (word (thing-at-point 'word)))
21216 (and (not (get-text-property pos 'keymap))
21217 (not (get-text-property pos 'org-no-flyspell))
21218 (not (member word org-todo-keywords-1))
21219 (not (member word org-all-time-keywords))
21220 (not (member word org-additional-option-like-keywords)))))
21222 (defun org-remove-flyspell-overlays-in (beg end)
21223 "Remove flyspell overlays in region."
21224 (and (org-bound-and-true-p flyspell-mode)
21225 (fboundp 'flyspell-delete-region-overlays)
21226 (flyspell-delete-region-overlays beg end))
21227 (add-text-properties beg end '(org-no-flyspell t)))
21229 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21230 (eval-after-load "bookmark"
21231 '(if (boundp 'bookmark-after-jump-hook)
21232 ;; We can use the hook
21233 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21234 ;; Hook not available, use advice
21235 (defadvice bookmark-jump (after org-make-visible activate)
21236 "Make the position visible."
21237 (org-bookmark-jump-unhide))))
21239 ;; Make sure saveplace shows the location if it was hidden
21240 (eval-after-load "saveplace"
21241 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21242 "Make the position visible."
21243 (org-bookmark-jump-unhide)))
21245 ;; Make sure ecb shows the location if it was hidden
21246 (eval-after-load "ecb"
21247 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21248 "Make hierarchy visible when jumping into location from ECB tree buffer."
21249 (if (eq major-mode 'org-mode)
21250 (org-show-context))))
21252 (defun org-bookmark-jump-unhide ()
21253 "Unhide the current position, to show the bookmark location."
21254 (and (eq major-mode 'org-mode)
21255 (or (outline-invisible-p)
21256 (save-excursion (goto-char (max (point-min) (1- (point))))
21257 (outline-invisible-p)))
21258 (org-show-context 'bookmark-jump)))
21260 ;; Make session.el ignore our circular variable
21261 (eval-after-load "session"
21262 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21264 ;;;; Experimental code
21266 (defun org-closed-in-range ()
21267 "Sparse tree of items closed in a certain time range.
21268 Still experimental, may disappear in the future."
21269 (interactive)
21270 ;; Get the time interval from the user.
21271 (let* ((time1 (org-float-time
21272 (org-read-date nil 'to-time nil "Starting date: ")))
21273 (time2 (org-float-time
21274 (org-read-date nil 'to-time nil "End date:")))
21275 ;; callback function
21276 (callback (lambda ()
21277 (let ((time
21278 (org-float-time
21279 (apply 'encode-time
21280 (org-parse-time-string
21281 (match-string 1))))))
21282 ;; check if time in interval
21283 (and (>= time time1) (<= time time2))))))
21284 ;; make tree, check each match with the callback
21285 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21287 ;;;; Finish up
21289 (provide 'org)
21291 (run-hooks 'org-load-hook)
21293 ;;; org.el ends here