org.el: Fix bug when gathering tag completion options.
[org-mode/org-kjn.git] / lisp / org.el
blob49a715361ab50d8fd361003151f35d3f31803d47
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.08
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.08"
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 `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 (match-end 0) end1 (1- (match-beginning 0)))
5431 (setq block-end (match-beginning 0))
5432 (when quoting
5433 (remove-text-properties beg end
5434 '(display t invisible t intangible t)))
5435 (add-text-properties
5436 beg end
5437 '(font-lock-fontified t font-lock-multiline t))
5438 (add-text-properties beg beg1 '(face org-meta-line))
5439 (add-text-properties end1 (min (point-max) (1+ end))
5440 '(face org-meta-line)) ; for end_src
5441 (cond
5442 ((and lang (not (string= lang "")) org-src-fontify-natively)
5443 (org-src-font-lock-fontify-block lang block-start block-end)
5444 ;; remove old background overlays
5445 (mapc (lambda (ov)
5446 (if (eq (overlay-get ov 'face) 'org-block-background)
5447 (delete-overlay ov)))
5448 (overlays-at (/ (+ beg1 block-end) 2)))
5449 ;; add a background overlay
5450 (setq ovl (make-overlay beg1 block-end))
5451 (overlay-put ovl 'face 'org-block-background)
5452 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5453 (quoting
5454 (add-text-properties beg1 (min (point-max) (1+ end1))
5455 '(face org-block))) ; end of source block
5456 ((not org-fontify-quote-and-verse-blocks))
5457 ((string= block-type "quote")
5458 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5459 ((string= block-type "verse")
5460 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5461 (add-text-properties beg beg1 '(face org-block-begin-line))
5462 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5464 ((member dc1 '("title:" "author:" "email:" "date:"))
5465 (add-text-properties
5466 beg (match-end 3)
5467 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5468 '(font-lock-fontified t invisible t)
5469 '(font-lock-fontified t face org-document-info-keyword)))
5470 (add-text-properties
5471 (match-beginning 6) (match-end 6)
5472 (if (string-equal dc1 "title:")
5473 '(font-lock-fontified t face org-document-title)
5474 '(font-lock-fontified t face org-document-info))))
5475 ((not (member (char-after beg) '(?\ ?\t)))
5476 ;; just any other in-buffer setting, but not indented
5477 (add-text-properties
5478 beg (1+ (match-end 0))
5479 '(font-lock-fontified t face org-meta-line))
5481 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5482 "orgtbl:" "tblfm:" "tblname:" "results:"
5483 "call:" "header:" "headers:" "name:"))
5484 (and (match-end 4) (equal dc3 "attr")))
5485 (add-text-properties
5486 beg (match-end 0)
5487 '(font-lock-fontified t face org-meta-line))
5489 ((member dc3 '(" " ""))
5490 (add-text-properties
5491 beg (match-end 0)
5492 '(font-lock-fontified t face font-lock-comment-face)))
5493 (t nil))))))
5495 (defun org-strip-protective-commas (beg end)
5496 "Strip protective commas between BEG and END in the current buffer."
5497 (interactive "r")
5498 (save-excursion
5499 (save-match-data
5500 (goto-char beg)
5501 (let ((front-line (save-excursion
5502 (re-search-forward
5503 "[^[:space:]]" end t)
5504 (goto-char (match-beginning 0))
5505 (current-column))))
5506 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5507 (goto-char (match-beginning 1))
5508 (when (= (current-column) front-line)
5509 (replace-match "" nil nil nil 1)))))))
5511 (defun org-activate-angle-links (limit)
5512 "Run through the buffer and add overlays to links."
5513 (if (re-search-forward org-angle-link-re limit t)
5514 (progn
5515 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5516 (add-text-properties (match-beginning 0) (match-end 0)
5517 (list 'mouse-face 'highlight
5518 'keymap org-mouse-map))
5519 (org-rear-nonsticky-at (match-end 0))
5520 t)))
5522 (defun org-activate-footnote-links (limit)
5523 "Run through the buffer and add overlays to footnotes."
5524 (let ((fn (org-footnote-next-reference-or-definition limit)))
5525 (when fn
5526 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5527 (org-remove-flyspell-overlays-in beg end)
5528 (add-text-properties beg end
5529 (list 'mouse-face 'highlight
5530 'keymap org-mouse-map
5531 'help-echo
5532 (if (= (point-at-bol) beg)
5533 "Footnote definition"
5534 "Footnote reference")
5535 'font-lock-fontified t
5536 'font-lock-multiline t
5537 'face 'org-footnote))))))
5539 (defun org-activate-bracket-links (limit)
5540 "Run through the buffer and add overlays to bracketed links."
5541 (if (re-search-forward org-bracket-link-regexp limit t)
5542 (let* ((help (concat "LINK: "
5543 (org-match-string-no-properties 1)))
5544 ;; FIXME: above we should remove the escapes.
5545 ;; but that requires another match, protecting match data,
5546 ;; a lot of overhead for font-lock.
5547 (ip (org-maybe-intangible
5548 (list 'invisible 'org-link
5549 'keymap org-mouse-map 'mouse-face 'highlight
5550 'font-lock-multiline t 'help-echo help)))
5551 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5552 'font-lock-multiline t 'help-echo help)))
5553 ;; We need to remove the invisible property here. Table narrowing
5554 ;; may have made some of this invisible.
5555 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5556 (remove-text-properties (match-beginning 0) (match-end 0)
5557 '(invisible nil))
5558 (if (match-end 3)
5559 (progn
5560 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5561 (org-rear-nonsticky-at (match-beginning 3))
5562 (add-text-properties (match-beginning 3) (match-end 3) vp)
5563 (org-rear-nonsticky-at (match-end 3))
5564 (add-text-properties (match-end 3) (match-end 0) ip)
5565 (org-rear-nonsticky-at (match-end 0)))
5566 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5567 (org-rear-nonsticky-at (match-beginning 1))
5568 (add-text-properties (match-beginning 1) (match-end 1) vp)
5569 (org-rear-nonsticky-at (match-end 1))
5570 (add-text-properties (match-end 1) (match-end 0) ip)
5571 (org-rear-nonsticky-at (match-end 0)))
5572 t)))
5574 (defun org-activate-dates (limit)
5575 "Run through the buffer and add overlays to dates."
5576 (if (re-search-forward org-tsr-regexp-both limit t)
5577 (progn
5578 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5579 (add-text-properties (match-beginning 0) (match-end 0)
5580 (list 'mouse-face 'highlight
5581 'keymap org-mouse-map))
5582 (org-rear-nonsticky-at (match-end 0))
5583 (when org-display-custom-times
5584 (if (match-end 3)
5585 (org-display-custom-time (match-beginning 3) (match-end 3)))
5586 (org-display-custom-time (match-beginning 1) (match-end 1)))
5587 t)))
5589 (defvar org-target-link-regexp nil
5590 "Regular expression matching radio targets in plain text.")
5591 (make-variable-buffer-local 'org-target-link-regexp)
5592 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5593 "Regular expression matching a link target.")
5594 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5595 "Regular expression matching a radio target.")
5596 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5597 "Regular expression matching any target.")
5599 (defun org-activate-target-links (limit)
5600 "Run through the buffer and add overlays to target matches."
5601 (when org-target-link-regexp
5602 (let ((case-fold-search t))
5603 (if (re-search-forward org-target-link-regexp limit t)
5604 (progn
5605 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5606 (add-text-properties (match-beginning 0) (match-end 0)
5607 (list 'mouse-face 'highlight
5608 'keymap org-mouse-map
5609 'help-echo "Radio target link"
5610 'org-linked-text t))
5611 (org-rear-nonsticky-at (match-end 0))
5612 t)))))
5614 (defun org-update-radio-target-regexp ()
5615 "Find all radio targets in this file and update the regular expression."
5616 (interactive)
5617 (when (memq 'radio org-activate-links)
5618 (setq org-target-link-regexp
5619 (org-make-target-link-regexp (org-all-targets 'radio)))
5620 (org-restart-font-lock)))
5622 (defun org-hide-wide-columns (limit)
5623 (let (s e)
5624 (setq s (text-property-any (point) (or limit (point-max))
5625 'org-cwidth t))
5626 (when s
5627 (setq e (next-single-property-change s 'org-cwidth))
5628 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5629 (goto-char e)
5630 t)))
5632 (defvar org-latex-and-specials-regexp nil
5633 "Regular expression for highlighting export special stuff.")
5634 (defvar org-match-substring-regexp)
5635 (defvar org-match-substring-with-braces-regexp)
5637 ;; This should be with the exporter code, but we also use if for font-locking
5638 (defconst org-export-html-special-string-regexps
5639 '(("\\\\-" . "&shy;")
5640 ("---\\([^-]\\)" . "&mdash;\\1")
5641 ("--\\([^-]\\)" . "&ndash;\\1")
5642 ("\\.\\.\\." . "&hellip;"))
5643 "Regular expressions for special string conversion.")
5646 (defun org-compute-latex-and-specials-regexp ()
5647 "Compute regular expression for stuff treated specially by exporters."
5648 (if (not org-highlight-latex-fragments-and-specials)
5649 (org-set-local 'org-latex-and-specials-regexp nil)
5650 (require 'org-exp)
5651 (let*
5652 ((matchers (plist-get org-format-latex-options :matchers))
5653 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5654 org-latex-regexps)))
5655 (org-export-allow-BIND nil)
5656 (options (org-combine-plists (org-default-export-plist)
5657 (org-infile-export-plist)))
5658 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5659 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5660 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5661 (org-export-html-expand (plist-get options :expand-quoted-html))
5662 (org-export-with-special-strings (plist-get options :special-strings))
5663 (re-sub
5664 (cond
5665 ((equal org-export-with-sub-superscripts '{})
5666 (list org-match-substring-with-braces-regexp))
5667 (org-export-with-sub-superscripts
5668 (list org-match-substring-regexp))
5669 (t nil)))
5670 (re-latex
5671 (if org-export-with-LaTeX-fragments
5672 (mapcar (lambda (x) (nth 1 x)) latexs)))
5673 (re-macros
5674 (if org-export-with-TeX-macros
5675 (list (concat "\\\\"
5676 (regexp-opt
5677 (append
5679 (delq nil
5680 (mapcar 'car-safe
5681 (append org-entities-user
5682 org-entities)))
5683 (if (boundp 'org-latex-entities)
5684 (mapcar (lambda (x)
5685 (or (car-safe x) x))
5686 org-latex-entities)
5687 nil))
5688 'words))) ; FIXME
5690 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5691 (re-special (if org-export-with-special-strings
5692 (mapcar (lambda (x) (car x))
5693 org-export-html-special-string-regexps)))
5694 (re-rest
5695 (delq nil
5696 (list
5697 (if org-export-html-expand "@<[^>\n]+>")
5698 ))))
5699 (org-set-local
5700 'org-latex-and-specials-regexp
5701 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5702 re-rest) "\\|")))))
5704 (defun org-do-latex-and-special-faces (limit)
5705 "Run through the buffer and add overlays to links."
5706 (when org-latex-and-specials-regexp
5707 (let (rtn d)
5708 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5709 limit t))
5710 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5711 'face))
5712 '(org-code org-verbatim underline)))
5713 (progn
5714 (setq rtn t
5715 d (cond ((member (char-after (1+ (match-beginning 0)))
5716 '(?_ ?^)) 1)
5717 (t 0)))
5718 (font-lock-prepend-text-property
5719 (+ d (match-beginning 0)) (match-end 0)
5720 'face 'org-latex-and-export-specials)
5721 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5722 '(font-lock-multiline t)))))
5723 rtn)))
5725 (defun org-restart-font-lock ()
5726 "Restart `font-lock-mode', to force refontification."
5727 (when (and (boundp 'font-lock-mode) font-lock-mode)
5728 (font-lock-mode -1)
5729 (font-lock-mode 1)))
5731 (defun org-all-targets (&optional radio)
5732 "Return a list of all targets in this file.
5733 With optional argument RADIO, only find radio targets."
5734 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5735 rtn)
5736 (save-excursion
5737 (goto-char (point-min))
5738 (while (re-search-forward re nil t)
5739 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5740 rtn)))
5742 (defun org-make-target-link-regexp (targets)
5743 "Make regular expression matching all strings in TARGETS.
5744 The regular expression finds the targets also if there is a line break
5745 between words."
5746 (and targets
5747 (concat
5748 "\\<\\("
5749 (mapconcat
5750 (lambda (x)
5751 (setq x (regexp-quote x))
5752 (while (string-match " +" x)
5753 (setq x (replace-match "\\s-+" t t x)))
5755 targets
5756 "\\|")
5757 "\\)\\>")))
5759 (defun org-activate-tags (limit)
5760 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5761 (progn
5762 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5763 (add-text-properties (match-beginning 1) (match-end 1)
5764 (list 'mouse-face 'highlight
5765 'keymap org-mouse-map))
5766 (org-rear-nonsticky-at (match-end 1))
5767 t)))
5769 (defun org-outline-level ()
5770 "Compute the outline level of the heading at point.
5771 This function assumes that the cursor is at the beginning of a line matched
5772 by `outline-regexp'. Otherwise it returns garbage.
5773 If this is called at a normal headline, the level is the number of stars.
5774 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5775 (save-excursion
5776 (looking-at org-outline-regexp)
5777 (1- (- (match-end 0) (match-beginning 0)))))
5779 (defvar org-font-lock-keywords nil)
5781 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5782 "Regular expression matching a property line.")
5784 (defvar org-font-lock-hook nil
5785 "Functions to be called for special font lock stuff.")
5787 (defvar org-font-lock-set-keywords-hook nil
5788 "Functions that can manipulate `org-font-lock-extra-keywords'.
5789 This is called after `org-font-lock-extra-keywords' is defined, but before
5790 it is installed to be used by font lock. This can be useful if something
5791 needs to be inserted at a specific position in the font-lock sequence.")
5793 (defun org-font-lock-hook (limit)
5794 (run-hook-with-args 'org-font-lock-hook limit))
5796 (defun org-set-font-lock-defaults ()
5797 (let* ((em org-fontify-emphasized-text)
5798 (lk org-activate-links)
5799 (org-font-lock-extra-keywords
5800 (list
5801 ;; Call the hook
5802 '(org-font-lock-hook)
5803 ;; Headlines
5804 `(,(if org-fontify-whole-heading-line
5805 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5806 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5807 (1 (org-get-level-face 1))
5808 (2 (org-get-level-face 2))
5809 (3 (org-get-level-face 3)))
5810 ;; Table lines
5811 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5812 (1 'org-table t))
5813 ;; Table internals
5814 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5815 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5816 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5817 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5818 ;; Drawers
5819 (list org-drawer-regexp '(0 'org-special-keyword t))
5820 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5821 ;; Properties
5822 (list org-property-re
5823 '(1 'org-special-keyword t)
5824 '(3 'org-property-value t))
5825 ;; Links
5826 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5827 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5828 (if (memq 'plain lk) '(org-activate-plain-links))
5829 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5830 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5831 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5832 (if (memq 'footnote lk) '(org-activate-footnote-links))
5833 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5834 '(org-hide-wide-columns (0 nil append))
5835 ;; TODO keyword
5836 (list (format org-heading-keyword-regexp-format
5837 org-todo-regexp)
5838 '(2 (org-get-todo-face 2) t))
5839 ;; DONE
5840 (if org-fontify-done-headline
5841 (list (format org-heading-keyword-regexp-format
5842 (concat
5843 "\\(?:"
5844 (mapconcat 'regexp-quote org-done-keywords "\\|")
5845 "\\)"))
5846 '(2 'org-headline-done t))
5847 nil)
5848 ;; Priorities
5849 '(org-font-lock-add-priority-faces)
5850 ;; Tags
5851 '(org-font-lock-add-tag-faces)
5852 ;; Special keywords
5853 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5854 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5855 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5856 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5857 ;; Emphasis
5858 (if em
5859 (if (featurep 'xemacs)
5860 '(org-do-emphasis-faces (0 nil append))
5861 '(org-do-emphasis-faces)))
5862 ;; Checkboxes
5863 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5864 1 'org-checkbox prepend)
5865 (if (cdr (assq 'checkbox org-list-automatic-rules))
5866 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5867 (0 (org-get-checkbox-statistics-face) t)))
5868 ;; Description list items
5869 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5870 1 'bold prepend)
5871 ;; ARCHIVEd headings
5872 (list (concat
5873 org-outline-regexp-bol
5874 "\\(.*:" org-archive-tag ":.*\\)")
5875 '(1 'org-archived prepend))
5876 ;; Specials
5877 '(org-do-latex-and-special-faces)
5878 '(org-fontify-entities)
5879 '(org-raise-scripts)
5880 ;; Code
5881 '(org-activate-code (1 'org-code t))
5882 ;; COMMENT
5883 (list (format org-heading-keyword-regexp-format
5884 (concat "\\("
5885 org-comment-string "\\|" org-quote-string
5886 "\\)"))
5887 '(2 'org-special-keyword t))
5888 '("^#.*" (0 'font-lock-comment-face t))
5889 ;; Blocks and meta lines
5890 '(org-fontify-meta-lines-and-blocks)
5892 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5893 (run-hooks 'org-font-lock-set-keywords-hook)
5894 ;; Now set the full font-lock-keywords
5895 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5896 (org-set-local 'font-lock-defaults
5897 '(org-font-lock-keywords t nil nil backward-paragraph))
5898 (kill-local-variable 'font-lock-keywords) nil))
5900 (defun org-toggle-pretty-entities ()
5901 "Toggle the composition display of entities as UTF8 characters."
5902 (interactive)
5903 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5904 (org-restart-font-lock)
5905 (if org-pretty-entities
5906 (message "Entities are displayed as UTF8 characters")
5907 (save-restriction
5908 (widen)
5909 (org-decompose-region (point-min) (point-max))
5910 (message "Entities are displayed plain"))))
5912 (defun org-fontify-entities (limit)
5913 "Find an entity to fontify."
5914 (let (ee)
5915 (when org-pretty-entities
5916 (catch 'match
5917 (while (re-search-forward
5918 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5919 limit t)
5920 (if (and (not (org-in-indented-comment-line))
5921 (setq ee (org-entity-get (match-string 1)))
5922 (= (length (nth 6 ee)) 1))
5923 (progn
5924 (add-text-properties
5925 (match-beginning 0) (match-end 1)
5926 (list 'font-lock-fontified t))
5927 (compose-region (match-beginning 0) (match-end 1)
5928 (nth 6 ee) nil)
5929 (backward-char 1)
5930 (throw 'match t))))
5931 nil))))
5933 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5934 "Fontify string S like in Org-mode."
5935 (with-temp-buffer
5936 (insert s)
5937 (let ((org-odd-levels-only odd-levels))
5938 (org-mode)
5939 (font-lock-fontify-buffer)
5940 (buffer-string))))
5942 (defvar org-m nil)
5943 (defvar org-l nil)
5944 (defvar org-f nil)
5945 (defun org-get-level-face (n)
5946 "Get the right face for match N in font-lock matching of headlines."
5947 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5948 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5949 (if org-cycle-level-faces
5950 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5951 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5952 (cond
5953 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5954 ((eq n 2) org-f)
5955 (t (if org-level-color-stars-only nil org-f))))
5958 (defun org-get-todo-face (kwd)
5959 "Get the right face for a TODO keyword KWD.
5960 If KWD is a number, get the corresponding match group."
5961 (if (numberp kwd) (setq kwd (match-string kwd)))
5962 (or (org-face-from-face-or-color
5963 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5964 (and (member kwd org-done-keywords) 'org-done)
5965 'org-todo))
5967 (defun org-face-from-face-or-color (context inherit face-or-color)
5968 "Create a face list that inherits INHERIT, but sets the foreground color.
5969 When FACE-OR-COLOR is not a string, just return it."
5970 (if (stringp face-or-color)
5971 (list :inherit inherit
5972 (cdr (assoc context org-faces-easy-properties))
5973 face-or-color)
5974 face-or-color))
5976 (defun org-font-lock-add-tag-faces (limit)
5977 "Add the special tag faces."
5978 (when (and org-tag-faces org-tags-special-faces-re)
5979 (while (re-search-forward org-tags-special-faces-re limit t)
5980 (add-text-properties (match-beginning 1) (match-end 1)
5981 (list 'face (org-get-tag-face 1)
5982 'font-lock-fontified t))
5983 (backward-char 1))))
5985 (defun org-font-lock-add-priority-faces (limit)
5986 "Add the special priority faces."
5987 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5988 (add-text-properties
5989 (match-beginning 0) (match-end 0)
5990 (list 'face (or (org-face-from-face-or-color
5991 'priority 'org-special-keyword
5992 (cdr (assoc (char-after (match-beginning 1))
5993 org-priority-faces)))
5994 'org-special-keyword)
5995 'font-lock-fontified t))))
5997 (defun org-get-tag-face (kwd)
5998 "Get the right face for a TODO keyword KWD.
5999 If KWD is a number, get the corresponding match group."
6000 (if (numberp kwd) (setq kwd (match-string kwd)))
6001 (or (org-face-from-face-or-color
6002 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6003 'org-tag))
6005 (defun org-unfontify-region (beg end &optional maybe_loudly)
6006 "Remove fontification and activation overlays from links."
6007 (font-lock-default-unfontify-region beg end)
6008 (let* ((buffer-undo-list t)
6009 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6010 (inhibit-modification-hooks t)
6011 deactivate-mark buffer-file-name buffer-file-truename)
6012 (org-decompose-region beg end)
6013 (remove-text-properties beg end
6014 '(mouse-face t keymap t org-linked-text t
6015 invisible t intangible t
6016 org-no-flyspell t org-emphasis t))
6017 (org-remove-font-lock-display-properties beg end)))
6019 (defconst org-script-display '(((raise -0.3) (height 0.7))
6020 ((raise 0.3) (height 0.7))
6021 ((raise -0.5))
6022 ((raise 0.5)))
6023 "Display properties for showing superscripts and subscripts.")
6025 (defun org-remove-font-lock-display-properties (beg end)
6026 "Remove specific display properties that have been added by font lock.
6027 The will remove the raise properties that are used to show superscripts
6028 and subscripts."
6029 (let (next prop)
6030 (while (< beg end)
6031 (setq next (next-single-property-change beg 'display nil end)
6032 prop (get-text-property beg 'display))
6033 (if (member prop org-script-display)
6034 (put-text-property beg next 'display nil))
6035 (setq beg next))))
6037 (defun org-raise-scripts (limit)
6038 "Add raise properties to sub/superscripts."
6039 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6040 (if (re-search-forward
6041 (if (eq org-use-sub-superscripts t)
6042 org-match-substring-regexp
6043 org-match-substring-with-braces-regexp)
6044 limit t)
6045 (let* ((pos (point)) table-p comment-p
6046 (mpos (match-beginning 3))
6047 (emph-p (get-text-property mpos 'org-emphasis))
6048 (link-p (get-text-property mpos 'mouse-face))
6049 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6050 (goto-char (point-at-bol))
6051 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6052 comment-p (org-looking-at-p "[ \t]*#"))
6053 (goto-char pos)
6054 ;; FIXME: Should we go back one character here, for a_b^c
6055 ;; (goto-char (1- pos)) ;????????????????????
6056 (if (or comment-p emph-p link-p keyw-p)
6058 (put-text-property (match-beginning 3) (match-end 0)
6059 'display
6060 (if (equal (char-after (match-beginning 2)) ?^)
6061 (nth (if table-p 3 1) org-script-display)
6062 (nth (if table-p 2 0) org-script-display)))
6063 (add-text-properties (match-beginning 2) (match-end 2)
6064 (list 'invisible t
6065 'org-dwidth t 'org-dwidth-n 1))
6066 (if (and (eq (char-after (match-beginning 3)) ?{)
6067 (eq (char-before (match-end 3)) ?}))
6068 (progn
6069 (add-text-properties
6070 (match-beginning 3) (1+ (match-beginning 3))
6071 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6072 (add-text-properties
6073 (1- (match-end 3)) (match-end 3)
6074 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6075 t)))))
6077 ;;;; Visibility cycling, including org-goto and indirect buffer
6079 ;;; Cycling
6081 (defvar org-cycle-global-status nil)
6082 (make-variable-buffer-local 'org-cycle-global-status)
6083 (defvar org-cycle-subtree-status nil)
6084 (make-variable-buffer-local 'org-cycle-subtree-status)
6086 ;;;###autoload
6088 (defvar org-inlinetask-min-level)
6090 (defun org-cycle (&optional arg)
6091 "TAB-action and visibility cycling for Org-mode.
6093 This is the command invoked in Org-mode by the TAB key. Its main purpose
6094 is outline visibility cycling, but it also invokes other actions
6095 in special contexts.
6097 - When this function is called with a prefix argument, rotate the entire
6098 buffer through 3 states (global cycling)
6099 1. OVERVIEW: Show only top-level headlines.
6100 2. CONTENTS: Show all headlines of all levels, but no body text.
6101 3. SHOW ALL: Show everything.
6102 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6103 determined by the variable `org-startup-folded', and by any VISIBILITY
6104 properties in the buffer.
6105 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6106 including any drawers.
6108 - When inside a table, re-align the table and move to the next field.
6110 - When point is at the beginning of a headline, rotate the subtree started
6111 by this line through 3 different states (local cycling)
6112 1. FOLDED: Only the main headline is shown.
6113 2. CHILDREN: The main headline and the direct children are shown.
6114 From this state, you can move to one of the children
6115 and zoom in further.
6116 3. SUBTREE: Show the entire subtree, including body text.
6117 If there is no subtree, switch directly from CHILDREN to FOLDED.
6119 - When point is at the beginning of an empty headline and the variable
6120 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6121 of the headline by demoting and promoting it to likely levels. This
6122 speeds up creation document structure by pressing TAB once or several
6123 times right after creating a new headline.
6125 - When there is a numeric prefix, go up to a heading with level ARG, do
6126 a `show-subtree' and return to the previous cursor position. If ARG
6127 is negative, go up that many levels.
6129 - When point is not at the beginning of a headline, execute the global
6130 binding for TAB, which is re-indenting the line. See the option
6131 `org-cycle-emulate-tab' for details.
6133 - Special case: if point is at the beginning of the buffer and there is
6134 no headline in line 1, this function will act as if called with prefix arg
6135 (C-u TAB, same as S-TAB) also when called without prefix arg.
6136 But only if also the variable `org-cycle-global-at-bob' is t."
6137 (interactive "P")
6138 (org-load-modules-maybe)
6139 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6140 (and org-cycle-level-after-item/entry-creation
6141 (or (org-cycle-level)
6142 (org-cycle-item-indentation))))
6143 (let* ((limit-level
6144 (or org-cycle-max-level
6145 (and (boundp 'org-inlinetask-min-level)
6146 org-inlinetask-min-level
6147 (1- org-inlinetask-min-level))))
6148 (nstars (and limit-level
6149 (if org-odd-levels-only
6150 (and limit-level (1- (* limit-level 2)))
6151 limit-level)))
6152 (org-outline-regexp
6153 (if (not (eq major-mode 'org-mode))
6154 outline-regexp
6155 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6156 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6157 (not (looking-at org-outline-regexp))))
6158 (org-cycle-hook
6159 (if bob-special
6160 (delq 'org-optimize-window-after-visibility-change
6161 (copy-sequence org-cycle-hook))
6162 org-cycle-hook))
6163 (pos (point)))
6165 (if (or bob-special (equal arg '(4)))
6166 ;; special case: use global cycling
6167 (setq arg t))
6169 (cond
6171 ((equal arg '(16))
6172 (setq last-command 'dummy)
6173 (org-set-startup-visibility)
6174 (message "Startup visibility, plus VISIBILITY properties"))
6176 ((equal arg '(64))
6177 (show-all)
6178 (message "Entire buffer visible, including drawers"))
6180 ;; Table: enter it or move to the next field.
6181 ((org-at-table-p 'any)
6182 (if (org-at-table.el-p)
6183 (message "Use C-c ' to edit table.el tables")
6184 (if arg (org-table-edit-field t)
6185 (org-table-justify-field-maybe)
6186 (call-interactively 'org-table-next-field))))
6188 ((run-hook-with-args-until-success
6189 'org-tab-after-check-for-table-hook))
6191 ;; Global cycling: delegate to `org-cycle-internal-global'.
6192 ((eq arg t) (org-cycle-internal-global))
6194 ;; Drawers: delegate to `org-flag-drawer'.
6195 ((and org-drawers org-drawer-regexp
6196 (save-excursion
6197 (beginning-of-line 1)
6198 (looking-at org-drawer-regexp)))
6199 (org-flag-drawer ; toggle block visibility
6200 (not (get-char-property (match-end 0) 'invisible))))
6202 ;; Show-subtree, ARG levels up from here.
6203 ((integerp arg)
6204 (save-excursion
6205 (org-back-to-heading)
6206 (outline-up-heading (if (< arg 0) (- arg)
6207 (- (funcall outline-level) arg)))
6208 (org-show-subtree)))
6210 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6211 ((and (featurep 'org-inlinetask)
6212 (org-inlinetask-at-task-p)
6213 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6214 (org-inlinetask-toggle-visibility))
6216 ((org-try-cdlatex-tab))
6218 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6219 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6220 (save-excursion (beginning-of-line 1)
6221 (looking-at org-outline-regexp)))
6222 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6223 (org-cycle-internal-local))
6225 ;; From there: TAB emulation and template completion.
6226 (buffer-read-only (org-back-to-heading))
6228 ((run-hook-with-args-until-success
6229 'org-tab-after-check-for-cycling-hook))
6231 ((org-try-structure-completion))
6233 ((run-hook-with-args-until-success
6234 'org-tab-before-tab-emulation-hook))
6236 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6237 (or (not (bolp))
6238 (not (looking-at org-outline-regexp))))
6239 (call-interactively (global-key-binding "\t")))
6241 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6242 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6243 (or (and (eq org-cycle-emulate-tab 'white)
6244 (= (match-end 0) (point-at-eol)))
6245 (and (eq org-cycle-emulate-tab 'whitestart)
6246 (>= (match-end 0) pos))))
6248 (eq org-cycle-emulate-tab t))
6249 (call-interactively (global-key-binding "\t")))
6251 (t (save-excursion
6252 (org-back-to-heading)
6253 (org-cycle)))))))
6255 (defun org-cycle-internal-global ()
6256 "Do the global cycling action."
6257 (cond
6258 ((and (eq last-command this-command)
6259 (eq org-cycle-global-status 'overview))
6260 ;; We just created the overview - now do table of contents
6261 ;; This can be slow in very large buffers, so indicate action
6262 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6263 (message "CONTENTS...")
6264 (org-content)
6265 (message "CONTENTS...done")
6266 (setq org-cycle-global-status 'contents)
6267 (run-hook-with-args 'org-cycle-hook 'contents))
6269 ((and (eq last-command this-command)
6270 (eq org-cycle-global-status 'contents))
6271 ;; We just showed the table of contents - now show everything
6272 (run-hook-with-args 'org-pre-cycle-hook 'all)
6273 (show-all)
6274 (message "SHOW ALL")
6275 (setq org-cycle-global-status 'all)
6276 (run-hook-with-args 'org-cycle-hook 'all))
6279 ;; Default action: go to overview
6280 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6281 (org-overview)
6282 (message "OVERVIEW")
6283 (setq org-cycle-global-status 'overview)
6284 (run-hook-with-args 'org-cycle-hook 'overview))))
6286 (defun org-cycle-internal-local ()
6287 "Do the local cycling action."
6288 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6289 ;; First, determine end of headline (EOH), end of subtree or item
6290 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6291 (save-excursion
6292 (if (org-at-item-p)
6293 (progn
6294 (beginning-of-line)
6295 (setq struct (org-list-struct))
6296 (setq eoh (point-at-eol))
6297 (setq eos (org-list-get-item-end-before-blank (point) struct))
6298 (setq has-children (org-list-has-child-p (point) struct)))
6299 (org-back-to-heading)
6300 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6301 (setq eos (save-excursion
6302 (org-end-of-subtree t)
6303 (unless (eobp)
6304 (skip-chars-forward " \t\n"))
6305 (if (eobp) (point) (1- (point)))))
6306 (setq has-children
6307 (or (save-excursion
6308 (let ((level (funcall outline-level)))
6309 (outline-next-heading)
6310 (and (org-at-heading-p t)
6311 (> (funcall outline-level) level))))
6312 (save-excursion
6313 (org-list-search-forward (org-item-beginning-re) eos t)))))
6314 ;; Determine end invisible part of buffer (EOL)
6315 (beginning-of-line 2)
6316 ;; XEmacs doesn't have `next-single-char-property-change'
6317 (if (featurep 'xemacs)
6318 (while (and (not (eobp)) ;; this is like `next-line'
6319 (get-char-property (1- (point)) 'invisible))
6320 (beginning-of-line 2))
6321 (while (and (not (eobp)) ;; this is like `next-line'
6322 (get-char-property (1- (point)) 'invisible))
6323 (goto-char (next-single-char-property-change (point) 'invisible))
6324 (and (eolp) (beginning-of-line 2))))
6325 (setq eol (point)))
6326 ;; Find out what to do next and set `this-command'
6327 (cond
6328 ((= eos eoh)
6329 ;; Nothing is hidden behind this heading
6330 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6331 (message "EMPTY ENTRY")
6332 (setq org-cycle-subtree-status nil)
6333 (save-excursion
6334 (goto-char eos)
6335 (outline-next-heading)
6336 (if (outline-invisible-p) (org-flag-heading nil))))
6337 ((and (or (>= eol eos)
6338 (not (string-match "\\S-" (buffer-substring eol eos))))
6339 (or has-children
6340 (not (setq children-skipped
6341 org-cycle-skip-children-state-if-no-children))))
6342 ;; Entire subtree is hidden in one line: children view
6343 (run-hook-with-args 'org-pre-cycle-hook 'children)
6344 (if (org-at-item-p)
6345 (org-list-set-item-visibility (point-at-bol) struct 'children)
6346 (org-show-entry)
6347 (org-with-limited-levels (show-children))
6348 ;; FIXME: This slows down the func way too much.
6349 ;; How keep drawers hidden in subtree anyway?
6350 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6351 ;; (org-cycle-hide-drawers 'subtree))
6353 ;; Fold every list in subtree to top-level items.
6354 (when (eq org-cycle-include-plain-lists 'integrate)
6355 (save-excursion
6356 (org-back-to-heading)
6357 (while (org-list-search-forward (org-item-beginning-re) eos t)
6358 (beginning-of-line 1)
6359 (let* ((struct (org-list-struct))
6360 (prevs (org-list-prevs-alist struct))
6361 (end (org-list-get-bottom-point struct)))
6362 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6363 (org-list-get-all-items (point) struct prevs))
6364 (goto-char end))))))
6365 (message "CHILDREN")
6366 (save-excursion
6367 (goto-char eos)
6368 (outline-next-heading)
6369 (if (outline-invisible-p) (org-flag-heading nil)))
6370 (setq org-cycle-subtree-status 'children)
6371 (run-hook-with-args 'org-cycle-hook 'children))
6372 ((or children-skipped
6373 (and (eq last-command this-command)
6374 (eq org-cycle-subtree-status 'children)))
6375 ;; We just showed the children, or no children are there,
6376 ;; now show everything.
6377 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6378 (outline-flag-region eoh eos nil)
6379 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6380 (setq org-cycle-subtree-status 'subtree)
6381 (run-hook-with-args 'org-cycle-hook 'subtree))
6383 ;; Default action: hide the subtree.
6384 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6385 (outline-flag-region eoh eos t)
6386 (message "FOLDED")
6387 (setq org-cycle-subtree-status 'folded)
6388 (run-hook-with-args 'org-cycle-hook 'folded)))))
6390 ;;;###autoload
6391 (defun org-global-cycle (&optional arg)
6392 "Cycle the global visibility. For details see `org-cycle'.
6393 With \\[universal-argument] prefix arg, switch to startup visibility.
6394 With a numeric prefix, show all headlines up to that level."
6395 (interactive "P")
6396 (let ((org-cycle-include-plain-lists
6397 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6398 (cond
6399 ((integerp arg)
6400 (show-all)
6401 (hide-sublevels arg)
6402 (setq org-cycle-global-status 'contents))
6403 ((equal arg '(4))
6404 (org-set-startup-visibility)
6405 (message "Startup visibility, plus VISIBILITY properties."))
6407 (org-cycle '(4))))))
6409 (defun org-set-startup-visibility ()
6410 "Set the visibility required by startup options and properties."
6411 (cond
6412 ((eq org-startup-folded t)
6413 (org-cycle '(4)))
6414 ((eq org-startup-folded 'content)
6415 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6416 (org-cycle '(4)) (org-cycle '(4)))))
6417 (unless (eq org-startup-folded 'showeverything)
6418 (if org-hide-block-startup (org-hide-block-all))
6419 (org-set-visibility-according-to-property 'no-cleanup)
6420 (org-cycle-hide-archived-subtrees 'all)
6421 (org-cycle-hide-drawers 'all)
6422 (org-cycle-show-empty-lines t)))
6424 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6425 "Switch subtree visibilities according to :VISIBILITY: property."
6426 (interactive)
6427 (let (org-show-entry-below state)
6428 (save-excursion
6429 (goto-char (point-min))
6430 (while (re-search-forward
6431 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6432 nil t)
6433 (setq state (match-string 1))
6434 (save-excursion
6435 (org-back-to-heading t)
6436 (hide-subtree)
6437 (org-reveal)
6438 (cond
6439 ((equal state '("fold" "folded"))
6440 (hide-subtree))
6441 ((equal state "children")
6442 (org-show-hidden-entry)
6443 (show-children))
6444 ((equal state "content")
6445 (save-excursion
6446 (save-restriction
6447 (org-narrow-to-subtree)
6448 (org-content))))
6449 ((member state '("all" "showall"))
6450 (show-subtree)))))
6451 (unless no-cleanup
6452 (org-cycle-hide-archived-subtrees 'all)
6453 (org-cycle-hide-drawers 'all)
6454 (org-cycle-show-empty-lines 'all)))))
6456 ;; This function uses outline-regexp instead of the more fundamental
6457 ;; org-outline-regexp so that org-cycle-global works outside of Org
6458 ;; buffers, where outline-regexp is needed.
6459 (defun org-overview ()
6460 "Switch to overview mode, showing only top-level headlines.
6461 Really, this shows all headlines with level equal or greater than the level
6462 of the first headline in the buffer. This is important, because if the
6463 first headline is not level one, then (hide-sublevels 1) gives confusing
6464 results."
6465 (interactive)
6466 (let ((level (save-excursion
6467 (goto-char (point-min))
6468 (if (re-search-forward (concat "^" outline-regexp) nil t)
6469 (progn
6470 (goto-char (match-beginning 0))
6471 (funcall outline-level))))))
6472 (and level (hide-sublevels level))))
6474 (defun org-content (&optional arg)
6475 "Show all headlines in the buffer, like a table of contents.
6476 With numerical argument N, show content up to level N."
6477 (interactive "P")
6478 (save-excursion
6479 ;; Visit all headings and show their offspring
6480 (and (integerp arg) (org-overview))
6481 (goto-char (point-max))
6482 (catch 'exit
6483 (while (and (progn (condition-case nil
6484 (outline-previous-visible-heading 1)
6485 (error (goto-char (point-min))))
6487 (looking-at org-outline-regexp))
6488 (if (integerp arg)
6489 (show-children (1- arg))
6490 (show-branches))
6491 (if (bobp) (throw 'exit nil))))))
6494 (defun org-optimize-window-after-visibility-change (state)
6495 "Adjust the window after a change in outline visibility.
6496 This function is the default value of the hook `org-cycle-hook'."
6497 (when (get-buffer-window (current-buffer))
6498 (cond
6499 ((eq state 'content) nil)
6500 ((eq state 'all) nil)
6501 ((eq state 'folded) nil)
6502 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6503 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6505 (defun org-remove-empty-overlays-at (pos)
6506 "Remove outline overlays that do not contain non-white stuff."
6507 (mapc
6508 (lambda (o)
6509 (and (eq 'outline (overlay-get o 'invisible))
6510 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6511 (overlay-end o))))
6512 (delete-overlay o)))
6513 (overlays-at pos)))
6515 (defun org-clean-visibility-after-subtree-move ()
6516 "Fix visibility issues after moving a subtree."
6517 ;; First, find a reasonable region to look at:
6518 ;; Start two siblings above, end three below
6519 (let* ((beg (save-excursion
6520 (and (org-get-last-sibling)
6521 (org-get-last-sibling))
6522 (point)))
6523 (end (save-excursion
6524 (and (org-get-next-sibling)
6525 (org-get-next-sibling)
6526 (org-get-next-sibling))
6527 (if (org-at-heading-p)
6528 (point-at-eol)
6529 (point))))
6530 (level (looking-at "\\*+"))
6531 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6532 (save-excursion
6533 (save-restriction
6534 (narrow-to-region beg end)
6535 (when re
6536 ;; Properly fold already folded siblings
6537 (goto-char (point-min))
6538 (while (re-search-forward re nil t)
6539 (if (and (not (outline-invisible-p))
6540 (save-excursion
6541 (goto-char (point-at-eol)) (outline-invisible-p)))
6542 (hide-entry))))
6543 (org-cycle-show-empty-lines 'overview)
6544 (org-cycle-hide-drawers 'overview)))))
6546 (defun org-cycle-show-empty-lines (state)
6547 "Show empty lines above all visible headlines.
6548 The region to be covered depends on STATE when called through
6549 `org-cycle-hook'. Lisp program can use t for STATE to get the
6550 entire buffer covered. Note that an empty line is only shown if there
6551 are at least `org-cycle-separator-lines' empty lines before the headline."
6552 (when (not (= org-cycle-separator-lines 0))
6553 (save-excursion
6554 (let* ((n (abs org-cycle-separator-lines))
6555 (re (cond
6556 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6557 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6558 (t (let ((ns (number-to-string (- n 2))))
6559 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6560 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6561 beg end b e)
6562 (cond
6563 ((memq state '(overview contents t))
6564 (setq beg (point-min) end (point-max)))
6565 ((memq state '(children folded))
6566 (setq beg (point) end (progn (org-end-of-subtree t t)
6567 (beginning-of-line 2)
6568 (point)))))
6569 (when beg
6570 (goto-char beg)
6571 (while (re-search-forward re end t)
6572 (unless (get-char-property (match-end 1) 'invisible)
6573 (setq e (match-end 1))
6574 (if (< org-cycle-separator-lines 0)
6575 (setq b (save-excursion
6576 (goto-char (match-beginning 0))
6577 (org-back-over-empty-lines)
6578 (if (save-excursion
6579 (goto-char (max (point-min) (1- (point))))
6580 (org-at-heading-p))
6581 (1- (point))
6582 (point))))
6583 (setq b (match-beginning 1)))
6584 (outline-flag-region b e nil)))))))
6585 ;; Never hide empty lines at the end of the file.
6586 (save-excursion
6587 (goto-char (point-max))
6588 (outline-previous-heading)
6589 (outline-end-of-heading)
6590 (if (and (looking-at "[ \t\n]+")
6591 (= (match-end 0) (point-max)))
6592 (outline-flag-region (point) (match-end 0) nil))))
6594 (defun org-show-empty-lines-in-parent ()
6595 "Move to the parent and re-show empty lines before visible headlines."
6596 (save-excursion
6597 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6598 (org-cycle-show-empty-lines context))))
6600 (defun org-files-list ()
6601 "Return `org-agenda-files' list, plus all open org-mode files.
6602 This is useful for operations that need to scan all of a user's
6603 open and agenda-wise Org files."
6604 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6605 (dolist (buf (buffer-list))
6606 (with-current-buffer buf
6607 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6608 (let ((file (expand-file-name (buffer-file-name))))
6609 (unless (member file files)
6610 (push file files))))))
6611 files))
6613 (defsubst org-entry-beginning-position ()
6614 "Return the beginning position of the current entry."
6615 (save-excursion (outline-back-to-heading t) (point)))
6617 (defsubst org-entry-end-position ()
6618 "Return the end position of the current entry."
6619 (save-excursion (outline-next-heading) (point)))
6621 (defun org-cycle-hide-drawers (state)
6622 "Re-hide all drawers after a visibility state change."
6623 (when (and (eq major-mode 'org-mode)
6624 (not (memq state '(overview folded contents))))
6625 (save-excursion
6626 (let* ((globalp (memq state '(contents all)))
6627 (beg (if globalp (point-min) (point)))
6628 (end (if globalp (point-max)
6629 (if (eq state 'children)
6630 (save-excursion (outline-next-heading) (point))
6631 (org-end-of-subtree t)))))
6632 (goto-char beg)
6633 (while (re-search-forward org-drawer-regexp end t)
6634 (org-flag-drawer t))))))
6636 (defun org-flag-drawer (flag)
6637 (save-excursion
6638 (beginning-of-line 1)
6639 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6640 (let ((b (match-end 0)))
6641 (if (re-search-forward
6642 "^[ \t]*:END:"
6643 (save-excursion (outline-next-heading) (point)) t)
6644 (outline-flag-region b (point-at-eol) flag)
6645 (error ":END: line missing at position %s" b))))))
6647 (defun org-subtree-end-visible-p ()
6648 "Is the end of the current subtree visible?"
6649 (pos-visible-in-window-p
6650 (save-excursion (org-end-of-subtree t) (point))))
6652 (defun org-first-headline-recenter (&optional N)
6653 "Move cursor to the first headline and recenter the headline.
6654 Optional argument N means put the headline into the Nth line of the window."
6655 (goto-char (point-min))
6656 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6657 (beginning-of-line)
6658 (recenter (prefix-numeric-value N))))
6660 ;;; Saving and restoring visibility
6662 (defun org-outline-overlay-data (&optional use-markers)
6663 "Return a list of the locations of all outline overlays.
6664 These are overlays with the `invisible' property value `outline'.
6665 The return value is a list of cons cells, with start and stop
6666 positions for each overlay.
6667 If USE-MARKERS is set, return the positions as markers."
6668 (let (beg end)
6669 (save-excursion
6670 (save-restriction
6671 (widen)
6672 (delq nil
6673 (mapcar (lambda (o)
6674 (when (eq (overlay-get o 'invisible) 'outline)
6675 (setq beg (overlay-start o)
6676 end (overlay-end o))
6677 (and beg end (> end beg)
6678 (if use-markers
6679 (cons (move-marker (make-marker) beg)
6680 (move-marker (make-marker) end))
6681 (cons beg end)))))
6682 (overlays-in (point-min) (point-max))))))))
6684 (defun org-set-outline-overlay-data (data)
6685 "Create visibility overlays for all positions in DATA.
6686 DATA should have been made by `org-outline-overlay-data'."
6687 (let (o)
6688 (save-excursion
6689 (save-restriction
6690 (widen)
6691 (show-all)
6692 (mapc (lambda (c)
6693 (outline-flag-region (car c) (cdr c) t))
6694 data)))))
6696 ;;; Folding of blocks
6698 (defvar org-hide-block-overlays nil
6699 "Overlays hiding blocks.")
6700 (make-variable-buffer-local 'org-hide-block-overlays)
6702 (defun org-block-map (function &optional start end)
6703 "Call FUNCTION at the head of all source blocks in the current buffer.
6704 Optional arguments START and END can be used to limit the range."
6705 (let ((start (or start (point-min)))
6706 (end (or end (point-max))))
6707 (save-excursion
6708 (goto-char start)
6709 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6710 (save-excursion
6711 (save-match-data
6712 (goto-char (match-beginning 0))
6713 (funcall function)))))))
6715 (defun org-hide-block-toggle-all ()
6716 "Toggle the visibility of all blocks in the current buffer."
6717 (org-block-map #'org-hide-block-toggle))
6719 (defun org-hide-block-all ()
6720 "Fold all blocks in the current buffer."
6721 (interactive)
6722 (org-show-block-all)
6723 (org-block-map #'org-hide-block-toggle-maybe))
6725 (defun org-show-block-all ()
6726 "Unfold all blocks in the current buffer."
6727 (interactive)
6728 (mapc 'delete-overlay org-hide-block-overlays)
6729 (setq org-hide-block-overlays nil))
6731 (defun org-hide-block-toggle-maybe ()
6732 "Toggle visibility of block at point."
6733 (interactive)
6734 (let ((case-fold-search t))
6735 (if (save-excursion
6736 (beginning-of-line 1)
6737 (looking-at org-block-regexp))
6738 (progn (org-hide-block-toggle)
6739 t) ;; to signal that we took action
6740 nil))) ;; to signal that we did not
6742 (defun org-hide-block-toggle (&optional force)
6743 "Toggle the visibility of the current block."
6744 (interactive)
6745 (save-excursion
6746 (beginning-of-line)
6747 (if (re-search-forward org-block-regexp nil t)
6748 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6749 (end (match-end 0)) ;; end of entire body
6751 (if (memq t (mapcar (lambda (overlay)
6752 (eq (overlay-get overlay 'invisible)
6753 'org-hide-block))
6754 (overlays-at start)))
6755 (if (or (not force) (eq force 'off))
6756 (mapc (lambda (ov)
6757 (when (member ov org-hide-block-overlays)
6758 (setq org-hide-block-overlays
6759 (delq ov org-hide-block-overlays)))
6760 (when (eq (overlay-get ov 'invisible)
6761 'org-hide-block)
6762 (delete-overlay ov)))
6763 (overlays-at start)))
6764 (setq ov (make-overlay start end))
6765 (overlay-put ov 'invisible 'org-hide-block)
6766 ;; make the block accessible to isearch
6767 (overlay-put
6768 ov 'isearch-open-invisible
6769 (lambda (ov)
6770 (when (member ov org-hide-block-overlays)
6771 (setq org-hide-block-overlays
6772 (delq ov org-hide-block-overlays)))
6773 (when (eq (overlay-get ov 'invisible)
6774 'org-hide-block)
6775 (delete-overlay ov))))
6776 (push ov org-hide-block-overlays)))
6777 (error "Not looking at a source block"))))
6779 ;; org-tab-after-check-for-cycling-hook
6780 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6781 ;; Remove overlays when changing major mode
6782 (add-hook 'org-mode-hook
6783 (lambda () (org-add-hook 'change-major-mode-hook
6784 'org-show-block-all 'append 'local)))
6786 ;;; Org-goto
6788 (defvar org-goto-window-configuration nil)
6789 (defvar org-goto-marker nil)
6790 (defvar org-goto-map
6791 (let ((map (make-sparse-keymap)))
6792 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6793 (while (setq cmd (pop cmds))
6794 (substitute-key-definition cmd cmd map global-map)))
6795 (suppress-keymap map)
6796 (org-defkey map "\C-m" 'org-goto-ret)
6797 (org-defkey map [(return)] 'org-goto-ret)
6798 (org-defkey map [(left)] 'org-goto-left)
6799 (org-defkey map [(right)] 'org-goto-right)
6800 (org-defkey map [(control ?g)] 'org-goto-quit)
6801 (org-defkey map "\C-i" 'org-cycle)
6802 (org-defkey map [(tab)] 'org-cycle)
6803 (org-defkey map [(down)] 'outline-next-visible-heading)
6804 (org-defkey map [(up)] 'outline-previous-visible-heading)
6805 (if org-goto-auto-isearch
6806 (if (fboundp 'define-key-after)
6807 (define-key-after map [t] 'org-goto-local-auto-isearch)
6808 nil)
6809 (org-defkey map "q" 'org-goto-quit)
6810 (org-defkey map "n" 'outline-next-visible-heading)
6811 (org-defkey map "p" 'outline-previous-visible-heading)
6812 (org-defkey map "f" 'outline-forward-same-level)
6813 (org-defkey map "b" 'outline-backward-same-level)
6814 (org-defkey map "u" 'outline-up-heading))
6815 (org-defkey map "/" 'org-occur)
6816 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6817 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6818 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6819 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6820 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6821 map))
6823 (defconst org-goto-help
6824 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6825 RET=jump to location [Q]uit and return to previous location
6826 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6828 (defvar org-goto-start-pos) ; dynamically scoped parameter
6830 ;; FIXME: Docstring does not mention both interfaces
6831 (defun org-goto (&optional alternative-interface)
6832 "Look up a different location in the current file, keeping current visibility.
6834 When you want look-up or go to a different location in a document, the
6835 fastest way is often to fold the entire buffer and then dive into the tree.
6836 This method has the disadvantage, that the previous location will be folded,
6837 which may not be what you want.
6839 This command works around this by showing a copy of the current buffer
6840 in an indirect buffer, in overview mode. You can dive into the tree in
6841 that copy, use org-occur and incremental search to find a location.
6842 When pressing RET or `Q', the command returns to the original buffer in
6843 which the visibility is still unchanged. After RET it will also jump to
6844 the location selected in the indirect buffer and expose the headline
6845 hierarchy above."
6846 (interactive "P")
6847 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6848 (org-refile-use-outline-path t)
6849 (org-refile-target-verify-function nil)
6850 (interface
6851 (if (not alternative-interface)
6852 org-goto-interface
6853 (if (eq org-goto-interface 'outline)
6854 'outline-path-completion
6855 'outline)))
6856 (org-goto-start-pos (point))
6857 (selected-point
6858 (if (eq interface 'outline)
6859 (car (org-get-location (current-buffer) org-goto-help))
6860 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6861 (org-refile-check-position pa)
6862 (nth 3 pa)))))
6863 (if selected-point
6864 (progn
6865 (org-mark-ring-push org-goto-start-pos)
6866 (goto-char selected-point)
6867 (if (or (outline-invisible-p) (org-invisible-p2))
6868 (org-show-context 'org-goto)))
6869 (message "Quit"))))
6871 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6872 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6873 (defvar org-goto-local-auto-isearch-map) ; defined below
6875 (defun org-get-location (buf help)
6876 "Let the user select a location in the Org-mode buffer BUF.
6877 This function uses a recursive edit. It returns the selected position
6878 or nil."
6879 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6880 (isearch-hide-immediately nil)
6881 (isearch-search-fun-function
6882 (lambda () 'org-goto-local-search-headings))
6883 (org-goto-selected-point org-goto-exit-command)
6884 (pop-up-frames nil)
6885 (special-display-buffer-names nil)
6886 (special-display-regexps nil)
6887 (special-display-function nil))
6888 (save-excursion
6889 (save-window-excursion
6890 (delete-other-windows)
6891 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6892 (org-pop-to-buffer-same-window
6893 (condition-case nil
6894 (make-indirect-buffer (current-buffer) "*org-goto*")
6895 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6896 (with-output-to-temp-buffer "*Help*"
6897 (princ help))
6898 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6899 (setq buffer-read-only nil)
6900 (let ((org-startup-truncated t)
6901 (org-startup-folded nil)
6902 (org-startup-align-all-tables nil))
6903 (org-mode)
6904 (org-overview))
6905 (setq buffer-read-only t)
6906 (if (and (boundp 'org-goto-start-pos)
6907 (integer-or-marker-p org-goto-start-pos))
6908 (let ((org-show-hierarchy-above t)
6909 (org-show-siblings t)
6910 (org-show-following-heading t))
6911 (goto-char org-goto-start-pos)
6912 (and (outline-invisible-p) (org-show-context)))
6913 (goto-char (point-min)))
6914 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6915 (message "Select location and press RET")
6916 (use-local-map org-goto-map)
6917 (recursive-edit)
6919 (kill-buffer "*org-goto*")
6920 (cons org-goto-selected-point org-goto-exit-command)))
6922 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6923 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6924 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6925 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6927 (defun org-goto-local-search-headings (string bound noerror)
6928 "Search and make sure that any matches are in headlines."
6929 (catch 'return
6930 (while (if isearch-forward
6931 (search-forward string bound noerror)
6932 (search-backward string bound noerror))
6933 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6934 (and (member :headline context)
6935 (not (member :tags context))))
6936 (throw 'return (point))))))
6938 (defun org-goto-local-auto-isearch ()
6939 "Start isearch."
6940 (interactive)
6941 (goto-char (point-min))
6942 (let ((keys (this-command-keys)))
6943 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6944 (isearch-mode t)
6945 (isearch-process-search-char (string-to-char keys)))))
6947 (defun org-goto-ret (&optional arg)
6948 "Finish `org-goto' by going to the new location."
6949 (interactive "P")
6950 (setq org-goto-selected-point (point)
6951 org-goto-exit-command 'return)
6952 (throw 'exit nil))
6954 (defun org-goto-left ()
6955 "Finish `org-goto' by going to the new location."
6956 (interactive)
6957 (if (org-at-heading-p)
6958 (progn
6959 (beginning-of-line 1)
6960 (setq org-goto-selected-point (point)
6961 org-goto-exit-command 'left)
6962 (throw 'exit nil))
6963 (error "Not on a heading")))
6965 (defun org-goto-right ()
6966 "Finish `org-goto' by going to the new location."
6967 (interactive)
6968 (if (org-at-heading-p)
6969 (progn
6970 (setq org-goto-selected-point (point)
6971 org-goto-exit-command 'right)
6972 (throw 'exit nil))
6973 (error "Not on a heading")))
6975 (defun org-goto-quit ()
6976 "Finish `org-goto' without cursor motion."
6977 (interactive)
6978 (setq org-goto-selected-point nil)
6979 (setq org-goto-exit-command 'quit)
6980 (throw 'exit nil))
6982 ;;; Indirect buffer display of subtrees
6984 (defvar org-indirect-dedicated-frame nil
6985 "This is the frame being used for indirect tree display.")
6986 (defvar org-last-indirect-buffer nil)
6988 (defun org-tree-to-indirect-buffer (&optional arg)
6989 "Create indirect buffer and narrow it to current subtree.
6990 With numerical prefix ARG, go up to this level and then take that tree.
6991 If ARG is negative, go up that many levels.
6992 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6993 indirect buffer previously made with this command, to avoid proliferation of
6994 indirect buffers. However, when you call the command with a \
6995 \\[universal-argument] prefix, or
6996 when `org-indirect-buffer-display' is `new-frame', the last buffer
6997 is kept so that you can work with several indirect buffers at the same time.
6998 If `org-indirect-buffer-display' is `dedicated-frame', the \
6999 \\[universal-argument] prefix also
7000 requests that a new frame be made for the new buffer, so that the dedicated
7001 frame is not changed."
7002 (interactive "P")
7003 (let ((cbuf (current-buffer))
7004 (cwin (selected-window))
7005 (pos (point))
7006 beg end level heading ibuf)
7007 (save-excursion
7008 (org-back-to-heading t)
7009 (when (numberp arg)
7010 (setq level (org-outline-level))
7011 (if (< arg 0) (setq arg (+ level arg)))
7012 (while (> (setq level (org-outline-level)) arg)
7013 (outline-up-heading 1 t)))
7014 (setq beg (point)
7015 heading (org-get-heading))
7016 (org-end-of-subtree t t)
7017 (if (org-at-heading-p) (backward-char 1))
7018 (setq end (point)))
7019 (if (and (buffer-live-p org-last-indirect-buffer)
7020 (not (eq org-indirect-buffer-display 'new-frame))
7021 (not arg))
7022 (kill-buffer org-last-indirect-buffer))
7023 (setq ibuf (org-get-indirect-buffer cbuf)
7024 org-last-indirect-buffer ibuf)
7025 (cond
7026 ((or (eq org-indirect-buffer-display 'new-frame)
7027 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7028 (select-frame (make-frame))
7029 (delete-other-windows)
7030 (org-pop-to-buffer-same-window ibuf)
7031 (org-set-frame-title heading))
7032 ((eq org-indirect-buffer-display 'dedicated-frame)
7033 (raise-frame
7034 (select-frame (or (and org-indirect-dedicated-frame
7035 (frame-live-p org-indirect-dedicated-frame)
7036 org-indirect-dedicated-frame)
7037 (setq org-indirect-dedicated-frame (make-frame)))))
7038 (delete-other-windows)
7039 (org-pop-to-buffer-same-window ibuf)
7040 (org-set-frame-title (concat "Indirect: " heading)))
7041 ((eq org-indirect-buffer-display 'current-window)
7042 (org-pop-to-buffer-same-window ibuf))
7043 ((eq org-indirect-buffer-display 'other-window)
7044 (pop-to-buffer ibuf))
7045 (t (error "Invalid value")))
7046 (if (featurep 'xemacs)
7047 (save-excursion (org-mode) (turn-on-font-lock)))
7048 (narrow-to-region beg end)
7049 (show-all)
7050 (goto-char pos)
7051 (run-hook-with-args 'org-cycle-hook 'all)
7052 (and (window-live-p cwin) (select-window cwin))))
7054 (defun org-get-indirect-buffer (&optional buffer)
7055 (setq buffer (or buffer (current-buffer)))
7056 (let ((n 1) (base (buffer-name buffer)) bname)
7057 (while (buffer-live-p
7058 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7059 (setq n (1+ n)))
7060 (condition-case nil
7061 (make-indirect-buffer buffer bname 'clone)
7062 (error (make-indirect-buffer buffer bname)))))
7064 (defun org-set-frame-title (title)
7065 "Set the title of the current frame to the string TITLE."
7066 ;; FIXME: how to name a single frame in XEmacs???
7067 (unless (featurep 'xemacs)
7068 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7070 ;;;; Structure editing
7072 ;;; Inserting headlines
7074 (defun org-previous-line-empty-p ()
7075 (save-excursion
7076 (and (not (bobp))
7077 (or (beginning-of-line 0) t)
7078 (save-match-data
7079 (looking-at "[ \t]*$")))))
7081 (defun org-insert-heading (&optional force-heading invisible-ok)
7082 "Insert a new heading or item with same depth at point.
7083 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7084 If point is at the beginning of a headline, insert a sibling before the
7085 current headline. If point is not at the beginning, split the line,
7086 create the new headline with the text in the current line after point
7087 \(but see also the variable `org-M-RET-may-split-line').
7089 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7090 This is important for non-interactive uses of the command."
7091 (interactive "P")
7092 (if (or (= (buffer-size) 0)
7093 (and (not (save-excursion
7094 (and (ignore-errors (org-back-to-heading invisible-ok))
7095 (org-at-heading-p))))
7096 (or force-heading (not (org-in-item-p)))))
7097 (progn
7098 (insert "\n* ")
7099 (run-hooks 'org-insert-heading-hook))
7100 (when (or force-heading (not (org-insert-item)))
7101 (let* ((empty-line-p nil)
7102 (level nil)
7103 (on-heading (org-at-heading-p))
7104 (head (save-excursion
7105 (condition-case nil
7106 (progn
7107 (org-back-to-heading invisible-ok)
7108 (when (and (not on-heading)
7109 (featurep 'org-inlinetask)
7110 (integerp org-inlinetask-min-level)
7111 (>= (length (match-string 0))
7112 org-inlinetask-min-level))
7113 ;; Find a heading level before the inline task
7114 (while (and (setq level (org-up-heading-safe))
7115 (>= level org-inlinetask-min-level)))
7116 (if (org-at-heading-p)
7117 (org-back-to-heading invisible-ok)
7118 (error "This should not happen")))
7119 (setq empty-line-p (org-previous-line-empty-p))
7120 (match-string 0))
7121 (error "*"))))
7122 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7123 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7124 pos hide-previous previous-pos)
7125 (cond
7126 ((and (org-at-heading-p) (bolp)
7127 (or (bobp)
7128 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7129 ;; insert before the current line
7130 (open-line (if blank 2 1)))
7131 ((and (bolp)
7132 (not org-insert-heading-respect-content)
7133 (or (bobp)
7134 (save-excursion
7135 (backward-char 1) (not (outline-invisible-p)))))
7136 ;; insert right here
7137 nil)
7139 ;; somewhere in the line
7140 (save-excursion
7141 (setq previous-pos (point-at-bol))
7142 (end-of-line)
7143 (setq hide-previous (outline-invisible-p)))
7144 (and org-insert-heading-respect-content (org-show-subtree))
7145 (let ((split
7146 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7147 (save-excursion
7148 (let ((p (point)))
7149 (goto-char (point-at-bol))
7150 (and (looking-at org-complex-heading-regexp)
7151 (match-beginning 4)
7152 (> p (match-beginning 4)))))))
7153 tags pos)
7154 (cond
7155 (org-insert-heading-respect-content
7156 (org-end-of-subtree nil t)
7157 (when (featurep 'org-inlinetask)
7158 (while (and (not (eobp))
7159 (looking-at "\\(\\*+\\)[ \t]+")
7160 (>= (length (match-string 1))
7161 org-inlinetask-min-level))
7162 (org-end-of-subtree nil t)))
7163 (or (bolp) (newline))
7164 (or (org-previous-line-empty-p)
7165 (and blank (newline)))
7166 (open-line 1))
7167 ((org-at-heading-p)
7168 (when hide-previous
7169 (show-children)
7170 (org-show-entry))
7171 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7172 (setq tags (and (match-end 2) (match-string 2)))
7173 (and (match-end 1)
7174 (delete-region (match-beginning 1) (match-end 1)))
7175 (setq pos (point-at-bol))
7176 (or split (end-of-line 1))
7177 (delete-horizontal-space)
7178 (if (string-match "\\`\\*+\\'"
7179 (buffer-substring (point-at-bol) (point)))
7180 (insert " "))
7181 (newline (if blank 2 1))
7182 (when tags
7183 (save-excursion
7184 (goto-char pos)
7185 (end-of-line 1)
7186 (insert " " tags)
7187 (org-set-tags nil 'align))))
7189 (or split (end-of-line 1))
7190 (newline (if blank 2 1)))))))
7191 (insert head) (just-one-space)
7192 (setq pos (point))
7193 (end-of-line 1)
7194 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7195 (when (and org-insert-heading-respect-content hide-previous)
7196 (save-excursion
7197 (goto-char previous-pos)
7198 (hide-subtree)))
7199 (run-hooks 'org-insert-heading-hook)))))
7201 (defun org-get-heading (&optional no-tags no-todo)
7202 "Return the heading of the current entry, without the stars.
7203 When NO-TAGS is non-nil, don't include tags.
7204 When NO-TODO is non-nil, don't include TODO keywords."
7205 (save-excursion
7206 (org-back-to-heading t)
7207 (cond
7208 ((and no-tags no-todo)
7209 (looking-at org-complex-heading-regexp)
7210 (match-string 4))
7211 (no-tags
7212 (looking-at (concat org-outline-regexp
7213 "\\(.*?\\)"
7214 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7215 (match-string 1))
7216 (no-todo
7217 (looking-at org-todo-line-regexp)
7218 (match-string 3))
7219 (t (looking-at org-heading-regexp)
7220 (match-string 2)))))
7222 (defun org-heading-components ()
7223 "Return the components of the current heading.
7224 This is a list with the following elements:
7225 - the level as an integer
7226 - the reduced level, different if `org-odd-levels-only' is set.
7227 - the TODO keyword, or nil
7228 - the priority character, like ?A, or nil if no priority is given
7229 - the headline text itself, or the tags string if no headline text
7230 - the tags string, or nil."
7231 (save-excursion
7232 (org-back-to-heading t)
7233 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7234 (list (length (match-string 1))
7235 (org-reduced-level (length (match-string 1)))
7236 (org-match-string-no-properties 2)
7237 (and (match-end 3) (aref (match-string 3) 2))
7238 (org-match-string-no-properties 4)
7239 (org-match-string-no-properties 5)))))
7241 (defun org-get-entry ()
7242 "Get the entry text, after heading, entire subtree."
7243 (save-excursion
7244 (org-back-to-heading t)
7245 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7247 (defun org-insert-heading-after-current ()
7248 "Insert a new heading with same level as current, after current subtree."
7249 (interactive)
7250 (org-back-to-heading)
7251 (org-insert-heading)
7252 (org-move-subtree-down)
7253 (end-of-line 1))
7255 (defun org-insert-heading-respect-content ()
7256 (interactive)
7257 (let ((org-insert-heading-respect-content t))
7258 (org-insert-heading t)))
7260 (defun org-insert-todo-heading-respect-content (&optional force-state)
7261 (interactive "P")
7262 (let ((org-insert-heading-respect-content t))
7263 (org-insert-todo-heading force-state t)))
7265 (defun org-insert-todo-heading (arg &optional force-heading)
7266 "Insert a new heading with the same level and TODO state as current heading.
7267 If the heading has no TODO state, or if the state is DONE, use the first
7268 state (TODO by default). Also with prefix arg, force first state."
7269 (interactive "P")
7270 (when (or force-heading (not (org-insert-item 'checkbox)))
7271 (org-insert-heading force-heading)
7272 (save-excursion
7273 (org-back-to-heading)
7274 (outline-previous-heading)
7275 (looking-at org-todo-line-regexp))
7276 (let*
7277 ((new-mark-x
7278 (if (or arg
7279 (not (match-beginning 2))
7280 (member (match-string 2) org-done-keywords))
7281 (car org-todo-keywords-1)
7282 (match-string 2)))
7283 (new-mark
7285 (run-hook-with-args-until-success
7286 'org-todo-get-default-hook new-mark-x nil)
7287 new-mark-x)))
7288 (beginning-of-line 1)
7289 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7290 (if org-treat-insert-todo-heading-as-state-change
7291 (org-todo new-mark)
7292 (insert new-mark " "))))
7293 (when org-provide-todo-statistics
7294 (org-update-parent-todo-statistics))))
7296 (defun org-insert-subheading (arg)
7297 "Insert a new subheading and demote it.
7298 Works for outline headings and for plain lists alike."
7299 (interactive "P")
7300 (org-insert-heading arg)
7301 (cond
7302 ((org-at-heading-p) (org-do-demote))
7303 ((org-at-item-p) (org-indent-item))))
7305 (defun org-insert-todo-subheading (arg)
7306 "Insert a new subheading with TODO keyword or checkbox and demote it.
7307 Works for outline headings and for plain lists alike."
7308 (interactive "P")
7309 (org-insert-todo-heading arg)
7310 (cond
7311 ((org-at-heading-p) (org-do-demote))
7312 ((org-at-item-p) (org-indent-item))))
7314 ;;; Promotion and Demotion
7316 (defvar org-after-demote-entry-hook nil
7317 "Hook run after an entry has been demoted.
7318 The cursor will be at the beginning of the entry.
7319 When a subtree is being demoted, the hook will be called for each node.")
7321 (defvar org-after-promote-entry-hook nil
7322 "Hook run after an entry has been promoted.
7323 The cursor will be at the beginning of the entry.
7324 When a subtree is being promoted, the hook will be called for each node.")
7326 (defun org-promote-subtree ()
7327 "Promote the entire subtree.
7328 See also `org-promote'."
7329 (interactive)
7330 (save-excursion
7331 (org-with-limited-levels (org-map-tree 'org-promote)))
7332 (org-fix-position-after-promote))
7334 (defun org-demote-subtree ()
7335 "Demote the entire subtree. See `org-demote'.
7336 See also `org-promote'."
7337 (interactive)
7338 (save-excursion
7339 (org-with-limited-levels (org-map-tree 'org-demote)))
7340 (org-fix-position-after-promote))
7343 (defun org-do-promote ()
7344 "Promote the current heading higher up the tree.
7345 If the region is active in `transient-mark-mode', promote all headings
7346 in the region."
7347 (interactive)
7348 (save-excursion
7349 (if (org-region-active-p)
7350 (org-map-region 'org-promote (region-beginning) (region-end))
7351 (org-promote)))
7352 (org-fix-position-after-promote))
7354 (defun org-do-demote ()
7355 "Demote the current heading lower down the tree.
7356 If the region is active in `transient-mark-mode', demote all headings
7357 in the region."
7358 (interactive)
7359 (save-excursion
7360 (if (org-region-active-p)
7361 (org-map-region 'org-demote (region-beginning) (region-end))
7362 (org-demote)))
7363 (org-fix-position-after-promote))
7365 (defun org-fix-position-after-promote ()
7366 "Make sure that after pro/demotion cursor position is right."
7367 (let ((pos (point)))
7368 (when (save-excursion
7369 (beginning-of-line 1)
7370 (looking-at org-todo-line-regexp)
7371 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7372 (cond ((eobp) (insert " "))
7373 ((eolp) (insert " "))
7374 ((equal (char-after) ?\ ) (forward-char 1))))))
7376 (defun org-current-level ()
7377 "Return the level of the current entry, or nil if before the first headline.
7378 The level is the number of stars at the beginning of the headline."
7379 (save-excursion
7380 (org-with-limited-levels
7381 (if (ignore-errors (org-back-to-heading t))
7382 (funcall outline-level)))))
7384 (defun org-get-previous-line-level ()
7385 "Return the outline depth of the last headline before the current line.
7386 Returns 0 for the first headline in the buffer, and nil if before the
7387 first headline."
7388 (let ((current-level (org-current-level))
7389 (prev-level (when (> (line-number-at-pos) 1)
7390 (save-excursion
7391 (beginning-of-line 0)
7392 (org-current-level)))))
7393 (cond ((null current-level) nil) ; Before first headline
7394 ((null prev-level) 0) ; At first headline
7395 (prev-level))))
7397 (defun org-reduced-level (l)
7398 "Compute the effective level of a heading.
7399 This takes into account the setting of `org-odd-levels-only'."
7400 (cond
7401 ((zerop l) 0)
7402 (org-odd-levels-only (1+ (floor (/ l 2))))
7403 (t l)))
7405 (defun org-level-increment ()
7406 "Return the number of stars that will be added or removed at a
7407 time to headlines when structure editing, based on the value of
7408 `org-odd-levels-only'."
7409 (if org-odd-levels-only 2 1))
7411 (defun org-get-valid-level (level &optional change)
7412 "Rectify a level change under the influence of `org-odd-levels-only'
7413 LEVEL is a current level, CHANGE is by how much the level should be
7414 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7415 even level numbers will become the next higher odd number."
7416 (if org-odd-levels-only
7417 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7418 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7419 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7420 (max 1 (+ level (or change 0)))))
7422 (if (boundp 'define-obsolete-function-alias)
7423 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7424 (define-obsolete-function-alias 'org-get-legal-level
7425 'org-get-valid-level)
7426 (define-obsolete-function-alias 'org-get-legal-level
7427 'org-get-valid-level "23.1")))
7429 (defun org-promote ()
7430 "Promote the current heading higher up the tree.
7431 If the region is active in `transient-mark-mode', promote all headings
7432 in the region."
7433 (org-back-to-heading t)
7434 (let* ((level (save-match-data (funcall outline-level)))
7435 (after-change-functions (remove 'flyspell-after-change-function
7436 after-change-functions))
7437 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7438 (diff (abs (- level (length up-head) -1))))
7439 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7440 (replace-match up-head nil t)
7441 ;; Fixup tag positioning
7442 (and org-auto-align-tags (org-set-tags nil t))
7443 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7444 (run-hooks 'org-after-promote-entry-hook)))
7446 (defun org-demote ()
7447 "Demote the current heading lower down the tree.
7448 If the region is active in `transient-mark-mode', demote all headings
7449 in the region."
7450 (org-back-to-heading t)
7451 (let* ((level (save-match-data (funcall outline-level)))
7452 (after-change-functions (remove 'flyspell-after-change-function
7453 after-change-functions))
7454 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7455 (diff (abs (- level (length down-head) -1))))
7456 (replace-match down-head nil t)
7457 ;; Fixup tag positioning
7458 (and org-auto-align-tags (org-set-tags nil t))
7459 (if org-adapt-indentation (org-fixup-indentation diff))
7460 (run-hooks 'org-after-demote-entry-hook)))
7462 (defun org-cycle-level ()
7463 "Cycle the level of an empty headline through possible states.
7464 This goes first to child, then to parent, level, then up the hierarchy.
7465 After top level, it switches back to sibling level."
7466 (interactive)
7467 (let ((org-adapt-indentation nil))
7468 (when (org-point-at-end-of-empty-headline)
7469 (setq this-command 'org-cycle-level) ; Only needed for caching
7470 (let ((cur-level (org-current-level))
7471 (prev-level (org-get-previous-line-level)))
7472 (cond
7473 ;; If first headline in file, promote to top-level.
7474 ((= prev-level 0)
7475 (loop repeat (/ (- cur-level 1) (org-level-increment))
7476 do (org-do-promote)))
7477 ;; If same level as prev, demote one.
7478 ((= prev-level cur-level)
7479 (org-do-demote))
7480 ;; If parent is top-level, promote to top level if not already.
7481 ((= prev-level 1)
7482 (loop repeat (/ (- cur-level 1) (org-level-increment))
7483 do (org-do-promote)))
7484 ;; If top-level, return to prev-level.
7485 ((= cur-level 1)
7486 (loop repeat (/ (- prev-level 1) (org-level-increment))
7487 do (org-do-demote)))
7488 ;; If less than prev-level, promote one.
7489 ((< cur-level prev-level)
7490 (org-do-promote))
7491 ;; If deeper than prev-level, promote until higher than
7492 ;; prev-level.
7493 ((> cur-level prev-level)
7494 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7495 do (org-do-promote))))
7496 t))))
7498 (defun org-map-tree (fun)
7499 "Call FUN for every heading underneath the current one."
7500 (org-back-to-heading)
7501 (let ((level (funcall outline-level)))
7502 (save-excursion
7503 (funcall fun)
7504 (while (and (progn
7505 (outline-next-heading)
7506 (> (funcall outline-level) level))
7507 (not (eobp)))
7508 (funcall fun)))))
7510 (defun org-map-region (fun beg end)
7511 "Call FUN for every heading between BEG and END."
7512 (let ((org-ignore-region t))
7513 (save-excursion
7514 (setq end (copy-marker end))
7515 (goto-char beg)
7516 (if (and (re-search-forward org-outline-regexp-bol nil t)
7517 (< (point) end))
7518 (funcall fun))
7519 (while (and (progn
7520 (outline-next-heading)
7521 (< (point) end))
7522 (not (eobp)))
7523 (funcall fun)))))
7525 (defvar org-property-end-re) ; silence byte-compiler
7526 (defun org-fixup-indentation (diff)
7527 "Change the indentation in the current entry by DIFF.
7528 However, if any line in the current entry has no indentation, or if it
7529 would end up with no indentation after the change, nothing at all is done."
7530 (save-excursion
7531 (let ((end (save-excursion (outline-next-heading)
7532 (point-marker)))
7533 (prohibit (if (> diff 0)
7534 "^\\S-"
7535 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7536 col)
7537 (unless (save-excursion (end-of-line 1)
7538 (re-search-forward prohibit end t))
7539 (while (and (< (point) end)
7540 (re-search-forward "^[ \t]+" end t))
7541 (goto-char (match-end 0))
7542 (setq col (current-column))
7543 (if (< diff 0) (replace-match ""))
7544 (org-indent-to-column (+ diff col))))
7545 (move-marker end nil))))
7547 (defun org-convert-to-odd-levels ()
7548 "Convert an org-mode file with all levels allowed to one with odd levels.
7549 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7550 level 5 etc."
7551 (interactive)
7552 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7553 (let ((outline-level 'org-outline-level)
7554 (org-odd-levels-only nil) n)
7555 (save-excursion
7556 (goto-char (point-min))
7557 (while (re-search-forward "^\\*\\*+ " nil t)
7558 (setq n (- (length (match-string 0)) 2))
7559 (while (>= (setq n (1- n)) 0)
7560 (org-demote))
7561 (end-of-line 1))))))
7563 (defun org-convert-to-oddeven-levels ()
7564 "Convert an org-mode file with only odd levels to one with odd/even levels.
7565 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7566 file contains a section with an even level, conversion would
7567 destroy the structure of the file. An error is signaled in this
7568 case."
7569 (interactive)
7570 (goto-char (point-min))
7571 ;; First check if there are no even levels
7572 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7573 (org-show-context t)
7574 (error "Not all levels are odd in this file. Conversion not possible"))
7575 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7576 (let ((outline-regexp org-outline-regexp)
7577 (outline-level 'org-outline-level)
7578 (org-odd-levels-only nil) n)
7579 (save-excursion
7580 (goto-char (point-min))
7581 (while (re-search-forward "^\\*\\*+ " nil t)
7582 (setq n (/ (1- (length (match-string 0))) 2))
7583 (while (>= (setq n (1- n)) 0)
7584 (org-promote))
7585 (end-of-line 1))))))
7587 (defun org-tr-level (n)
7588 "Make N odd if required."
7589 (if org-odd-levels-only (1+ (/ n 2)) n))
7591 ;;; Vertical tree motion, cutting and pasting of subtrees
7593 (defun org-move-subtree-up (&optional arg)
7594 "Move the current subtree up past ARG headlines of the same level."
7595 (interactive "p")
7596 (org-move-subtree-down (- (prefix-numeric-value arg))))
7598 (defun org-move-subtree-down (&optional arg)
7599 "Move the current subtree down past ARG headlines of the same level."
7600 (interactive "p")
7601 (setq arg (prefix-numeric-value arg))
7602 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7603 'org-get-last-sibling))
7604 (ins-point (make-marker))
7605 (cnt (abs arg))
7606 (col (current-column))
7607 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7608 ;; Select the tree
7609 (org-back-to-heading)
7610 (setq beg0 (point))
7611 (save-excursion
7612 (setq ne-beg (org-back-over-empty-lines))
7613 (setq beg (point)))
7614 (save-match-data
7615 (save-excursion (outline-end-of-heading)
7616 (setq folded (outline-invisible-p)))
7617 (outline-end-of-subtree))
7618 (outline-next-heading)
7619 (setq ne-end (org-back-over-empty-lines))
7620 (setq end (point))
7621 (goto-char beg0)
7622 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7623 ;; include less whitespace
7624 (save-excursion
7625 (goto-char beg)
7626 (forward-line (- ne-beg ne-end))
7627 (setq beg (point))))
7628 ;; Find insertion point, with error handling
7629 (while (> cnt 0)
7630 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7631 (progn (goto-char beg0)
7632 (error "Cannot move past superior level or buffer limit")))
7633 (setq cnt (1- cnt)))
7634 (if (> arg 0)
7635 ;; Moving forward - still need to move over subtree
7636 (progn (org-end-of-subtree t t)
7637 (save-excursion
7638 (org-back-over-empty-lines)
7639 (or (bolp) (newline)))))
7640 (setq ne-ins (org-back-over-empty-lines))
7641 (move-marker ins-point (point))
7642 (setq txt (buffer-substring beg end))
7643 (org-save-markers-in-region beg end)
7644 (delete-region beg end)
7645 (org-remove-empty-overlays-at beg)
7646 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7647 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7648 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7649 (let ((bbb (point)))
7650 (insert-before-markers txt)
7651 (org-reinstall-markers-in-region bbb)
7652 (move-marker ins-point bbb))
7653 (or (bolp) (insert "\n"))
7654 (setq ins-end (point))
7655 (goto-char ins-point)
7656 (org-skip-whitespace)
7657 (when (and (< arg 0)
7658 (org-first-sibling-p)
7659 (> ne-ins ne-beg))
7660 ;; Move whitespace back to beginning
7661 (save-excursion
7662 (goto-char ins-end)
7663 (let ((kill-whole-line t))
7664 (kill-line (- ne-ins ne-beg)) (point)))
7665 (insert (make-string (- ne-ins ne-beg) ?\n)))
7666 (move-marker ins-point nil)
7667 (if folded
7668 (hide-subtree)
7669 (org-show-entry)
7670 (show-children)
7671 (org-cycle-hide-drawers 'children))
7672 (org-clean-visibility-after-subtree-move)
7673 ;; move back to the initial column we were at
7674 (move-to-column col)))
7676 (defvar org-subtree-clip ""
7677 "Clipboard for cut and paste of subtrees.
7678 This is actually only a copy of the kill, because we use the normal kill
7679 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7681 (defvar org-subtree-clip-folded nil
7682 "Was the last copied subtree folded?
7683 This is used to fold the tree back after pasting.")
7685 (defun org-cut-subtree (&optional n)
7686 "Cut the current subtree into the clipboard.
7687 With prefix arg N, cut this many sequential subtrees.
7688 This is a short-hand for marking the subtree and then cutting it."
7689 (interactive "p")
7690 (org-copy-subtree n 'cut))
7692 (defun org-copy-subtree (&optional n cut force-store-markers)
7693 "Cut the current subtree into the clipboard.
7694 With prefix arg N, cut this many sequential subtrees.
7695 This is a short-hand for marking the subtree and then copying it.
7696 If CUT is non-nil, actually cut the subtree.
7697 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7698 of some markers in the region, even if CUT is non-nil. This is
7699 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7700 (interactive "p")
7701 (let (beg end folded (beg0 (point)))
7702 (if (org-called-interactively-p 'any)
7703 (org-back-to-heading nil) ; take what looks like a subtree
7704 (org-back-to-heading t)) ; take what is really there
7705 (org-back-over-empty-lines)
7706 (setq beg (point))
7707 (skip-chars-forward " \t\r\n")
7708 (save-match-data
7709 (save-excursion (outline-end-of-heading)
7710 (setq folded (outline-invisible-p)))
7711 (condition-case nil
7712 (org-forward-same-level (1- n) t)
7713 (error nil))
7714 (org-end-of-subtree t t))
7715 (org-back-over-empty-lines)
7716 (setq end (point))
7717 (goto-char beg0)
7718 (when (> end beg)
7719 (setq org-subtree-clip-folded folded)
7720 (when (or cut force-store-markers)
7721 (org-save-markers-in-region beg end))
7722 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7723 (setq org-subtree-clip (current-kill 0))
7724 (message "%s: Subtree(s) with %d characters"
7725 (if cut "Cut" "Copied")
7726 (length org-subtree-clip)))))
7728 (defun org-paste-subtree (&optional level tree for-yank)
7729 "Paste the clipboard as a subtree, with modification of headline level.
7730 The entire subtree is promoted or demoted in order to match a new headline
7731 level.
7733 If the cursor is at the beginning of a headline, the same level as
7734 that headline is used to paste the tree
7736 If not, the new level is derived from the *visible* headings
7737 before and after the insertion point, and taken to be the inferior headline
7738 level of the two. So if the previous visible heading is level 3 and the
7739 next is level 4 (or vice versa), level 4 will be used for insertion.
7740 This makes sure that the subtree remains an independent subtree and does
7741 not swallow low level entries.
7743 You can also force a different level, either by using a numeric prefix
7744 argument, or by inserting the heading marker by hand. For example, if the
7745 cursor is after \"*****\", then the tree will be shifted to level 5.
7747 If optional TREE is given, use this text instead of the kill ring.
7749 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7750 move back over whitespace before inserting, and move point to the end of
7751 the inserted text when done."
7752 (interactive "P")
7753 (setq tree (or tree (and kill-ring (current-kill 0))))
7754 (unless (org-kill-is-subtree-p tree)
7755 (error "%s"
7756 (substitute-command-keys
7757 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7758 (org-with-limited-levels
7759 (let* ((visp (not (outline-invisible-p)))
7760 (txt tree)
7761 (^re_ "\\(\\*+\\)[ \t]*")
7762 (old-level (if (string-match org-outline-regexp-bol txt)
7763 (- (match-end 0) (match-beginning 0) 1)
7764 -1))
7765 (force-level (cond (level (prefix-numeric-value level))
7766 ((and (looking-at "[ \t]*$")
7767 (string-match
7768 "^\\*+$" (buffer-substring
7769 (point-at-bol) (point))))
7770 (- (match-end 1) (match-beginning 1)))
7771 ((and (bolp)
7772 (looking-at org-outline-regexp))
7773 (- (match-end 0) (point) 1))
7774 (t nil)))
7775 (previous-level (save-excursion
7776 (condition-case nil
7777 (progn
7778 (outline-previous-visible-heading 1)
7779 (if (looking-at ^re_)
7780 (- (match-end 0) (match-beginning 0) 1)
7782 (error 1))))
7783 (next-level (save-excursion
7784 (condition-case nil
7785 (progn
7786 (or (looking-at org-outline-regexp)
7787 (outline-next-visible-heading 1))
7788 (if (looking-at ^re_)
7789 (- (match-end 0) (match-beginning 0) 1)
7791 (error 1))))
7792 (new-level (or force-level (max previous-level next-level)))
7793 (shift (if (or (= old-level -1)
7794 (= new-level -1)
7795 (= old-level new-level))
7797 (- new-level old-level)))
7798 (delta (if (> shift 0) -1 1))
7799 (func (if (> shift 0) 'org-demote 'org-promote))
7800 (org-odd-levels-only nil)
7801 beg end newend)
7802 ;; Remove the forced level indicator
7803 (if force-level
7804 (delete-region (point-at-bol) (point)))
7805 ;; Paste
7806 (beginning-of-line (if (bolp) 1 2))
7807 (unless for-yank (org-back-over-empty-lines))
7808 (setq beg (point))
7809 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7810 (insert-before-markers txt)
7811 (unless (string-match "\n\\'" txt) (insert "\n"))
7812 (setq newend (point))
7813 (org-reinstall-markers-in-region beg)
7814 (setq end (point))
7815 (goto-char beg)
7816 (skip-chars-forward " \t\n\r")
7817 (setq beg (point))
7818 (if (and (outline-invisible-p) visp)
7819 (save-excursion (outline-show-heading)))
7820 ;; Shift if necessary
7821 (unless (= shift 0)
7822 (save-restriction
7823 (narrow-to-region beg end)
7824 (while (not (= shift 0))
7825 (org-map-region func (point-min) (point-max))
7826 (setq shift (+ delta shift)))
7827 (goto-char (point-min))
7828 (setq newend (point-max))))
7829 (when (or (org-called-interactively-p 'interactive) for-yank)
7830 (message "Clipboard pasted as level %d subtree" new-level))
7831 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7832 kill-ring
7833 (eq org-subtree-clip (current-kill 0))
7834 org-subtree-clip-folded)
7835 ;; The tree was folded before it was killed/copied
7836 (hide-subtree))
7837 (and for-yank (goto-char newend)))))
7839 (defun org-kill-is-subtree-p (&optional txt)
7840 "Check if the current kill is an outline subtree, or a set of trees.
7841 Returns nil if kill does not start with a headline, or if the first
7842 headline level is not the largest headline level in the tree.
7843 So this will actually accept several entries of equal levels as well,
7844 which is OK for `org-paste-subtree'.
7845 If optional TXT is given, check this string instead of the current kill."
7846 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7847 (re (org-get-limited-outline-regexp))
7848 (^re (concat "^" re))
7849 (start-level (and kill
7850 (string-match
7851 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7852 kill)
7853 (- (match-end 2) (match-beginning 2) 1)))
7854 (start (1+ (or (match-beginning 2) -1))))
7855 (if (not start-level)
7856 (progn
7857 nil) ;; does not even start with a heading
7858 (catch 'exit
7859 (while (setq start (string-match ^re kill (1+ start)))
7860 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7861 (throw 'exit nil)))
7862 t))))
7864 (defvar org-markers-to-move nil
7865 "Markers that should be moved with a cut-and-paste operation.
7866 Those markers are stored together with their positions relative to
7867 the start of the region.")
7869 (defun org-save-markers-in-region (beg end)
7870 "Check markers in region.
7871 If these markers are between BEG and END, record their position relative
7872 to BEG, so that after moving the block of text, we can put the markers back
7873 into place.
7874 This function gets called just before an entry or tree gets cut from the
7875 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7876 called immediately, to move the markers with the entries."
7877 (setq org-markers-to-move nil)
7878 (when (featurep 'org-clock)
7879 (org-clock-save-markers-for-cut-and-paste beg end))
7880 (when (featurep 'org-agenda)
7881 (org-agenda-save-markers-for-cut-and-paste beg end)))
7883 (defun org-check-and-save-marker (marker beg end)
7884 "Check if MARKER is between BEG and END.
7885 If yes, remember the marker and the distance to BEG."
7886 (when (and (marker-buffer marker)
7887 (equal (marker-buffer marker) (current-buffer)))
7888 (if (and (>= marker beg) (< marker end))
7889 (push (cons marker (- marker beg)) org-markers-to-move))))
7891 (defun org-reinstall-markers-in-region (beg)
7892 "Move all remembered markers to their position relative to BEG."
7893 (mapc (lambda (x)
7894 (move-marker (car x) (+ beg (cdr x))))
7895 org-markers-to-move)
7896 (setq org-markers-to-move nil))
7898 (defun org-narrow-to-subtree ()
7899 "Narrow buffer to the current subtree."
7900 (interactive)
7901 (save-excursion
7902 (save-match-data
7903 (org-with-limited-levels
7904 (narrow-to-region
7905 (progn (org-back-to-heading t) (point))
7906 (progn (org-end-of-subtree t t)
7907 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7908 (point)))))))
7910 (defun org-narrow-to-block ()
7911 "Narrow buffer to the current block."
7912 (interactive)
7913 (let* ((case-fold-search t)
7914 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7915 "^[ \t]*#\\+end_.*")))
7916 (if blockp
7917 (narrow-to-region (car blockp) (cdr blockp))
7918 (error "Not in a block"))))
7920 (eval-when-compile
7921 (defvar org-property-drawer-re))
7923 (defvar org-property-start-re) ;; defined below
7924 (defun org-clone-subtree-with-time-shift (n &optional shift)
7925 "Clone the task (subtree) at point N times.
7926 The clones will be inserted as siblings.
7928 In interactive use, the user will be prompted for the number of
7929 clones to be produced, and for a time SHIFT, which may be a
7930 repeater as used in time stamps, for example `+3d'.
7932 When a valid repeater is given and the entry contains any time
7933 stamps, the clones will become a sequence in time, with time
7934 stamps in the subtree shifted for each clone produced. If SHIFT
7935 is nil or the empty string, time stamps will be left alone. The
7936 ID property of the original subtree is removed.
7938 If the original subtree did contain time stamps with a repeater,
7939 the following will happen:
7940 - the repeater will be removed in each clone
7941 - an additional clone will be produced, with the current, unshifted
7942 date(s) in the entry.
7943 - the original entry will be placed *after* all the clones, with
7944 repeater intact.
7945 - the start days in the repeater in the original entry will be shifted
7946 to past the last clone.
7947 In this way you can spell out a number of instances of a repeating task,
7948 and still retain the repeater to cover future instances of the task."
7949 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7950 (let (beg end template task idprop
7951 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7952 (drawer-re org-drawer-regexp))
7953 (if (not (and (integerp n) (> n 0)))
7954 (error "Invalid number of replications %s" n))
7955 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7956 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7957 shift)))
7958 (error "Invalid shift specification %s" shift))
7959 (when doshift
7960 (setq shift-n (string-to-number (match-string 1 shift))
7961 shift-what (cdr (assoc (match-string 2 shift)
7962 '(("d" . day) ("w" . week)
7963 ("m" . month) ("y" . year))))))
7964 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7965 (setq nmin 1 nmax n)
7966 (org-back-to-heading t)
7967 (setq beg (point))
7968 (setq idprop (org-entry-get nil "ID"))
7969 (org-end-of-subtree t t)
7970 (or (bolp) (insert "\n"))
7971 (setq end (point))
7972 (setq template (buffer-substring beg end))
7973 (when (and doshift
7974 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7975 (delete-region beg end)
7976 (setq end beg)
7977 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7978 (goto-char end)
7979 (loop for n from nmin to nmax do
7980 ;; prepare clone
7981 (with-temp-buffer
7982 (insert template)
7983 (org-mode)
7984 (goto-char (point-min))
7985 (org-show-subtree)
7986 (and idprop (if org-clone-delete-id
7987 (org-entry-delete nil "ID")
7988 (org-id-get-create t)))
7989 (unless (= n 0)
7990 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7991 (kill-whole-line))
7992 (goto-char (point-min))
7993 (while (re-search-forward drawer-re nil t)
7994 (mapc (lambda (d)
7995 (org-remove-empty-drawer-at d (point))) org-drawers)))
7996 (goto-char (point-min))
7997 (when doshift
7998 (while (re-search-forward org-ts-regexp-both nil t)
7999 (org-timestamp-change (* n shift-n) shift-what))
8000 (unless (= n n-no-remove)
8001 (goto-char (point-min))
8002 (while (re-search-forward org-ts-regexp nil t)
8003 (save-excursion
8004 (goto-char (match-beginning 0))
8005 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8006 (delete-region (match-beginning 1) (match-end 1)))))))
8007 (setq task (buffer-string)))
8008 (insert task))
8009 (goto-char beg)))
8011 ;;; Outline Sorting
8013 (defun org-sort (with-case)
8014 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8015 Optional argument WITH-CASE means sort case-sensitively."
8016 (interactive "P")
8017 (cond
8018 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8019 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8021 (org-call-with-arg 'org-sort-entries with-case))))
8023 (defun org-sort-remove-invisible (s)
8024 (remove-text-properties 0 (length s) org-rm-props s)
8025 (while (string-match org-bracket-link-regexp s)
8026 (setq s (replace-match (if (match-end 2)
8027 (match-string 3 s)
8028 (match-string 1 s)) t t s)))
8031 (defvar org-priority-regexp) ; defined later in the file
8033 (defvar org-after-sorting-entries-or-items-hook nil
8034 "Hook that is run after a bunch of entries or items have been sorted.
8035 When children are sorted, the cursor is in the parent line when this
8036 hook gets called. When a region or a plain list is sorted, the cursor
8037 will be in the first entry of the sorted region/list.")
8039 (defun org-sort-entries
8040 (&optional with-case sorting-type getkey-func compare-func property)
8041 "Sort entries on a certain level of an outline tree.
8042 If there is an active region, the entries in the region are sorted.
8043 Else, if the cursor is before the first entry, sort the top-level items.
8044 Else, the children of the entry at point are sorted.
8046 Sorting can be alphabetically, numerically, by date/time as given by
8047 a time stamp, by a property or by priority.
8049 The command prompts for the sorting type unless it has been given to the
8050 function through the SORTING-TYPE argument, which needs to be a character,
8051 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8052 precise meaning of each character:
8054 n Numerically, by converting the beginning of the entry/item to a number.
8055 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8056 t By date/time, either the first active time stamp in the entry, or, if
8057 none exist, by the first inactive one.
8058 s By the scheduled date/time.
8059 d By deadline date/time.
8060 c By creation time, which is assumed to be the first inactive time stamp
8061 at the beginning of a line.
8062 p By priority according to the cookie.
8063 r By the value of a property.
8065 Capital letters will reverse the sort order.
8067 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8068 called with point at the beginning of the record. It must return either
8069 a string or a number that should serve as the sorting key for that record.
8071 Comparing entries ignores case by default. However, with an optional argument
8072 WITH-CASE, the sorting considers case as well."
8073 (interactive "P")
8074 (let ((case-func (if with-case 'identity 'downcase))
8075 start beg end stars re re2
8076 txt what tmp)
8077 ;; Find beginning and end of region to sort
8078 (cond
8079 ((org-region-active-p)
8080 ;; we will sort the region
8081 (setq end (region-end)
8082 what "region")
8083 (goto-char (region-beginning))
8084 (if (not (org-at-heading-p)) (outline-next-heading))
8085 (setq start (point)))
8086 ((or (org-at-heading-p)
8087 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8088 ;; we will sort the children of the current headline
8089 (org-back-to-heading)
8090 (setq start (point)
8091 end (progn (org-end-of-subtree t t)
8092 (or (bolp) (insert "\n"))
8093 (org-back-over-empty-lines)
8094 (point))
8095 what "children")
8096 (goto-char start)
8097 (show-subtree)
8098 (outline-next-heading))
8100 ;; we will sort the top-level entries in this file
8101 (goto-char (point-min))
8102 (or (org-at-heading-p) (outline-next-heading))
8103 (setq start (point))
8104 (goto-char (point-max))
8105 (beginning-of-line 1)
8106 (when (looking-at ".*?\\S-")
8107 ;; File ends in a non-white line
8108 (end-of-line 1)
8109 (insert "\n"))
8110 (setq end (point-max))
8111 (setq what "top-level")
8112 (goto-char start)
8113 (show-all)))
8115 (setq beg (point))
8116 (if (>= beg end) (error "Nothing to sort"))
8118 (looking-at "\\(\\*+\\)")
8119 (setq stars (match-string 1)
8120 re (concat "^" (regexp-quote stars) " +")
8121 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8122 txt (buffer-substring beg end))
8123 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8124 (if (and (not (equal stars "*")) (string-match re2 txt))
8125 (error "Region to sort contains a level above the first entry"))
8127 (unless sorting-type
8128 (message
8129 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8130 [t]ime [s]cheduled [d]eadline [c]reated
8131 A/N/T/S/D/C/P/O/F means reversed:"
8132 what)
8133 (setq sorting-type (read-char-exclusive))
8135 (and (= (downcase sorting-type) ?f)
8136 (setq getkey-func
8137 (org-icompleting-read "Sort using function: "
8138 obarray 'fboundp t nil nil))
8139 (setq getkey-func (intern getkey-func)))
8141 (and (= (downcase sorting-type) ?r)
8142 (setq property
8143 (org-icompleting-read "Property: "
8144 (mapcar 'list (org-buffer-property-keys t))
8145 nil t))))
8147 (message "Sorting entries...")
8149 (save-restriction
8150 (narrow-to-region start end)
8151 (let ((dcst (downcase sorting-type))
8152 (case-fold-search nil)
8153 (now (current-time)))
8154 (sort-subr
8155 (/= dcst sorting-type)
8156 ;; This function moves to the beginning character of the "record" to
8157 ;; be sorted.
8158 (lambda nil
8159 (if (re-search-forward re nil t)
8160 (goto-char (match-beginning 0))
8161 (goto-char (point-max))))
8162 ;; This function moves to the last character of the "record" being
8163 ;; sorted.
8164 (lambda nil
8165 (save-match-data
8166 (condition-case nil
8167 (outline-forward-same-level 1)
8168 (error
8169 (goto-char (point-max))))))
8170 ;; This function returns the value that gets sorted against.
8171 (lambda nil
8172 (cond
8173 ((= dcst ?n)
8174 (if (looking-at org-complex-heading-regexp)
8175 (string-to-number (match-string 4))
8176 nil))
8177 ((= dcst ?a)
8178 (if (looking-at org-complex-heading-regexp)
8179 (funcall case-func (match-string 4))
8180 nil))
8181 ((= dcst ?t)
8182 (let ((end (save-excursion (outline-next-heading) (point))))
8183 (if (or (re-search-forward org-ts-regexp end t)
8184 (re-search-forward org-ts-regexp-both end t))
8185 (org-time-string-to-seconds (match-string 0))
8186 (org-float-time now))))
8187 ((= dcst ?c)
8188 (let ((end (save-excursion (outline-next-heading) (point))))
8189 (if (re-search-forward
8190 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8191 end t)
8192 (org-time-string-to-seconds (match-string 0))
8193 (org-float-time now))))
8194 ((= dcst ?s)
8195 (let ((end (save-excursion (outline-next-heading) (point))))
8196 (if (re-search-forward org-scheduled-time-regexp end t)
8197 (org-time-string-to-seconds (match-string 1))
8198 (org-float-time now))))
8199 ((= dcst ?d)
8200 (let ((end (save-excursion (outline-next-heading) (point))))
8201 (if (re-search-forward org-deadline-time-regexp end t)
8202 (org-time-string-to-seconds (match-string 1))
8203 (org-float-time now))))
8204 ((= dcst ?p)
8205 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8206 (string-to-char (match-string 2))
8207 org-default-priority))
8208 ((= dcst ?r)
8209 (or (org-entry-get nil property) ""))
8210 ((= dcst ?o)
8211 (if (looking-at org-complex-heading-regexp)
8212 (- 9999 (length (member (match-string 2)
8213 org-todo-keywords-1)))))
8214 ((= dcst ?f)
8215 (if getkey-func
8216 (progn
8217 (setq tmp (funcall getkey-func))
8218 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8219 tmp)
8220 (error "Invalid key function `%s'" getkey-func)))
8221 (t (error "Invalid sorting type `%c'" sorting-type))))
8223 (cond
8224 ((= dcst ?a) 'string<)
8225 ((= dcst ?f) compare-func)
8226 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8227 (t nil)))))
8228 (run-hooks 'org-after-sorting-entries-or-items-hook)
8229 (message "Sorting entries...done")))
8231 (defun org-do-sort (table what &optional with-case sorting-type)
8232 "Sort TABLE of WHAT according to SORTING-TYPE.
8233 The user will be prompted for the SORTING-TYPE if the call to this
8234 function does not specify it. WHAT is only for the prompt, to indicate
8235 what is being sorted. The sorting key will be extracted from
8236 the car of the elements of the table.
8237 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8238 (unless sorting-type
8239 (message
8240 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8241 what)
8242 (setq sorting-type (read-char-exclusive)))
8243 (let ((dcst (downcase sorting-type))
8244 extractfun comparefun)
8245 ;; Define the appropriate functions
8246 (cond
8247 ((= dcst ?n)
8248 (setq extractfun 'string-to-number
8249 comparefun (if (= dcst sorting-type) '< '>)))
8250 ((= dcst ?a)
8251 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8252 (lambda(x) (downcase (org-sort-remove-invisible x))))
8253 comparefun (if (= dcst sorting-type)
8254 'string<
8255 (lambda (a b) (and (not (string< a b))
8256 (not (string= a b)))))))
8257 ((= dcst ?t)
8258 (setq extractfun
8259 (lambda (x)
8260 (if (or (string-match org-ts-regexp x)
8261 (string-match org-ts-regexp-both x))
8262 (org-float-time
8263 (org-time-string-to-time (match-string 0 x)))
8265 comparefun (if (= dcst sorting-type) '< '>)))
8266 (t (error "Invalid sorting type `%c'" sorting-type)))
8268 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8269 table)
8270 (lambda (a b) (funcall comparefun (car a) (car b))))))
8273 ;;; The orgstruct minor mode
8275 ;; Define a minor mode which can be used in other modes in order to
8276 ;; integrate the org-mode structure editing commands.
8278 ;; This is really a hack, because the org-mode structure commands use
8279 ;; keys which normally belong to the major mode. Here is how it
8280 ;; works: The minor mode defines all the keys necessary to operate the
8281 ;; structure commands, but wraps the commands into a function which
8282 ;; tests if the cursor is currently at a headline or a plain list
8283 ;; item. If that is the case, the structure command is used,
8284 ;; temporarily setting many Org-mode variables like regular
8285 ;; expressions for filling etc. However, when any of those keys is
8286 ;; used at a different location, function uses `key-binding' to look
8287 ;; up if the key has an associated command in another currently active
8288 ;; keymap (minor modes, major mode, global), and executes that
8289 ;; command. There might be problems if any of the keys is otherwise
8290 ;; used as a prefix key.
8292 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8293 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8294 ;; addresses this by checking explicitly for both bindings.
8296 (defvar orgstruct-mode-map (make-sparse-keymap)
8297 "Keymap for the minor `orgstruct-mode'.")
8299 (defvar org-local-vars nil
8300 "List of local variables, for use by `orgstruct-mode'.")
8302 ;;;###autoload
8303 (define-minor-mode orgstruct-mode
8304 "Toggle the minor mode `orgstruct-mode'.
8305 This mode is for using Org-mode structure commands in other
8306 modes. The following keys behave as if Org-mode were active, if
8307 the cursor is on a headline, or on a plain list item (both as
8308 defined by Org-mode).
8310 M-up Move entry/item up
8311 M-down Move entry/item down
8312 M-left Promote
8313 M-right Demote
8314 M-S-up Move entry/item up
8315 M-S-down Move entry/item down
8316 M-S-left Promote subtree
8317 M-S-right Demote subtree
8318 M-q Fill paragraph and items like in Org-mode
8319 C-c ^ Sort entries
8320 C-c - Cycle list bullet
8321 TAB Cycle item visibility
8322 M-RET Insert new heading/item
8323 S-M-RET Insert new TODO heading / Checkbox item
8324 C-c C-c Set tags / toggle checkbox"
8325 nil " OrgStruct" nil
8326 (org-load-modules-maybe)
8327 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8329 ;;;###autoload
8330 (defun turn-on-orgstruct ()
8331 "Unconditionally turn on `orgstruct-mode'."
8332 (orgstruct-mode 1))
8334 (defun orgstruct++-mode (&optional arg)
8335 "Toggle `orgstruct-mode', the enhanced version of it.
8336 In addition to setting orgstruct-mode, this also exports all indentation
8337 and autofilling variables from org-mode into the buffer. It will also
8338 recognize item context in multiline items.
8339 Note that turning off orgstruct-mode will *not* remove the
8340 indentation/paragraph settings. This can only be done by refreshing the
8341 major mode, for example with \\[normal-mode]."
8342 (interactive "P")
8343 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8344 (if (< arg 1)
8345 (orgstruct-mode -1)
8346 (orgstruct-mode 1)
8347 (let (var val)
8348 (mapc
8349 (lambda (x)
8350 (when (string-match
8351 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8352 (symbol-name (car x)))
8353 (setq var (car x) val (nth 1 x))
8354 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8355 org-local-vars)
8356 (org-set-local 'orgstruct-is-++ t))))
8358 (defvar orgstruct-is-++ nil
8359 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8360 (make-variable-buffer-local 'orgstruct-is-++)
8362 ;;;###autoload
8363 (defun turn-on-orgstruct++ ()
8364 "Unconditionally turn on `orgstruct++-mode'."
8365 (orgstruct++-mode 1))
8367 (defun orgstruct-error ()
8368 "Error when there is no default binding for a structure key."
8369 (interactive)
8370 (error "This key has no function outside structure elements"))
8372 (defun orgstruct-setup ()
8373 "Setup orgstruct keymaps."
8374 (let ((nfunc 0)
8375 (bindings
8376 (list
8377 '([(meta up)] org-metaup)
8378 '([(meta down)] org-metadown)
8379 '([(meta left)] org-metaleft)
8380 '([(meta right)] org-metaright)
8381 '([(meta shift up)] org-shiftmetaup)
8382 '([(meta shift down)] org-shiftmetadown)
8383 '([(meta shift left)] org-shiftmetaleft)
8384 '([(meta shift right)] org-shiftmetaright)
8385 '([?\e (up)] org-metaup)
8386 '([?\e (down)] org-metadown)
8387 '([?\e (left)] org-metaleft)
8388 '([?\e (right)] org-metaright)
8389 '([?\e (shift up)] org-shiftmetaup)
8390 '([?\e (shift down)] org-shiftmetadown)
8391 '([?\e (shift left)] org-shiftmetaleft)
8392 '([?\e (shift right)] org-shiftmetaright)
8393 '([(shift up)] org-shiftup)
8394 '([(shift down)] org-shiftdown)
8395 '([(shift left)] org-shiftleft)
8396 '([(shift right)] org-shiftright)
8397 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8398 '("\M-q" fill-paragraph)
8399 '("\C-c^" org-sort)
8400 '("\C-c-" org-cycle-list-bullet)))
8401 elt key fun cmd)
8402 (while (setq elt (pop bindings))
8403 (setq nfunc (1+ nfunc))
8404 (setq key (org-key (car elt))
8405 fun (nth 1 elt)
8406 cmd (orgstruct-make-binding fun nfunc key))
8407 (org-defkey orgstruct-mode-map key cmd))
8409 ;; Special treatment needed for TAB and RET
8410 (org-defkey orgstruct-mode-map [(tab)]
8411 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8412 (org-defkey orgstruct-mode-map "\C-i"
8413 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8415 (org-defkey orgstruct-mode-map "\M-\C-m"
8416 (orgstruct-make-binding 'org-insert-heading 105
8417 "\M-\C-m" [(meta return)]))
8418 (org-defkey orgstruct-mode-map [(meta return)]
8419 (orgstruct-make-binding 'org-insert-heading 106
8420 [(meta return)] "\M-\C-m"))
8422 (org-defkey orgstruct-mode-map [(shift meta return)]
8423 (orgstruct-make-binding 'org-insert-todo-heading 107
8424 [(meta return)] "\M-\C-m"))
8426 (org-defkey orgstruct-mode-map "\e\C-m"
8427 (orgstruct-make-binding 'org-insert-heading 108
8428 "\e\C-m" [?\e (return)]))
8429 (org-defkey orgstruct-mode-map [?\e (return)]
8430 (orgstruct-make-binding 'org-insert-heading 109
8431 [?\e (return)] "\e\C-m"))
8432 (org-defkey orgstruct-mode-map [?\e (shift return)]
8433 (orgstruct-make-binding 'org-insert-todo-heading 110
8434 [?\e (return)] "\e\C-m"))
8436 (unless org-local-vars
8437 (setq org-local-vars (org-get-local-variables)))
8441 (defun orgstruct-make-binding (fun n &rest keys)
8442 "Create a function for binding in the structure minor mode.
8443 FUN is the command to call inside a table. N is used to create a unique
8444 command name. KEYS are keys that should be checked in for a command
8445 to execute outside of tables."
8446 (eval
8447 (list 'defun
8448 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8449 '(arg)
8450 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8451 "Outside of structure, run the binding of `"
8452 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8453 "'.")
8454 '(interactive "p")
8455 (list 'if
8456 `(org-context-p 'headline 'item
8457 (and orgstruct-is-++
8458 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8459 'item-body))
8460 (list 'org-run-like-in-org-mode (list 'quote fun))
8461 (list 'let '(orgstruct-mode)
8462 (list 'call-interactively
8463 (append '(or)
8464 (mapcar (lambda (k)
8465 (list 'key-binding k))
8466 keys)
8467 '('orgstruct-error))))))))
8469 (defun org-context-p (&rest contexts)
8470 "Check if local context is any of CONTEXTS.
8471 Possible values in the list of contexts are `table', `headline', and `item'."
8472 (let ((pos (point)))
8473 (goto-char (point-at-bol))
8474 (prog1 (or (and (memq 'table contexts)
8475 (looking-at "[ \t]*|"))
8476 (and (memq 'headline contexts)
8477 (looking-at org-outline-regexp))
8478 (and (memq 'item contexts)
8479 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8480 (and (memq 'item-body contexts)
8481 (org-in-item-p)))
8482 (goto-char pos))))
8484 (defun org-get-local-variables ()
8485 "Return a list of all local variables in an org-mode buffer."
8486 (let (varlist)
8487 (with-current-buffer (get-buffer-create "*Org tmp*")
8488 (erase-buffer)
8489 (org-mode)
8490 (setq varlist (buffer-local-variables)))
8491 (kill-buffer "*Org tmp*")
8492 (delq nil
8493 (mapcar
8494 (lambda (x)
8495 (setq x
8496 (if (symbolp x)
8497 (list x)
8498 (list (car x) (list 'quote (cdr x)))))
8499 (if (string-match
8500 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8501 (symbol-name (car x)))
8502 x nil))
8503 varlist))))
8505 (defun org-clone-local-variables (from-buffer &optional regexp)
8506 "Clone local variables from FROM-BUFFER.
8507 Optional argument REGEXP selects variables to clone."
8508 (mapc
8509 (lambda (pair)
8510 (and (symbolp (car pair))
8511 (or (null regexp)
8512 (string-match regexp (symbol-name (car pair))))
8513 (set (make-local-variable (car pair))
8514 (cdr pair))))
8515 (buffer-local-variables from-buffer)))
8517 ;;;###autoload
8518 (defun org-run-like-in-org-mode (cmd)
8519 "Run a command, pretending that the current buffer is in Org-mode.
8520 This will temporarily bind local variables that are typically bound in
8521 Org-mode to the values they have in Org-mode, and then interactively
8522 call CMD."
8523 (org-load-modules-maybe)
8524 (unless org-local-vars
8525 (setq org-local-vars (org-get-local-variables)))
8526 (eval (list 'let org-local-vars
8527 (list 'call-interactively (list 'quote cmd)))))
8529 ;;;; Archiving
8531 (defun org-get-category (&optional pos force-refresh)
8532 "Get the category applying to position POS."
8533 (save-match-data
8534 (if force-refresh (org-refresh-category-properties))
8535 (let ((pos (or pos (point))))
8536 (or (get-text-property pos 'org-category)
8537 (progn (org-refresh-category-properties)
8538 (get-text-property pos 'org-category))))))
8540 (defun org-refresh-category-properties ()
8541 "Refresh category text properties in the buffer."
8542 (let ((def-cat (cond
8543 ((null org-category)
8544 (if buffer-file-name
8545 (file-name-sans-extension
8546 (file-name-nondirectory buffer-file-name))
8547 "???"))
8548 ((symbolp org-category) (symbol-name org-category))
8549 (t org-category)))
8550 beg end cat pos optionp)
8551 (org-unmodified
8552 (save-excursion
8553 (save-restriction
8554 (widen)
8555 (goto-char (point-min))
8556 (put-text-property (point) (point-max) 'org-category def-cat)
8557 (while (re-search-forward
8558 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8559 (setq pos (match-end 0)
8560 optionp (equal (char-after (match-beginning 0)) ?#)
8561 cat (org-trim (match-string 2)))
8562 (if optionp
8563 (setq beg (point-at-bol) end (point-max))
8564 (org-back-to-heading t)
8565 (setq beg (point) end (org-end-of-subtree t t)))
8566 (put-text-property beg end 'org-category cat)
8567 (put-text-property beg end 'org-category-position beg)
8568 (goto-char pos)))))))
8571 ;;;; Link Stuff
8573 ;;; Link abbreviations
8575 (defun org-link-expand-abbrev (link)
8576 "Apply replacements as defined in `org-link-abbrev-alist."
8577 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8578 (let* ((key (match-string 1 link))
8579 (as (or (assoc key org-link-abbrev-alist-local)
8580 (assoc key org-link-abbrev-alist)))
8581 (tag (and (match-end 2) (match-string 3 link)))
8582 rpl)
8583 (if (not as)
8584 link
8585 (setq rpl (cdr as))
8586 (cond
8587 ((symbolp rpl) (funcall rpl tag))
8588 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8589 ((string-match "%h" rpl)
8590 (replace-match (url-hexify-string (or tag "")) t t rpl))
8591 (t (concat rpl tag)))))
8592 link))
8594 ;;; Storing and inserting links
8596 (defvar org-insert-link-history nil
8597 "Minibuffer history for links inserted with `org-insert-link'.")
8599 (defvar org-stored-links nil
8600 "Contains the links stored with `org-store-link'.")
8602 (defvar org-store-link-plist nil
8603 "Plist with info about the most recently link created with `org-store-link'.")
8605 (defvar org-link-protocols nil
8606 "Link protocols added to Org-mode using `org-add-link-type'.")
8608 (defvar org-store-link-functions nil
8609 "List of functions that are called to create and store a link.
8610 Each function will be called in turn until one returns a non-nil
8611 value. Each function should check if it is responsible for creating
8612 this link (for example by looking at the major mode).
8613 If not, it must exit and return nil.
8614 If yes, it should return a non-nil value after a calling
8615 `org-store-link-props' with a list of properties and values.
8616 Special properties are:
8618 :type The link prefix, like \"http\". This must be given.
8619 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8620 This is obligatory as well.
8621 :description Optional default description for the second pair
8622 of brackets in an Org-mode link. The user can still change
8623 this when inserting this link into an Org-mode buffer.
8625 In addition to these, any additional properties can be specified
8626 and then used in remember templates.")
8628 (defun org-add-link-type (type &optional follow export)
8629 "Add TYPE to the list of `org-link-types'.
8630 Re-compute all regular expressions depending on `org-link-types'
8632 FOLLOW and EXPORT are two functions.
8634 FOLLOW should take the link path as the single argument and do whatever
8635 is necessary to follow the link, for example find a file or display
8636 a mail message.
8638 EXPORT should format the link path for export to one of the export formats.
8639 It should be a function accepting three arguments:
8641 path the path of the link, the text after the prefix (like \"http:\")
8642 desc the description of the link, if any, or a description added by
8643 org-export-normalize-links if there is none
8644 format the export format, a symbol like `html' or `latex' or `ascii'..
8646 The function may use the FORMAT information to return different values
8647 depending on the format. The return value will be put literally into
8648 the exported file. If the return value is nil, this means Org should
8649 do what it normally does with links which do not have EXPORT defined.
8651 Org-mode has a built-in default for exporting links. If you are happy with
8652 this default, there is no need to define an export function for the link
8653 type. For a simple example of an export function, see `org-bbdb.el'."
8654 (add-to-list 'org-link-types type t)
8655 (org-make-link-regexps)
8656 (if (assoc type org-link-protocols)
8657 (setcdr (assoc type org-link-protocols) (list follow export))
8658 (push (list type follow export) org-link-protocols)))
8660 (defvar org-agenda-buffer-name)
8662 ;;;###autoload
8663 (defun org-store-link (arg)
8664 "\\<org-mode-map>Store an org-link to the current location.
8665 This link is added to `org-stored-links' and can later be inserted
8666 into an org-buffer with \\[org-insert-link].
8668 For some link types, a prefix arg is interpreted:
8669 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8670 For file links, arg negates `org-context-in-file-links'."
8671 (interactive "P")
8672 (org-load-modules-maybe)
8673 (setq org-store-link-plist nil) ; reset
8674 (org-with-limited-levels
8675 (let (link cpltxt desc description search txt custom-id agenda-link)
8676 (cond
8678 ((run-hook-with-args-until-success 'org-store-link-functions)
8679 (setq link (plist-get org-store-link-plist :link)
8680 desc (or (plist-get org-store-link-plist :description) link)))
8682 ((org-src-edit-buffer-p)
8683 (let (label gc)
8684 (while (or (not label)
8685 (save-excursion
8686 (save-restriction
8687 (widen)
8688 (goto-char (point-min))
8689 (re-search-forward
8690 (regexp-quote (format org-coderef-label-format label))
8691 nil t))))
8692 (when label (message "Label exists already") (sit-for 2))
8693 (setq label (read-string "Code line label: " label)))
8694 (end-of-line 1)
8695 (setq link (format org-coderef-label-format label))
8696 (setq gc (- 79 (length link)))
8697 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8698 (insert link)
8699 (setq link (concat "(" label ")") desc nil)))
8701 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8702 ;; We are in the agenda, link to referenced location
8703 (let ((m (or (get-text-property (point) 'org-hd-marker)
8704 (get-text-property (point) 'org-marker))))
8705 (when m
8706 (org-with-point-at m
8707 (setq agenda-link
8708 (if (org-called-interactively-p 'any)
8709 (call-interactively 'org-store-link)
8710 (org-store-link nil)))))))
8712 ((eq major-mode 'calendar-mode)
8713 (let ((cd (calendar-cursor-to-date)))
8714 (setq link
8715 (format-time-string
8716 (car org-time-stamp-formats)
8717 (apply 'encode-time
8718 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8719 nil nil nil))))
8720 (org-store-link-props :type "calendar" :date cd)))
8722 ((eq major-mode 'w3-mode)
8723 (setq cpltxt (if (and (buffer-name)
8724 (not (string-match "Untitled" (buffer-name))))
8725 (buffer-name)
8726 (url-view-url t))
8727 link (org-make-link (url-view-url t)))
8728 (org-store-link-props :type "w3" :url (url-view-url t)))
8730 ((eq major-mode 'w3m-mode)
8731 (setq cpltxt (or w3m-current-title w3m-current-url)
8732 link (org-make-link w3m-current-url))
8733 (org-store-link-props :type "w3m" :url (url-view-url t)))
8735 ((setq search (run-hook-with-args-until-success
8736 'org-create-file-search-functions))
8737 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8738 "::" search))
8739 (setq cpltxt (or description link)))
8741 ((eq major-mode 'image-mode)
8742 (setq cpltxt (concat "file:"
8743 (abbreviate-file-name buffer-file-name))
8744 link (org-make-link cpltxt))
8745 (org-store-link-props :type "image" :file buffer-file-name))
8747 ((eq major-mode 'dired-mode)
8748 ;; link to the file in the current line
8749 (let ((file (dired-get-filename nil t)))
8750 (setq file (if file
8751 (abbreviate-file-name
8752 (expand-file-name (dired-get-filename nil t)))
8753 ;; otherwise, no file so use current directory.
8754 default-directory))
8755 (setq cpltxt (concat "file:" file)
8756 link (org-make-link cpltxt))))
8758 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8759 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8760 (cond
8761 ((org-in-regexp "<<\\(.*?\\)>>")
8762 (setq cpltxt
8763 (concat "file:"
8764 (abbreviate-file-name
8765 (buffer-file-name (buffer-base-buffer)))
8766 "::" (match-string 1))
8767 link (org-make-link cpltxt)))
8768 ((and (featurep 'org-id)
8769 (or (eq org-link-to-org-use-id t)
8770 (and (eq org-link-to-org-use-id 'create-if-interactive)
8771 (org-called-interactively-p 'any))
8772 (and (eq org-link-to-org-use-id
8773 'create-if-interactive-and-no-custom-id)
8774 (org-called-interactively-p 'any)
8775 (not custom-id))
8776 (and org-link-to-org-use-id
8777 (org-entry-get nil "ID"))))
8778 ;; We can make a link using the ID.
8779 (setq link (condition-case nil
8780 (prog1 (org-id-store-link)
8781 (setq desc (plist-get org-store-link-plist
8782 :description)))
8783 (error
8784 ;; probably before first headline, link to file only
8785 (concat "file:"
8786 (abbreviate-file-name
8787 (buffer-file-name (buffer-base-buffer))))))))
8789 ;; Just link to current headline
8790 (setq cpltxt (concat "file:"
8791 (abbreviate-file-name
8792 (buffer-file-name (buffer-base-buffer)))))
8793 ;; Add a context search string
8794 (when (org-xor org-context-in-file-links arg)
8795 (setq txt (cond
8796 ((org-at-heading-p) nil)
8797 ((org-region-active-p)
8798 (buffer-substring (region-beginning) (region-end)))
8799 (t nil)))
8800 (when (or (null txt) (string-match "\\S-" txt))
8801 (setq cpltxt
8802 (concat cpltxt "::"
8803 (condition-case nil
8804 (org-make-org-heading-search-string txt)
8805 (error "")))
8806 desc (or (nth 4 (ignore-errors
8807 (org-heading-components))) "NONE"))))
8808 (if (string-match "::\\'" cpltxt)
8809 (setq cpltxt (substring cpltxt 0 -2)))
8810 (setq link (org-make-link cpltxt)))))
8812 ((buffer-file-name (buffer-base-buffer))
8813 ;; Just link to this file here.
8814 (setq cpltxt (concat "file:"
8815 (abbreviate-file-name
8816 (buffer-file-name (buffer-base-buffer)))))
8817 ;; Add a context string
8818 (when (org-xor org-context-in-file-links arg)
8819 (setq txt (if (org-region-active-p)
8820 (buffer-substring (region-beginning) (region-end))
8821 (buffer-substring (point-at-bol) (point-at-eol))))
8822 ;; Only use search option if there is some text.
8823 (when (string-match "\\S-" txt)
8824 (setq cpltxt
8825 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8826 desc "NONE")))
8827 (setq link (org-make-link cpltxt)))
8829 ((org-called-interactively-p 'interactive)
8830 (error "Cannot link to a buffer which is not visiting a file"))
8832 (t (setq link nil)))
8834 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8835 (setq link (or link cpltxt)
8836 desc (or desc cpltxt))
8837 (if (equal desc "NONE") (setq desc nil))
8839 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8840 (progn
8841 (setq org-stored-links
8842 (cons (list link desc) org-stored-links))
8843 (message "Stored: %s" (or desc link))
8844 (when custom-id
8845 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8846 "::#" custom-id))
8847 (setq org-stored-links
8848 (cons (list link desc) org-stored-links))))
8849 (or agenda-link (and link (org-make-link-string link desc)))))))
8851 (defun org-store-link-props (&rest plist)
8852 "Store link properties, extract names and addresses."
8853 (let (x adr)
8854 (when (setq x (plist-get plist :from))
8855 (setq adr (mail-extract-address-components x))
8856 (setq plist (plist-put plist :fromname (car adr)))
8857 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8858 (when (setq x (plist-get plist :to))
8859 (setq adr (mail-extract-address-components x))
8860 (setq plist (plist-put plist :toname (car adr)))
8861 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8862 (let ((from (plist-get plist :from))
8863 (to (plist-get plist :to)))
8864 (when (and from to org-from-is-user-regexp)
8865 (setq plist
8866 (plist-put plist :fromto
8867 (if (string-match org-from-is-user-regexp from)
8868 (concat "to %t")
8869 (concat "from %f"))))))
8870 (setq org-store-link-plist plist))
8872 (defun org-add-link-props (&rest plist)
8873 "Add these properties to the link property list."
8874 (let (key value)
8875 (while plist
8876 (setq key (pop plist) value (pop plist))
8877 (setq org-store-link-plist
8878 (plist-put org-store-link-plist key value)))))
8880 (defun org-email-link-description (&optional fmt)
8881 "Return the description part of an email link.
8882 This takes information from `org-store-link-plist' and formats it
8883 according to FMT (default from `org-email-link-description-format')."
8884 (setq fmt (or fmt org-email-link-description-format))
8885 (let* ((p org-store-link-plist)
8886 (to (plist-get p :toaddress))
8887 (from (plist-get p :fromaddress))
8888 (table
8889 (list
8890 (cons "%c" (plist-get p :fromto))
8891 (cons "%F" (plist-get p :from))
8892 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8893 (cons "%T" (plist-get p :to))
8894 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8895 (cons "%s" (plist-get p :subject))
8896 (cons "%d" (plist-get p :date))
8897 (cons "%m" (plist-get p :message-id)))))
8898 (when (string-match "%c" fmt)
8899 ;; Check if the user wrote this message
8900 (if (and org-from-is-user-regexp from to
8901 (save-match-data (string-match org-from-is-user-regexp from)))
8902 (setq fmt (replace-match "to %t" t t fmt))
8903 (setq fmt (replace-match "from %f" t t fmt))))
8904 (org-replace-escapes fmt table)))
8906 (defun org-make-org-heading-search-string (&optional string heading)
8907 "Make search string for STRING or current headline."
8908 (interactive)
8909 (let ((s (or string (org-get-heading)))
8910 (lines org-context-in-file-links))
8911 (unless (and string (not heading))
8912 ;; We are using a headline, clean up garbage in there.
8913 (if (string-match org-todo-regexp s)
8914 (setq s (replace-match "" t t s)))
8915 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8916 (setq s (replace-match "" t t s)))
8917 (setq s (org-trim s))
8918 (if (string-match (concat "^\\(" org-quote-string "\\|"
8919 org-comment-string "\\)") s)
8920 (setq s (replace-match "" t t s)))
8921 (while (string-match org-ts-regexp s)
8922 (setq s (replace-match "" t t s))))
8923 (or string (setq s (concat "*" s))) ; Add * for headlines
8924 (when (and string (integerp lines) (> lines 0))
8925 (let ((slines (org-split-string s "\n")))
8926 (when (< lines (length slines))
8927 (setq s (mapconcat
8928 'identity
8929 (reverse (nthcdr (- (length slines) lines)
8930 (reverse slines))) "\n")))))
8931 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8933 (defun org-make-link (&rest strings)
8934 "Concatenate STRINGS."
8935 (apply 'concat strings))
8937 (defun org-make-link-string (link &optional description)
8938 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8939 (unless (string-match "\\S-" link)
8940 (error "Empty link"))
8941 (when (and description
8942 (stringp description)
8943 (not (string-match "\\S-" description)))
8944 (setq description nil))
8945 (when (stringp description)
8946 ;; Remove brackets from the description, they are fatal.
8947 (while (string-match "\\[" description)
8948 (setq description (replace-match "{" t t description)))
8949 (while (string-match "\\]" description)
8950 (setq description (replace-match "}" t t description))))
8951 (when (equal link description)
8952 ;; No description needed, it is identical
8953 (setq description nil))
8954 (when (and (not description)
8955 (not (string-match (org-image-file-name-regexp) link))
8956 (not (equal link (org-link-escape link))))
8957 (setq description (org-extract-attributes link)))
8958 (setq link
8959 (cond ((string-match (org-image-file-name-regexp) link) link)
8960 ((string-match org-link-types-re link)
8961 (concat (match-string 1 link)
8962 (org-link-escape (substring link (match-end 1)))))
8963 (t (org-link-escape link))))
8964 (concat "[[" link "]"
8965 (if description (concat "[" description "]") "")
8966 "]"))
8968 (defconst org-link-escape-chars
8969 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8970 "List of characters that should be escaped in link.
8971 This is the list that is used for internal purposes.")
8973 (defvar org-url-encoding-use-url-hexify nil)
8975 (defconst org-link-escape-chars-browser
8976 '(?\ )
8977 "List of escapes for characters that are problematic in links.
8978 This is the list that is used before handing over to the browser.")
8980 (defun org-link-escape (text &optional table merge)
8981 "Return percent escaped representation of TEXT.
8982 TEXT is a string with the text to escape.
8983 Optional argument TABLE is a list with characters that should be
8984 escaped. When nil, `org-link-escape-chars' is used.
8985 If optional argument MERGE is set, merge TABLE into
8986 `org-link-escape-chars'."
8987 (if (and org-url-encoding-use-url-hexify (not table))
8988 (url-hexify-string text)
8989 (cond
8990 ((and table merge)
8991 (mapc (lambda (defchr)
8992 (unless (member defchr table)
8993 (setq table (cons defchr table)))) org-link-escape-chars))
8994 ((null table)
8995 (setq table org-link-escape-chars)))
8996 (mapconcat
8997 (lambda (char)
8998 (if (or (member char table)
8999 (< char 32) (= char 37) (> char 126))
9000 (mapconcat (lambda (sequence-element)
9001 (format "%%%.2X" sequence-element))
9002 (or (encode-coding-char char 'utf-8)
9003 (error "Unable to percent escape character: %s"
9004 (char-to-string char))) "")
9005 (char-to-string char))) text "")))
9007 (defun org-link-unescape (str)
9008 "Unhex hexified Unicode strings as returned from the JavaScript function
9009 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9010 (unless (and (null str) (string= "" str))
9011 (let ((pos 0) (case-fold-search t) unhexed)
9012 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9013 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9014 (setq str (replace-match unhexed t t str))
9015 (setq pos (+ pos (length unhexed))))))
9016 str)
9018 (defun org-link-unescape-compound (hex)
9019 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9020 Note: this function also decodes single byte encodings like
9021 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9022 (save-match-data
9023 (let* ((bytes (cdr (split-string hex "%")))
9024 (ret "")
9025 (eat 0)
9026 (sum 0))
9027 (while bytes
9028 (let* ((val (string-to-number (pop bytes) 16))
9029 (shift-xor
9030 (if (= 0 eat)
9031 (cond
9032 ((>= val 252) (cons 6 252))
9033 ((>= val 248) (cons 5 248))
9034 ((>= val 240) (cons 4 240))
9035 ((>= val 224) (cons 3 224))
9036 ((>= val 192) (cons 2 192))
9037 (t (cons 0 0)))
9038 (cons 6 128))))
9039 (if (>= val 192) (setq eat (car shift-xor)))
9040 (setq val (logxor val (cdr shift-xor)))
9041 (setq sum (+ (lsh sum (car shift-xor)) val))
9042 (if (> eat 0) (setq eat (- eat 1)))
9043 (cond
9044 ((= 0 eat) ;multi byte
9045 (setq ret (concat ret (org-char-to-string sum)))
9046 (setq sum 0))
9047 ((not bytes) ; single byte(s)
9048 (setq ret (org-link-unescape-single-byte-sequence hex))))
9049 )) ;; end (while bytes
9050 ret )))
9052 (defun org-link-unescape-single-byte-sequence (hex)
9053 "Unhexify hex-encoded single byte character sequences."
9054 (mapconcat (lambda (byte)
9055 (char-to-string (string-to-number byte 16)))
9056 (cdr (split-string hex "%")) ""))
9058 (defun org-xor (a b)
9059 "Exclusive or."
9060 (if a (not b) b))
9062 (defun org-fixup-message-id-for-http (s)
9063 "Replace special characters in a message id, so it can be used in an http query."
9064 (when (string-match "%" s)
9065 (setq s (mapconcat (lambda (c)
9066 (if (eq c ?%)
9067 "%25"
9068 (char-to-string c)))
9069 s "")))
9070 (while (string-match "<" s)
9071 (setq s (replace-match "%3C" t t s)))
9072 (while (string-match ">" s)
9073 (setq s (replace-match "%3E" t t s)))
9074 (while (string-match "@" s)
9075 (setq s (replace-match "%40" t t s)))
9078 ;;;###autoload
9079 (defun org-insert-link-global ()
9080 "Insert a link like Org-mode does.
9081 This command can be called in any mode to insert a link in Org-mode syntax."
9082 (interactive)
9083 (org-load-modules-maybe)
9084 (org-run-like-in-org-mode 'org-insert-link))
9086 (defun org-insert-link (&optional complete-file link-location default-description)
9087 "Insert a link. At the prompt, enter the link.
9089 Completion can be used to insert any of the link protocol prefixes like
9090 http or ftp in use.
9092 The history can be used to select a link previously stored with
9093 `org-store-link'. When the empty string is entered (i.e. if you just
9094 press RET at the prompt), the link defaults to the most recently
9095 stored link. As SPC triggers completion in the minibuffer, you need to
9096 use M-SPC or C-q SPC to force the insertion of a space character.
9098 You will also be prompted for a description, and if one is given, it will
9099 be displayed in the buffer instead of the link.
9101 If there is already a link at point, this command will allow you to edit link
9102 and description parts.
9104 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9105 be selected using completion. The path to the file will be relative to the
9106 current directory if the file is in the current directory or a subdirectory.
9107 Otherwise, the link will be the absolute path as completed in the minibuffer
9108 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9109 option `org-link-file-path-type'.
9111 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9112 the current directory or below.
9114 With three \\[universal-argument] prefixes, negate the meaning of
9115 `org-keep-stored-link-after-insertion'.
9117 If `org-make-link-description-function' is non-nil, this function will be
9118 called with the link target, and the result will be the default
9119 link description.
9121 If the LINK-LOCATION parameter is non-nil, this value will be
9122 used as the link location instead of reading one interactively.
9124 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9125 be used as the default description."
9126 (interactive "P")
9127 (let* ((wcf (current-window-configuration))
9128 (region (if (org-region-active-p)
9129 (buffer-substring (region-beginning) (region-end))))
9130 (remove (and region (list (region-beginning) (region-end))))
9131 (desc region)
9132 tmphist ; byte-compile incorrectly complains about this
9133 (link link-location)
9134 entry file all-prefixes)
9135 (cond
9136 (link-location) ; specified by arg, just use it.
9137 ((org-in-regexp org-bracket-link-regexp 1)
9138 ;; We do have a link at point, and we are going to edit it.
9139 (setq remove (list (match-beginning 0) (match-end 0)))
9140 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9141 (setq link (read-string "Link: "
9142 (org-link-unescape
9143 (org-match-string-no-properties 1)))))
9144 ((or (org-in-regexp org-angle-link-re)
9145 (org-in-regexp org-plain-link-re))
9146 ;; Convert to bracket link
9147 (setq remove (list (match-beginning 0) (match-end 0))
9148 link (read-string "Link: "
9149 (org-remove-angle-brackets (match-string 0)))))
9150 ((member complete-file '((4) (16)))
9151 ;; Completing read for file names.
9152 (setq link (org-file-complete-link complete-file)))
9154 ;; Read link, with completion for stored links.
9155 (with-output-to-temp-buffer "*Org Links*"
9156 (princ "Insert a link.
9157 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9158 (when org-stored-links
9159 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9160 (princ (mapconcat
9161 (lambda (x)
9162 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9163 (reverse org-stored-links) "\n"))))
9164 (let ((cw (selected-window)))
9165 (select-window (get-buffer-window "*Org Links*" 'visible))
9166 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9167 (unless (pos-visible-in-window-p (point-max))
9168 (org-fit-window-to-buffer))
9169 (and (window-live-p cw) (select-window cw)))
9170 ;; Fake a link history, containing the stored links.
9171 (setq tmphist (append (mapcar 'car org-stored-links)
9172 org-insert-link-history))
9173 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9174 (mapcar 'car org-link-abbrev-alist)
9175 org-link-types))
9176 (unwind-protect
9177 (progn
9178 (setq link
9179 (let ((org-completion-use-ido nil)
9180 (org-completion-use-iswitchb nil))
9181 (org-completing-read
9182 "Link: "
9183 (append
9184 (mapcar (lambda (x) (list (concat x ":")))
9185 all-prefixes)
9186 (mapcar 'car org-stored-links))
9187 nil nil nil
9188 'tmphist
9189 (car (car org-stored-links)))))
9190 (if (not (string-match "\\S-" link))
9191 (error "No link selected"))
9192 (if (or (member link all-prefixes)
9193 (and (equal ":" (substring link -1))
9194 (member (substring link 0 -1) all-prefixes)
9195 (setq link (substring link 0 -1))))
9196 (setq link (org-link-try-special-completion link))))
9197 (set-window-configuration wcf)
9198 (kill-buffer "*Org Links*"))
9199 (setq entry (assoc link org-stored-links))
9200 (or entry (push link org-insert-link-history))
9201 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9202 (not org-keep-stored-link-after-insertion))
9203 (setq org-stored-links (delq (assoc link org-stored-links)
9204 org-stored-links)))
9205 (setq desc (or desc (nth 1 entry)))))
9207 (if (string-match org-plain-link-re link)
9208 ;; URL-like link, normalize the use of angular brackets.
9209 (setq link (org-make-link (org-remove-angle-brackets link))))
9211 ;; Check if we are linking to the current file with a search option
9212 ;; If yes, simplify the link by using only the search option.
9213 (when (and buffer-file-name
9214 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9215 (let* ((path (match-string 1 link))
9216 (case-fold-search nil)
9217 (search (match-string 2 link)))
9218 (save-match-data
9219 (if (equal (file-truename buffer-file-name) (file-truename path))
9220 ;; We are linking to this same file, with a search option
9221 (setq link search)))))
9223 ;; Check if we can/should use a relative path. If yes, simplify the link
9224 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9225 (let* ((type (match-string 1 link))
9226 (path (match-string 2 link))
9227 (origpath path)
9228 (case-fold-search nil))
9229 (cond
9230 ((or (eq org-link-file-path-type 'absolute)
9231 (equal complete-file '(16)))
9232 (setq path (abbreviate-file-name (expand-file-name path))))
9233 ((eq org-link-file-path-type 'noabbrev)
9234 (setq path (expand-file-name path)))
9235 ((eq org-link-file-path-type 'relative)
9236 (setq path (file-relative-name path)))
9238 (save-match-data
9239 (if (string-match (concat "^" (regexp-quote
9240 (expand-file-name
9241 (file-name-as-directory
9242 default-directory))))
9243 (expand-file-name path))
9244 ;; We are linking a file with relative path name.
9245 (setq path (substring (expand-file-name path)
9246 (match-end 0)))
9247 (setq path (abbreviate-file-name (expand-file-name path)))))))
9248 (setq link (concat type path))
9249 (if (equal desc origpath)
9250 (setq desc path))))
9252 (if org-make-link-description-function
9253 (setq desc (funcall org-make-link-description-function link desc))
9254 (if default-description (setq desc default-description)))
9256 (setq desc (read-string "Description: " desc))
9257 (unless (string-match "\\S-" desc) (setq desc nil))
9258 (if remove (apply 'delete-region remove))
9259 (insert (org-make-link-string link desc))))
9261 (defun org-link-try-special-completion (type)
9262 "If there is completion support for link type TYPE, offer it."
9263 (let ((fun (intern (concat "org-" type "-complete-link"))))
9264 (if (functionp fun)
9265 (funcall fun)
9266 (read-string "Link (no completion support): " (concat type ":")))))
9268 (defun org-file-complete-link (&optional arg)
9269 "Create a file link using completion."
9270 (let (file link)
9271 (setq file (read-file-name "File: "))
9272 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9273 (pwd1 (file-name-as-directory (abbreviate-file-name
9274 (expand-file-name ".")))))
9275 (cond
9276 ((equal arg '(16))
9277 (setq link (org-make-link
9278 "file:"
9279 (abbreviate-file-name (expand-file-name file)))))
9280 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9281 (setq link (org-make-link "file:" (match-string 1 file))))
9282 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9283 (expand-file-name file))
9284 (setq link (org-make-link
9285 "file:" (match-string 1 (expand-file-name file)))))
9286 (t (setq link (org-make-link "file:" file)))))
9287 link))
9289 (defun org-completing-read (&rest args)
9290 "Completing-read with SPACE being a normal character."
9291 (let ((enable-recursive-minibuffers t)
9292 (minibuffer-local-completion-map
9293 (copy-keymap minibuffer-local-completion-map)))
9294 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9295 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9296 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9297 (apply 'org-icompleting-read args)))
9299 (defun org-completing-read-no-i (&rest args)
9300 (let (org-completion-use-ido org-completion-use-iswitchb)
9301 (apply 'org-completing-read args)))
9303 (defun org-iswitchb-completing-read (prompt choices &rest args)
9304 "Use iswitch as a completing-read replacement to choose from choices.
9305 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9306 from."
9307 (let* ((iswitchb-use-virtual-buffers nil)
9308 (iswitchb-make-buflist-hook
9309 (lambda ()
9310 (setq iswitchb-temp-buflist choices))))
9311 (iswitchb-read-buffer prompt)))
9313 (defun org-icompleting-read (&rest args)
9314 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9315 (org-without-partial-completion
9316 (if (and org-completion-use-ido
9317 (fboundp 'ido-completing-read)
9318 (boundp 'ido-mode) ido-mode
9319 (listp (second args)))
9320 (let ((ido-enter-matching-directory nil))
9321 (apply 'ido-completing-read (concat (car args))
9322 (if (consp (car (nth 1 args)))
9323 (mapcar 'car (nth 1 args))
9324 (nth 1 args))
9325 (cddr args)))
9326 (if (and org-completion-use-iswitchb
9327 (boundp 'iswitchb-mode) iswitchb-mode
9328 (listp (second args)))
9329 (apply 'org-iswitchb-completing-read (concat (car args))
9330 (if (consp (car (nth 1 args)))
9331 (mapcar 'car (nth 1 args))
9332 (nth 1 args))
9333 (cddr args))
9334 (apply 'completing-read args)))))
9336 (defun org-extract-attributes (s)
9337 "Extract the attributes cookie from a string and set as text property."
9338 (let (a attr (start 0) key value)
9339 (save-match-data
9340 (when (string-match "{{\\([^}]+\\)}}$" s)
9341 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9342 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9343 (setq key (match-string 1 a) value (match-string 2 a)
9344 start (match-end 0)
9345 attr (plist-put attr (intern key) value))))
9346 (org-add-props s nil 'org-attr attr))
9349 (defun org-extract-attributes-from-string (tag)
9350 (let (key value attr)
9351 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9352 (setq key (match-string 1 tag) value (match-string 2 tag)
9353 tag (replace-match "" t t tag)
9354 attr (plist-put attr (intern key) value)))
9355 (cons tag attr)))
9357 (defun org-attributes-to-string (plist)
9358 "Format a property list into an HTML attribute list."
9359 (let ((s "") key value)
9360 (while plist
9361 (setq key (pop plist) value (pop plist))
9362 (and value
9363 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9366 ;;; Opening/following a link
9368 (defvar org-link-search-failed nil)
9370 (defvar org-open-link-functions nil
9371 "Hook for functions finding a plain text link.
9372 These functions must take a single argument, the link content.
9373 They will be called for links that look like [[link text][description]]
9374 when LINK TEXT does not have a protocol like \"http:\" and does not look
9375 like a filename (e.g. \"./blue.png\").
9377 These functions will be called *before* Org attempts to resolve the
9378 link by doing text searches in the current buffer - so if you want a
9379 link \"[[target]]\" to still find \"<<target>>\", your function should
9380 handle this as a special case.
9382 When the function does handle the link, it must return a non-nil value.
9383 If it decides that it is not responsible for this link, it must return
9384 nil to indicate that that Org-mode can continue with other options
9385 like exact and fuzzy text search.")
9387 (defun org-next-link ()
9388 "Move forward to the next link.
9389 If the link is in hidden text, expose it."
9390 (interactive)
9391 (when (and org-link-search-failed (eq this-command last-command))
9392 (goto-char (point-min))
9393 (message "Link search wrapped back to beginning of buffer"))
9394 (setq org-link-search-failed nil)
9395 (let* ((pos (point))
9396 (ct (org-context))
9397 (a (assoc :link ct)))
9398 (if a (goto-char (nth 2 a)))
9399 (if (re-search-forward org-any-link-re nil t)
9400 (progn
9401 (goto-char (match-beginning 0))
9402 (if (outline-invisible-p) (org-show-context)))
9403 (goto-char pos)
9404 (setq org-link-search-failed t)
9405 (error "No further link found"))))
9407 (defun org-previous-link ()
9408 "Move backward to the previous link.
9409 If the link is in hidden text, expose it."
9410 (interactive)
9411 (when (and org-link-search-failed (eq this-command last-command))
9412 (goto-char (point-max))
9413 (message "Link search wrapped back to end of buffer"))
9414 (setq org-link-search-failed nil)
9415 (let* ((pos (point))
9416 (ct (org-context))
9417 (a (assoc :link ct)))
9418 (if a (goto-char (nth 1 a)))
9419 (if (re-search-backward org-any-link-re nil t)
9420 (progn
9421 (goto-char (match-beginning 0))
9422 (if (outline-invisible-p) (org-show-context)))
9423 (goto-char pos)
9424 (setq org-link-search-failed t)
9425 (error "No further link found"))))
9427 (defun org-translate-link (s)
9428 "Translate a link string if a translation function has been defined."
9429 (if (and org-link-translation-function
9430 (fboundp org-link-translation-function)
9431 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9432 (progn
9433 (setq s (funcall org-link-translation-function
9434 (match-string 1) (match-string 2)))
9435 (concat (car s) ":" (cdr s)))
9438 (defun org-translate-link-from-planner (type path)
9439 "Translate a link from Emacs Planner syntax so that Org can follow it.
9440 This is still an experimental function, your mileage may vary."
9441 (cond
9442 ((member type '("http" "https" "news" "ftp"))
9443 ;; standard Internet links are the same.
9444 nil)
9445 ((and (equal type "irc") (string-match "^//" path))
9446 ;; Planner has two / at the beginning of an irc link, we have 1.
9447 ;; We should have zero, actually....
9448 (setq path (substring path 1)))
9449 ((and (equal type "lisp") (string-match "^/" path))
9450 ;; Planner has a slash, we do not.
9451 (setq type "elisp" path (substring path 1)))
9452 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9453 ;; A typical message link. Planner has the id after the final slash,
9454 ;; we separate it with a hash mark
9455 (setq path (concat (match-string 1 path) "#"
9456 (org-remove-angle-brackets (match-string 2 path)))))
9458 (cons type path))
9460 (defun org-find-file-at-mouse (ev)
9461 "Open file link or URL at mouse."
9462 (interactive "e")
9463 (mouse-set-point ev)
9464 (org-open-at-point 'in-emacs))
9466 (defun org-open-at-mouse (ev)
9467 "Open file link or URL at mouse.
9468 See the docstring of `org-open-file' for details."
9469 (interactive "e")
9470 (mouse-set-point ev)
9471 (if (eq major-mode 'org-agenda-mode)
9472 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9473 (org-open-at-point))
9475 (defvar org-window-config-before-follow-link nil
9476 "The window configuration before following a link.
9477 This is saved in case the need arises to restore it.")
9479 (defvar org-open-link-marker (make-marker)
9480 "Marker pointing to the location where `org-open-at-point; was called.")
9482 ;;;###autoload
9483 (defun org-open-at-point-global ()
9484 "Follow a link like Org-mode does.
9485 This command can be called in any mode to follow a link that has
9486 Org-mode syntax."
9487 (interactive)
9488 (org-run-like-in-org-mode 'org-open-at-point))
9490 ;;;###autoload
9491 (defun org-open-link-from-string (s &optional arg reference-buffer)
9492 "Open a link in the string S, as if it was in Org-mode."
9493 (interactive "sLink: \nP")
9494 (let ((reference-buffer (or reference-buffer (current-buffer))))
9495 (with-temp-buffer
9496 (let ((org-inhibit-startup (not reference-buffer)))
9497 (org-mode)
9498 (insert s)
9499 (goto-char (point-min))
9500 (when reference-buffer
9501 (setq org-link-abbrev-alist-local
9502 (with-current-buffer reference-buffer
9503 org-link-abbrev-alist-local)))
9504 (org-open-at-point arg reference-buffer)))))
9506 (defvar org-open-at-point-functions nil
9507 "Hook that is run when following a link at point.
9509 Functions in this hook must return t if they identify and follow
9510 a link at point. If they don't find anything interesting at point,
9511 they must return nil.")
9513 (defun org-open-at-point (&optional arg reference-buffer)
9514 "Open link at or after point.
9515 If there is no link at point, this function will search forward up to
9516 the end of the current line.
9517 Normally, files will be opened by an appropriate application. If the
9518 optional prefix argument ARG is non-nil, Emacs will visit the file.
9519 With a double prefix argument, try to open outside of Emacs, in the
9520 application the system uses for this file type."
9521 (interactive "P")
9522 ;; if in a code block, then open the block's results
9523 (unless (call-interactively #'org-babel-open-src-block-result)
9524 (org-load-modules-maybe)
9525 (move-marker org-open-link-marker (point))
9526 (setq org-window-config-before-follow-link (current-window-configuration))
9527 (org-remove-occur-highlights nil nil t)
9528 (cond
9529 ((and (org-at-heading-p)
9530 (not (org-in-regexp
9531 (concat org-plain-link-re "\\|"
9532 org-bracket-link-regexp "\\|"
9533 org-angle-link-re "\\|"
9534 "[ \t]:[^ \t\n]+:[ \t]*$")))
9535 (not (get-text-property (point) 'org-linked-text)))
9536 (or (org-offer-links-in-entry arg)
9537 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9538 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9539 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9540 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9541 (not (org-in-regexp org-bracket-link-regexp)))
9542 (org-footnote-action))
9544 (let (type path link line search (pos (point)))
9545 (catch 'match
9546 (save-excursion
9547 (skip-chars-forward "^]\n\r")
9548 (when (org-in-regexp org-bracket-link-regexp 1)
9549 (setq link (org-extract-attributes
9550 (org-link-unescape (org-match-string-no-properties 1))))
9551 (while (string-match " *\n *" link)
9552 (setq link (replace-match " " t t link)))
9553 (setq link (org-link-expand-abbrev link))
9554 (cond
9555 ((or (file-name-absolute-p link)
9556 (string-match "^\\.\\.?/" link))
9557 (setq type "file" path link))
9558 ((string-match org-link-re-with-space3 link)
9559 (setq type (match-string 1 link) path (match-string 2 link)))
9560 (t (setq type "thisfile" path link)))
9561 (throw 'match t)))
9563 (when (get-text-property (point) 'org-linked-text)
9564 (setq type "thisfile"
9565 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9566 (1+ (point)) (point))
9567 path (buffer-substring
9568 (or (previous-single-property-change pos 'org-linked-text)
9569 (point-min))
9570 (or (next-single-property-change pos 'org-linked-text)
9571 (point-max))))
9572 (throw 'match t))
9574 (save-excursion
9575 (when (or (org-in-regexp org-angle-link-re)
9576 (org-in-regexp org-plain-link-re))
9577 (setq type (match-string 1)
9578 path (org-link-unescape (match-string 2)))
9579 (throw 'match t)))
9580 (save-excursion
9581 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9582 (setq type "tags"
9583 path (match-string 1))
9584 (while (string-match ":" path)
9585 (setq path (replace-match "+" t t path)))
9586 (throw 'match t)))
9587 (when (org-in-regexp "<\\([^><\n]+\\)>")
9588 (setq type "tree-match"
9589 path (match-string 1))
9590 (throw 'match t)))
9591 (unless path
9592 (error "No link found"))
9594 ;; switch back to reference buffer
9595 ;; needed when if called in a temporary buffer through
9596 ;; org-open-link-from-string
9597 (with-current-buffer (or reference-buffer (current-buffer))
9599 ;; Remove any trailing spaces in path
9600 (if (string-match " +\\'" path)
9601 (setq path (replace-match "" t t path)))
9602 (if (and org-link-translation-function
9603 (fboundp org-link-translation-function))
9604 ;; Check if we need to translate the link
9605 (let ((tmp (funcall org-link-translation-function type path)))
9606 (setq type (car tmp) path (cdr tmp))))
9608 (cond
9610 ((assoc type org-link-protocols)
9611 (funcall (nth 1 (assoc type org-link-protocols)) path))
9613 ((equal type "mailto")
9614 (let ((cmd (car org-link-mailto-program))
9615 (args (cdr org-link-mailto-program)) args1
9616 (address path) (subject "") a)
9617 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9618 (setq address (match-string 1 path)
9619 subject (org-link-escape (match-string 2 path))))
9620 (while args
9621 (cond
9622 ((not (stringp (car args))) (push (pop args) args1))
9623 (t (setq a (pop args))
9624 (if (string-match "%a" a)
9625 (setq a (replace-match address t t a)))
9626 (if (string-match "%s" a)
9627 (setq a (replace-match subject t t a)))
9628 (push a args1))))
9629 (apply cmd (nreverse args1))))
9631 ((member type '("http" "https" "ftp" "news"))
9632 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9633 (org-link-escape
9634 path org-link-escape-chars-browser)
9635 path))))
9637 ((string= type "doi")
9638 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9639 (org-link-escape
9640 path org-link-escape-chars-browser)
9641 path))))
9643 ((member type '("message"))
9644 (browse-url (concat type ":" path)))
9646 ((string= type "tags")
9647 (org-tags-view arg path))
9649 ((string= type "tree-match")
9650 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9652 ((string= type "file")
9653 (if (string-match "::\\([0-9]+\\)\\'" path)
9654 (setq line (string-to-number (match-string 1 path))
9655 path (substring path 0 (match-beginning 0)))
9656 (if (string-match "::\\(.+\\)\\'" path)
9657 (setq search (match-string 1 path)
9658 path (substring path 0 (match-beginning 0)))))
9659 (if (string-match "[*?{]" (file-name-nondirectory path))
9660 (dired path)
9661 (org-open-file path arg line search)))
9663 ((string= type "shell")
9664 (let ((cmd path))
9665 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9666 (string-match org-confirm-shell-link-not-regexp cmd))
9667 (not org-confirm-shell-link-function)
9668 (funcall org-confirm-shell-link-function
9669 (format "Execute \"%s\" in shell? "
9670 (org-add-props cmd nil
9671 'face 'org-warning))))
9672 (progn
9673 (message "Executing %s" cmd)
9674 (shell-command cmd))
9675 (error "Abort"))))
9677 ((string= type "elisp")
9678 (let ((cmd path))
9679 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9680 (string-match org-confirm-elisp-link-not-regexp cmd))
9681 (not org-confirm-elisp-link-function)
9682 (funcall org-confirm-elisp-link-function
9683 (format "Execute \"%s\" as elisp? "
9684 (org-add-props cmd nil
9685 'face 'org-warning))))
9686 (message "%s => %s" cmd
9687 (if (equal (string-to-char cmd) ?\()
9688 (eval (read cmd))
9689 (call-interactively (read cmd))))
9690 (error "Abort"))))
9692 ((and (string= type "thisfile")
9693 (run-hook-with-args-until-success
9694 'org-open-link-functions path)))
9696 ((string= type "thisfile")
9697 (if arg
9698 (switch-to-buffer-other-window
9699 (org-get-buffer-for-internal-link (current-buffer)))
9700 (org-mark-ring-push))
9701 (let ((cmd `(org-link-search
9702 ,path
9703 ,(cond ((equal arg '(4)) ''occur)
9704 ((equal arg '(16)) ''org-occur)
9705 (t nil))
9706 ,pos)))
9707 (condition-case nil (let ((org-link-search-inhibit-query t))
9708 (eval cmd))
9709 (error (progn (widen) (eval cmd))))))
9712 (browse-url-at-point)))))))
9713 (move-marker org-open-link-marker nil)
9714 (run-hook-with-args 'org-follow-link-hook)))
9716 (defun org-offer-links-in-entry (&optional nth zero)
9717 "Offer links in the current entry and follow the selected link.
9718 If there is only one link, follow it immediately as well.
9719 If NTH is an integer, immediately pick the NTH link found.
9720 If ZERO is a string, check also this string for a link, and if
9721 there is one, offer it as link number zero."
9722 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9723 "\\(" org-angle-link-re "\\)\\|"
9724 "\\(" org-plain-link-re "\\)"))
9725 (cnt ?0)
9726 (in-emacs (if (integerp nth) nil nth))
9727 have-zero end links link c)
9728 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9729 (push (match-string 0 zero) links)
9730 (setq cnt (1- cnt) have-zero t))
9731 (save-excursion
9732 (org-back-to-heading t)
9733 (setq end (save-excursion (outline-next-heading) (point)))
9734 (while (re-search-forward re end t)
9735 (push (match-string 0) links))
9736 (setq links (org-uniquify (reverse links))))
9738 (cond
9739 ((null links)
9740 (message "No links"))
9741 ((equal (length links) 1)
9742 (setq link (list (car links))))
9743 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9744 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9745 (t ; we have to select a link
9746 (save-excursion
9747 (save-window-excursion
9748 (delete-other-windows)
9749 (with-output-to-temp-buffer "*Select Link*"
9750 (mapc (lambda (l)
9751 (if (not (string-match org-bracket-link-regexp l))
9752 (princ (format "[%c] %s\n" (incf cnt)
9753 (org-remove-angle-brackets l)))
9754 (if (match-end 3)
9755 (princ (format "[%c] %s (%s)\n" (incf cnt)
9756 (match-string 3 l) (match-string 1 l)))
9757 (princ (format "[%c] %s\n" (incf cnt)
9758 (match-string 1 l))))))
9759 links))
9760 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9761 (message "Select link to open, RET to open all:")
9762 (setq c (read-char-exclusive))
9763 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9764 (when (equal c ?q) (error "Abort"))
9765 (if (equal c ?\C-m)
9766 (setq link links)
9767 (setq nth (- c ?0))
9768 (if have-zero (setq nth (1+ nth)))
9769 (unless (and (integerp nth) (>= (length links) nth))
9770 (error "Invalid link selection"))
9771 (setq link (list (nth (1- nth) links))))))
9772 (if link
9773 (let ((buf (current-buffer)))
9774 (dolist (l link)
9775 (org-open-link-from-string l in-emacs buf))
9777 nil)))
9779 ;; Add special file links that specify the way of opening
9781 (org-add-link-type "file+sys" 'org-open-file-with-system)
9782 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9783 (defun org-open-file-with-system (path)
9784 "Open file at PATH using the system way of opening it."
9785 (org-open-file path 'system))
9786 (defun org-open-file-with-emacs (path)
9787 "Open file at PATH in Emacs."
9788 (org-open-file path 'emacs))
9789 (defun org-remove-file-link-modifiers ()
9790 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9791 (goto-char (point-min))
9792 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9793 (org-if-unprotected
9794 (replace-match "file:" t t))))
9795 (eval-after-load "org-exp"
9796 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9797 'org-remove-file-link-modifiers))
9799 ;;;; Time estimates
9801 (defun org-get-effort (&optional pom)
9802 "Get the effort estimate for the current entry."
9803 (org-entry-get pom org-effort-property))
9805 ;;; File search
9807 (defvar org-create-file-search-functions nil
9808 "List of functions to construct the right search string for a file link.
9809 These functions are called in turn with point at the location to
9810 which the link should point.
9812 A function in the hook should first test if it would like to
9813 handle this file type, for example by checking the `major-mode'
9814 or the file extension. If it decides not to handle this file, it
9815 should just return nil to give other functions a chance. If it
9816 does handle the file, it must return the search string to be used
9817 when following the link. The search string will be part of the
9818 file link, given after a double colon, and `org-open-at-point'
9819 will automatically search for it. If special measures must be
9820 taken to make the search successful, another function should be
9821 added to the companion hook `org-execute-file-search-functions',
9822 which see.
9824 A function in this hook may also use `setq' to set the variable
9825 `description' to provide a suggestion for the descriptive text to
9826 be used for this link when it gets inserted into an Org-mode
9827 buffer with \\[org-insert-link].")
9829 (defvar org-execute-file-search-functions nil
9830 "List of functions to execute a file search triggered by a link.
9832 Functions added to this hook must accept a single argument, the
9833 search string that was part of the file link, the part after the
9834 double colon. The function must first check if it would like to
9835 handle this search, for example by checking the `major-mode' or
9836 the file extension. If it decides not to handle this search, it
9837 should just return nil to give other functions a chance. If it
9838 does handle the search, it must return a non-nil value to keep
9839 other functions from trying.
9841 Each function can access the current prefix argument through the
9842 variable `current-prefix-argument'. Note that a single prefix is
9843 used to force opening a link in Emacs, so it may be good to only
9844 use a numeric or double prefix to guide the search function.
9846 In case this is needed, a function in this hook can also restore
9847 the window configuration before `org-open-at-point' was called using:
9849 (set-window-configuration org-window-config-before-follow-link)")
9851 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9852 (defun org-link-search (s &optional type avoid-pos stealth)
9853 "Search for a link search option.
9854 If S is surrounded by forward slashes, it is interpreted as a
9855 regular expression. In org-mode files, this will create an `org-occur'
9856 sparse tree. In ordinary files, `occur' will be used to list matches.
9857 If the current buffer is in `dired-mode', grep will be used to search
9858 in all files. If AVOID-POS is given, ignore matches near that position.
9860 When optional argument STEALTH is non-nil, do not modify
9861 visibility around point, thus ignoring
9862 `org-show-hierarchy-above', `org-show-following-heading' and
9863 `org-show-siblings' variables."
9864 (let ((case-fold-search t)
9865 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9866 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9867 (append '(("") (" ") ("\t") ("\n"))
9868 org-emphasis-alist)
9869 "\\|") "\\)"))
9870 (pos (point))
9871 (pre nil) (post nil)
9872 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9873 (cond
9874 ;; First check if there are any special search functions
9875 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9876 ;; Now try the builtin stuff
9877 ((and (equal (string-to-char s0) ?#)
9878 (> (length s0) 1)
9879 (save-excursion
9880 (goto-char (point-min))
9881 (and
9882 (re-search-forward
9883 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9884 (setq type 'dedicated
9885 pos (match-beginning 0))))
9886 ;; There is an exact target for this
9887 (goto-char pos)
9888 (org-back-to-heading t)))
9889 ((save-excursion
9890 (goto-char (point-min))
9891 (and
9892 (re-search-forward
9893 (concat "<<" (regexp-quote s0) ">>") nil t)
9894 (setq type 'dedicated
9895 pos (match-beginning 0))))
9896 ;; There is an exact target for this
9897 (goto-char pos))
9898 ((and (string-match "^(\\(.*\\))$" s0)
9899 (save-excursion
9900 (goto-char (point-min))
9901 (and
9902 (re-search-forward
9903 (concat "[^[]" (regexp-quote
9904 (format org-coderef-label-format
9905 (match-string 1 s0))))
9906 nil t)
9907 (setq type 'dedicated
9908 pos (1+ (match-beginning 0))))))
9909 ;; There is a coderef target for this
9910 (goto-char pos))
9911 ((string-match "^/\\(.*\\)/$" s)
9912 ;; A regular expression
9913 (cond
9914 ((eq major-mode 'org-mode)
9915 (org-occur (match-string 1 s)))
9916 ;;((eq major-mode 'dired-mode)
9917 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9918 (t (org-do-occur (match-string 1 s)))))
9919 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9920 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9921 (goto-char (point-min))
9922 (cond
9923 ((let (case-fold-search)
9924 (re-search-forward (format org-complex-heading-regexp-format
9925 (regexp-quote s))
9926 nil t))
9927 ;; OK, found a match
9928 (setq type 'dedicated)
9929 (goto-char (match-beginning 0)))
9930 ((and (not org-link-search-inhibit-query)
9931 (eq org-link-search-must-match-exact-headline 'query-to-create)
9932 (y-or-n-p "No match - create this as a new heading? "))
9933 (goto-char (point-max))
9934 (or (bolp) (newline))
9935 (insert "* " s "\n")
9936 (beginning-of-line 0))
9938 (goto-char pos)
9939 (error "No match"))))
9941 ;; A normal search string
9942 (when (equal (string-to-char s) ?*)
9943 ;; Anchor on headlines, post may include tags.
9944 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9945 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9946 s (substring s 1)))
9947 (remove-text-properties
9948 0 (length s)
9949 '(face nil mouse-face nil keymap nil fontified nil) s)
9950 ;; Make a series of regular expressions to find a match
9951 (setq words (org-split-string s "[ \n\r\t]+")
9953 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9954 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9955 "\\)" markers)
9956 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9957 re2a (concat "[ \t\r\n]" re2a_)
9958 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9959 re4 (concat "[^a-zA-Z_]" re4_)
9961 re1 (concat pre re2 post)
9962 re3 (concat pre (if pre re4_ re4) post)
9963 re5 (concat pre ".*" re4)
9964 re2 (concat pre re2)
9965 re2a (concat pre (if pre re2a_ re2a))
9966 re4 (concat pre (if pre re4_ re4))
9967 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9968 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9969 re5 "\\)"
9971 (cond
9972 ((eq type 'org-occur) (org-occur reall))
9973 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9974 (t (goto-char (point-min))
9975 (setq type 'fuzzy)
9976 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9977 (org-search-not-self 1 re1 nil t)
9978 (org-search-not-self 1 re2 nil t)
9979 (org-search-not-self 1 re2a nil t)
9980 (org-search-not-self 1 re3 nil t)
9981 (org-search-not-self 1 re4 nil t)
9982 (org-search-not-self 1 re5 nil t)
9984 (goto-char (match-beginning 1))
9985 (goto-char pos)
9986 (error "No match"))))))
9987 (and (eq major-mode 'org-mode)
9988 (not stealth)
9989 (org-show-context 'link-search))
9990 type))
9992 (defun org-search-not-self (group &rest args)
9993 "Execute `re-search-forward', but only accept matches that do not
9994 enclose the position of `org-open-link-marker'."
9995 (let ((m org-open-link-marker))
9996 (catch 'exit
9997 (while (apply 're-search-forward args)
9998 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9999 (goto-char (match-end group))
10000 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10001 (> (match-beginning 0) (marker-position m))
10002 (< (match-end 0) (marker-position m)))
10003 (save-match-data
10004 (or (not (org-in-regexp
10005 org-bracket-link-analytic-regexp 1))
10006 (not (match-end 4)) ; no description
10007 (and (<= (match-beginning 4) (point))
10008 (>= (match-end 4) (point))))))
10009 (throw 'exit (point))))))))
10011 (defun org-get-buffer-for-internal-link (buffer)
10012 "Return a buffer to be used for displaying the link target of internal links."
10013 (cond
10014 ((not org-display-internal-link-with-indirect-buffer)
10015 buffer)
10016 ((string-match "(Clone)$" (buffer-name buffer))
10017 (message "Buffer is already a clone, not making another one")
10018 ;; we also do not modify visibility in this case
10019 buffer)
10020 (t ; make a new indirect buffer for displaying the link
10021 (let* ((bn (buffer-name buffer))
10022 (ibn (concat bn "(Clone)"))
10023 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10024 (with-current-buffer ib (org-overview))
10025 ib))))
10027 (defun org-do-occur (regexp &optional cleanup)
10028 "Call the Emacs command `occur'.
10029 If CLEANUP is non-nil, remove the printout of the regular expression
10030 in the *Occur* buffer. This is useful if the regex is long and not useful
10031 to read."
10032 (occur regexp)
10033 (when cleanup
10034 (let ((cwin (selected-window)) win beg end)
10035 (when (setq win (get-buffer-window "*Occur*"))
10036 (select-window win))
10037 (goto-char (point-min))
10038 (when (re-search-forward "match[a-z]+" nil t)
10039 (setq beg (match-end 0))
10040 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10041 (setq end (1- (match-beginning 0)))))
10042 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10043 (goto-char (point-min))
10044 (select-window cwin))))
10046 ;;; The mark ring for links jumps
10048 (defvar org-mark-ring nil
10049 "Mark ring for positions before jumps in Org-mode.")
10050 (defvar org-mark-ring-last-goto nil
10051 "Last position in the mark ring used to go back.")
10052 ;; Fill and close the ring
10053 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10054 (loop for i from 1 to org-mark-ring-length do
10055 (push (make-marker) org-mark-ring))
10056 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10057 org-mark-ring)
10059 (defun org-mark-ring-push (&optional pos buffer)
10060 "Put the current position or POS into the mark ring and rotate it."
10061 (interactive)
10062 (setq pos (or pos (point)))
10063 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10064 (move-marker (car org-mark-ring)
10065 (or pos (point))
10066 (or buffer (current-buffer)))
10067 (message "%s"
10068 (substitute-command-keys
10069 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10071 (defun org-mark-ring-goto (&optional n)
10072 "Jump to the previous position in the mark ring.
10073 With prefix arg N, jump back that many stored positions. When
10074 called several times in succession, walk through the entire ring.
10075 Org-mode commands jumping to a different position in the current file,
10076 or to another Org-mode file, automatically push the old position
10077 onto the ring."
10078 (interactive "p")
10079 (let (p m)
10080 (if (eq last-command this-command)
10081 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10082 (setq p org-mark-ring))
10083 (setq org-mark-ring-last-goto p)
10084 (setq m (car p))
10085 (org-pop-to-buffer-same-window (marker-buffer m))
10086 (goto-char m)
10087 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10089 (defun org-remove-angle-brackets (s)
10090 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10091 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10093 (defun org-add-angle-brackets (s)
10094 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10095 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10097 (defun org-remove-double-quotes (s)
10098 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10099 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10102 ;;; Following specific links
10104 (defun org-follow-timestamp-link ()
10105 (cond
10106 ((org-at-date-range-p t)
10107 (let ((org-agenda-start-on-weekday)
10108 (t1 (match-string 1))
10109 (t2 (match-string 2)))
10110 (setq t1 (time-to-days (org-time-string-to-time t1))
10111 t2 (time-to-days (org-time-string-to-time t2)))
10112 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10113 ((org-at-timestamp-p t)
10114 (org-agenda-list nil (time-to-days (org-time-string-to-time
10115 (substring (match-string 1) 0 10)))
10117 (t (error "This should not happen"))))
10120 ;;; Following file links
10121 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10122 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10123 (declare-function mailcap-mime-info
10124 "mailcap" (string &optional request no-decode))
10125 (defvar org-wait nil)
10126 (defun org-open-file (path &optional in-emacs line search)
10127 "Open the file at PATH.
10128 First, this expands any special file name abbreviations. Then the
10129 configuration variable `org-file-apps' is checked if it contains an
10130 entry for this file type, and if yes, the corresponding command is launched.
10132 If no application is found, Emacs simply visits the file.
10134 With optional prefix argument IN-EMACS, Emacs will visit the file.
10135 With a double \\[universal-argument] \\[universal-argument] \
10136 prefix arg, Org tries to avoid opening in Emacs
10137 and to use an external application to visit the file.
10139 Optional LINE specifies a line to go to, optional SEARCH a string
10140 to search for. If LINE or SEARCH is given, the file will be
10141 opened in Emacs, unless an entry from org-file-apps that makes
10142 use of groups in a regexp matches.
10144 If you want to change the way frames are used when following a
10145 link, please customize `org-link-frame-setup'.
10147 If the file does not exist, an error is thrown."
10148 (let* ((file (if (equal path "")
10149 buffer-file-name
10150 (substitute-in-file-name (expand-file-name path))))
10151 (file-apps (append org-file-apps (org-default-apps)))
10152 (apps (org-remove-if
10153 'org-file-apps-entry-match-against-dlink-p file-apps))
10154 (apps-dlink (org-remove-if-not
10155 'org-file-apps-entry-match-against-dlink-p file-apps))
10156 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10157 (dirp (if remp nil (file-directory-p file)))
10158 (file (if (and dirp org-open-directory-means-index-dot-org)
10159 (concat (file-name-as-directory file) "index.org")
10160 file))
10161 (a-m-a-p (assq 'auto-mode apps))
10162 (dfile (downcase file))
10163 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10164 (link (cond ((and (eq line nil)
10165 (eq search nil))
10166 file)
10167 (line
10168 (concat file "::" (number-to-string line)))
10169 (search
10170 (concat file "::" search))))
10171 (dlink (downcase link))
10172 (old-buffer (current-buffer))
10173 (old-pos (point))
10174 (old-mode major-mode)
10175 ext cmd link-match-data)
10176 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10177 (setq ext (match-string 1 dfile))
10178 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10179 (setq ext (match-string 1 dfile))))
10180 (cond
10181 ((member in-emacs '((16) system))
10182 (setq cmd (cdr (assoc 'system apps))))
10183 (in-emacs (setq cmd 'emacs))
10185 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10186 (and dirp (cdr (assoc 'directory apps)))
10187 ; first, try matching against apps-dlink
10188 ; if we get a match here, store the match data for later
10189 (let ((match (assoc-default dlink apps-dlink
10190 'string-match)))
10191 (if match
10192 (progn (setq link-match-data (match-data))
10193 match)
10194 (progn (setq in-emacs (or in-emacs line search))
10195 nil))) ; if we have no match in apps-dlink,
10196 ; always open the file in emacs if line or search
10197 ; is given (for backwards compatibility)
10198 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10199 'string-match)
10200 (cdr (assoc ext apps))
10201 (cdr (assoc t apps))))))
10202 (when (eq cmd 'system)
10203 (setq cmd (cdr (assoc 'system apps))))
10204 (when (eq cmd 'default)
10205 (setq cmd (cdr (assoc t apps))))
10206 (when (eq cmd 'mailcap)
10207 (require 'mailcap)
10208 (mailcap-parse-mailcaps)
10209 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10210 (command (mailcap-mime-info mime-type)))
10211 (if (stringp command)
10212 (setq cmd command)
10213 (setq cmd 'emacs))))
10214 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10215 (not (file-exists-p file))
10216 (not org-open-non-existing-files))
10217 (error "No such file: %s" file))
10218 (cond
10219 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10220 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10221 (while (string-match "['\"]%s['\"]" cmd)
10222 (setq cmd (replace-match "%s" t t cmd)))
10223 (while (string-match "%s" cmd)
10224 (setq cmd (replace-match
10225 (save-match-data
10226 (shell-quote-argument
10227 (convert-standard-filename file)))
10228 t t cmd)))
10230 ;; Replace "%1", "%2" etc. in command with group matches from regex
10231 (save-match-data
10232 (let ((match-index 1)
10233 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10234 (set-match-data link-match-data)
10235 (while (<= match-index number-of-groups)
10236 (let ((regex (concat "%" (number-to-string match-index)))
10237 (replace-with (match-string match-index dlink)))
10238 (while (string-match regex cmd)
10239 (setq cmd (replace-match replace-with t t cmd))))
10240 (setq match-index (+ match-index 1)))))
10242 (save-window-excursion
10243 (start-process-shell-command cmd nil cmd)
10244 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10246 ((or (stringp cmd)
10247 (eq cmd 'emacs))
10248 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10249 (widen)
10250 (if line (org-goto-line line)
10251 (if search (org-link-search search))))
10252 ((consp cmd)
10253 (let ((file (convert-standard-filename file)))
10254 (save-match-data
10255 (set-match-data link-match-data)
10256 (eval cmd))))
10257 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10258 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10259 (or (not (equal old-buffer (current-buffer)))
10260 (not (equal old-pos (point))))
10261 (org-mark-ring-push old-pos old-buffer))))
10263 (defun org-file-apps-entry-match-against-dlink-p (entry)
10264 "This function returns non-nil if `entry' uses a regular
10265 expression which should be matched against the whole link by
10266 org-open-file.
10268 It assumes that is the case when the entry uses a regular
10269 expression which has at least one grouping construct and the
10270 action is either a lisp form or a command string containing
10271 '%1', i.e. using at least one subexpression match as a
10272 parameter."
10273 (let ((selector (car entry))
10274 (action (cdr entry)))
10275 (if (stringp selector)
10276 (and (> (regexp-opt-depth selector) 0)
10277 (or (and (stringp action)
10278 (string-match "%[0-9]" action))
10279 (consp action)))
10280 nil)))
10282 (defun org-default-apps ()
10283 "Return the default applications for this operating system."
10284 (cond
10285 ((eq system-type 'darwin)
10286 org-file-apps-defaults-macosx)
10287 ((eq system-type 'windows-nt)
10288 org-file-apps-defaults-windowsnt)
10289 (t org-file-apps-defaults-gnu)))
10291 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10292 "Convert extensions to regular expressions in the cars of LIST.
10293 Also, weed out any non-string entries, because the return value is used
10294 only for regexp matching.
10295 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10296 point to the symbol `emacs', indicating that the file should
10297 be opened in Emacs."
10298 (append
10299 (delq nil
10300 (mapcar (lambda (x)
10301 (if (not (stringp (car x)))
10303 (if (string-match "\\W" (car x))
10305 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10306 list))
10307 (if add-auto-mode
10308 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10310 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10311 (defun org-file-remote-p (file)
10312 "Test whether FILE specifies a location on a remote system.
10313 Return non-nil if the location is indeed remote.
10315 For example, the filename \"/user@host:/foo\" specifies a location
10316 on the system \"/user@host:\"."
10317 (cond ((fboundp 'file-remote-p)
10318 (file-remote-p file))
10319 ((fboundp 'tramp-handle-file-remote-p)
10320 (tramp-handle-file-remote-p file))
10321 ((and (boundp 'ange-ftp-name-format)
10322 (string-match (car ange-ftp-name-format) file))
10324 (t nil)))
10327 ;;;; Refiling
10329 (defun org-get-org-file ()
10330 "Read a filename, with default directory `org-directory'."
10331 (let ((default (or org-default-notes-file remember-data-file)))
10332 (read-file-name (format "File name [%s]: " default)
10333 (file-name-as-directory org-directory)
10334 default)))
10336 (defun org-notes-order-reversed-p ()
10337 "Check if the current file should receive notes in reversed order."
10338 (cond
10339 ((not org-reverse-note-order) nil)
10340 ((eq t org-reverse-note-order) t)
10341 ((not (listp org-reverse-note-order)) nil)
10342 (t (catch 'exit
10343 (let ((all org-reverse-note-order)
10344 entry)
10345 (while (setq entry (pop all))
10346 (if (string-match (car entry) buffer-file-name)
10347 (throw 'exit (cdr entry))))
10348 nil)))))
10350 (defvar org-refile-target-table nil
10351 "The list of refile targets, created by `org-refile'.")
10353 (defvar org-agenda-new-buffers nil
10354 "Buffers created to visit agenda files.")
10356 (defvar org-refile-cache nil
10357 "Cache for refile targets.")
10359 (defvar org-refile-markers nil
10360 "All the markers used for caching refile locations.")
10362 (defun org-refile-marker (pos)
10363 "Get a new refile marker, but only if caching is in use."
10364 (if (not org-refile-use-cache)
10366 (let ((m (make-marker)))
10367 (move-marker m pos)
10368 (push m org-refile-markers)
10369 m)))
10371 (defun org-refile-cache-clear ()
10372 "Clear the refile cache and disable all the markers."
10373 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10374 (setq org-refile-markers nil)
10375 (setq org-refile-cache nil)
10376 (message "Refile cache has been cleared"))
10378 (defun org-refile-cache-check-set (set)
10379 "Check if all the markers in the cache still have live buffers."
10380 (let (marker)
10381 (catch 'exit
10382 (while (and set (setq marker (nth 3 (pop set))))
10383 ;; if org-refile-use-outline-path is 'file, marker may be nil
10384 (when (and marker (null (marker-buffer marker)))
10385 (message "not found") (sit-for 3)
10386 (throw 'exit nil)))
10387 t)))
10389 (defun org-refile-cache-put (set &rest identifiers)
10390 "Push the refile targets SET into the cache, under IDENTIFIERS."
10391 (let* ((key (sha1 (prin1-to-string identifiers)))
10392 (entry (assoc key org-refile-cache)))
10393 (if entry
10394 (setcdr entry set)
10395 (push (cons key set) org-refile-cache))))
10397 (defun org-refile-cache-get (&rest identifiers)
10398 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10399 (cond
10400 ((not org-refile-cache) nil)
10401 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10403 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10404 org-refile-cache))))
10405 (and set (org-refile-cache-check-set set) set)))))
10407 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10408 "Produce a table with refile targets."
10409 (let ((case-fold-search nil)
10410 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10411 (entries (or org-refile-targets '((nil . (:level . 1)))))
10412 targets tgs txt re files f desc descre fast-path-p level pos0)
10413 (message "Getting targets...")
10414 (with-current-buffer (or default-buffer (current-buffer))
10415 (while (setq entry (pop entries))
10416 (setq files (car entry) desc (cdr entry))
10417 (setq fast-path-p nil)
10418 (cond
10419 ((null files) (setq files (list (current-buffer))))
10420 ((eq files 'org-agenda-files)
10421 (setq files (org-agenda-files 'unrestricted)))
10422 ((and (symbolp files) (fboundp files))
10423 (setq files (funcall files)))
10424 ((and (symbolp files) (boundp files))
10425 (setq files (symbol-value files))))
10426 (if (stringp files) (setq files (list files)))
10427 (cond
10428 ((eq (car desc) :tag)
10429 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10430 ((eq (car desc) :todo)
10431 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10432 ((eq (car desc) :regexp)
10433 (setq descre (cdr desc)))
10434 ((eq (car desc) :level)
10435 (setq descre (concat "^\\*\\{" (number-to-string
10436 (if org-odd-levels-only
10437 (1- (* 2 (cdr desc)))
10438 (cdr desc)))
10439 "\\}[ \t]")))
10440 ((eq (car desc) :maxlevel)
10441 (setq fast-path-p t)
10442 (setq descre (concat "^\\*\\{1," (number-to-string
10443 (if org-odd-levels-only
10444 (1- (* 2 (cdr desc)))
10445 (cdr desc)))
10446 "\\}[ \t]")))
10447 (t (error "Bad refiling target description %s" desc)))
10448 (while (setq f (pop files))
10449 (with-current-buffer
10450 (if (bufferp f) f (org-get-agenda-file-buffer f))
10452 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10453 (progn
10454 (if (bufferp f) (setq f (buffer-file-name
10455 (buffer-base-buffer f))))
10456 (setq f (and f (expand-file-name f)))
10457 (if (eq org-refile-use-outline-path 'file)
10458 (push (list (file-name-nondirectory f) f nil nil) tgs))
10459 (save-excursion
10460 (save-restriction
10461 (widen)
10462 (goto-char (point-min))
10463 (while (re-search-forward descre nil t)
10464 (goto-char (setq pos0 (point-at-bol)))
10465 (catch 'next
10466 (when org-refile-target-verify-function
10467 (save-match-data
10468 (or (funcall org-refile-target-verify-function)
10469 (throw 'next t))))
10470 (when (and (looking-at org-complex-heading-regexp)
10471 (not (member (match-string 4) excluded-entries))
10472 (match-string 4))
10473 (setq level (org-reduced-level
10474 (- (match-end 1) (match-beginning 1)))
10475 txt (org-link-display-format (match-string 4))
10476 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10477 re (format org-complex-heading-regexp-format
10478 (regexp-quote (match-string 4))))
10479 (when org-refile-use-outline-path
10480 (setq txt (mapconcat
10481 'org-protect-slash
10482 (append
10483 (if (eq org-refile-use-outline-path
10484 'file)
10485 (list (file-name-nondirectory
10486 (buffer-file-name
10487 (buffer-base-buffer))))
10488 (if (eq org-refile-use-outline-path
10489 'full-file-path)
10490 (list (buffer-file-name
10491 (buffer-base-buffer)))))
10492 (org-get-outline-path fast-path-p
10493 level txt)
10494 (list txt))
10495 "/")))
10496 (push (list txt f re (org-refile-marker (point)))
10497 tgs)))
10498 (when (= (point) pos0)
10499 ;; verification function has not moved point
10500 (goto-char (point-at-eol))))))))
10501 (when org-refile-use-cache
10502 (org-refile-cache-put tgs (buffer-file-name) descre))
10503 (setq targets (append tgs targets))
10504 ))))
10505 (message "Getting targets...done")
10506 (nreverse targets)))
10508 (defun org-protect-slash (s)
10509 (while (string-match "/" s)
10510 (setq s (replace-match "\\" t t s)))
10513 (defvar org-olpa (make-vector 20 nil))
10515 (defun org-get-outline-path (&optional fastp level heading)
10516 "Return the outline path to the current entry, as a list.
10518 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10519 routine which makes outline path derivations for an entire file,
10520 avoiding backtracing. Refile target collection makes use of that."
10521 (if fastp
10522 (progn
10523 (if (> level 19)
10524 (error "Outline path failure, more than 19 levels"))
10525 (loop for i from level upto 19 do
10526 (aset org-olpa i nil))
10527 (prog1
10528 (delq nil (append org-olpa nil))
10529 (aset org-olpa level heading)))
10530 (let (rtn case-fold-search)
10531 (save-excursion
10532 (save-restriction
10533 (widen)
10534 (while (org-up-heading-safe)
10535 (when (looking-at org-complex-heading-regexp)
10536 (push (org-match-string-no-properties 4) rtn)))
10537 rtn)))))
10539 (defun org-format-outline-path (path &optional width prefix)
10540 "Format the outline path PATH for display.
10541 Width is the maximum number of characters that is available.
10542 Prefix is a prefix to be included in the returned string,
10543 such as the file name."
10544 (setq width (or width 79))
10545 (if prefix (setq width (- width (length prefix))))
10546 (if (not path)
10547 (or prefix "")
10548 (let* ((nsteps (length path))
10549 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10550 (maxwidth (if (<= total-width width)
10551 10000 ;; everything fits
10552 ;; we need to shorten the level headings
10553 (/ (- width nsteps) nsteps)))
10554 (org-odd-levels-only nil)
10555 (n 0)
10556 (total (1+ (length prefix))))
10557 (setq maxwidth (max maxwidth 10))
10558 (concat prefix
10559 (mapconcat
10560 (lambda (h)
10561 (setq n (1+ n))
10562 (if (and (= n nsteps) (< maxwidth 10000))
10563 (setq maxwidth (- total-width total)))
10564 (if (< (length h) maxwidth)
10565 (progn (setq total (+ total (length h) 1)) h)
10566 (setq h (substring h 0 (- maxwidth 2))
10567 total (+ total maxwidth 1))
10568 (if (string-match "[ \t]+\\'" h)
10569 (setq h (substring h 0 (match-beginning 0))))
10570 (setq h (concat h "..")))
10571 (org-add-props h nil 'face
10572 (nth (% (1- n) org-n-level-faces)
10573 org-level-faces))
10575 path "/")))))
10577 (defun org-display-outline-path (&optional file current)
10578 "Display the current outline path in the echo area."
10579 (interactive "P")
10580 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10581 (case-fold-search nil)
10582 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10583 (if current (setq path (append path
10584 (save-excursion
10585 (org-back-to-heading t)
10586 (if (looking-at org-complex-heading-regexp)
10587 (list (match-string 4)))))))
10588 (message "%s"
10589 (org-format-outline-path
10590 path
10591 (1- (frame-width))
10592 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10594 (defvar org-refile-history nil
10595 "History for refiling operations.")
10597 (defvar org-after-refile-insert-hook nil
10598 "Hook run after `org-refile' has inserted its stuff at the new location.
10599 Note that this is still *before* the stuff will be removed from
10600 the *old* location.")
10602 (defvar org-capture-last-stored-marker)
10603 (defun org-refile (&optional goto default-buffer rfloc)
10604 "Move the entry or entries at point to another heading.
10605 The list of target headings is compiled using the information in
10606 `org-refile-targets', which see.
10608 At the target location, the entry is filed as a subitem of the target
10609 heading. Depending on `org-reverse-note-order', the new subitem will
10610 either be the first or the last subitem.
10612 If there is an active region, all entries in that region will be moved.
10613 However, the region must fulfill the requirement that the first heading
10614 is the first one sets the top-level of the moved text - at most siblings
10615 below it are allowed.
10617 With prefix arg GOTO, the command will only visit the target location
10618 and not actually move anything.
10620 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10621 go to the location where the last refiling operation has put the subtree.
10622 With a prefix argument of `2', refile to the running clock.
10624 RFLOC can be a refile location obtained in a different way.
10626 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10628 If you are using target caching (see `org-refile-use-cache'),
10629 You have to clear the target cache in order to find new targets.
10630 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10631 prefix argument (`C-u C-u C-u C-c C-w')."
10633 (interactive "P")
10634 (if (member goto '(0 (64)))
10635 (org-refile-cache-clear)
10636 (let* ((cbuf (current-buffer))
10637 (regionp (org-region-active-p))
10638 (region-start (and regionp (region-beginning)))
10639 (region-end (and regionp (region-end)))
10640 (region-length (and regionp (- region-end region-start)))
10641 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10642 pos it nbuf file re level reversed)
10643 (setq last-command nil)
10644 (when regionp
10645 (goto-char region-start)
10646 (or (bolp) (goto-char (point-at-bol)))
10647 (setq region-start (point))
10648 (unless (or (org-kill-is-subtree-p
10649 (buffer-substring region-start region-end))
10650 (prog1 org-refile-active-region-within-subtree
10651 (org-toggle-heading)))
10652 (error "The region is not a (sequence of) subtree(s)")))
10653 (if (equal goto '(16))
10654 (org-refile-goto-last-stored)
10655 (when (or
10656 (and (equal goto 2)
10657 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10658 (prog1
10659 (setq it (list (or org-clock-heading "running clock")
10660 (buffer-file-name
10661 (marker-buffer org-clock-hd-marker))
10663 (marker-position org-clock-hd-marker)))
10664 (setq goto nil)))
10665 (setq it (or rfloc
10666 (let (heading-text)
10667 (save-excursion
10668 (unless goto
10669 (org-back-to-heading t)
10670 (setq heading-text
10671 (nth 4 (org-heading-components))))
10672 (org-refile-get-location
10673 (cond (goto "Goto")
10674 (regionp "Refile region to")
10675 (t (concat "Refile subtree \""
10676 heading-text "\" to")))
10677 default-buffer
10678 (and (not (equal '(4) goto))
10679 org-refile-allow-creating-parent-nodes)
10680 goto))))))
10681 (setq file (nth 1 it)
10682 re (nth 2 it)
10683 pos (nth 3 it))
10684 (if (and (not goto)
10686 (equal (buffer-file-name) file)
10687 (if regionp
10688 (and (>= pos region-start)
10689 (<= pos region-end))
10690 (and (>= pos (point))
10691 (< pos (save-excursion
10692 (org-end-of-subtree t t))))))
10693 (error "Cannot refile to position inside the tree or region"))
10695 (setq nbuf (or (find-buffer-visiting file)
10696 (find-file-noselect file)))
10697 (if goto
10698 (progn
10699 (org-pop-to-buffer-same-window nbuf)
10700 (goto-char pos)
10701 (org-show-context 'org-goto))
10702 (if regionp
10703 (progn
10704 (org-kill-new (buffer-substring region-start region-end))
10705 (org-save-markers-in-region region-start region-end))
10706 (org-copy-subtree 1 nil t))
10707 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10708 (find-file-noselect file)))
10709 (setq reversed (org-notes-order-reversed-p))
10710 (save-excursion
10711 (save-restriction
10712 (widen)
10713 (if pos
10714 (progn
10715 (goto-char pos)
10716 (looking-at org-outline-regexp)
10717 (setq level (org-get-valid-level (funcall outline-level) 1))
10718 (goto-char
10719 (if reversed
10720 (or (outline-next-heading) (point-max))
10721 (or (save-excursion (org-get-next-sibling))
10722 (org-end-of-subtree t t)
10723 (point-max)))))
10724 (setq level 1)
10725 (if (not reversed)
10726 (goto-char (point-max))
10727 (goto-char (point-min))
10728 (or (outline-next-heading) (goto-char (point-max)))))
10729 (if (not (bolp)) (newline))
10730 (org-paste-subtree level)
10731 (when org-log-refile
10732 (org-add-log-setup 'refile nil nil 'findpos
10733 org-log-refile)
10734 (unless (eq org-log-refile 'note)
10735 (save-excursion (org-add-log-note))))
10736 (and org-auto-align-tags (org-set-tags nil t))
10737 (bookmark-set "org-refile-last-stored")
10738 ;; If we are refiling for capture, make sure that the
10739 ;; last-capture pointers point here
10740 (when (org-bound-and-true-p org-refile-for-capture)
10741 (bookmark-set "org-capture-last-stored-marker")
10742 (move-marker org-capture-last-stored-marker (point)))
10743 (if (fboundp 'deactivate-mark) (deactivate-mark))
10744 (run-hooks 'org-after-refile-insert-hook))))
10745 (if regionp
10746 (delete-region (point) (+ (point) region-length))
10747 (org-cut-subtree))
10748 (when (featurep 'org-inlinetask)
10749 (org-inlinetask-remove-END-maybe))
10750 (setq org-markers-to-move nil)
10751 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10753 (defun org-refile-goto-last-stored ()
10754 "Go to the location where the last refile was stored."
10755 (interactive)
10756 (bookmark-jump "org-refile-last-stored")
10757 (message "This is the location of the last refile"))
10759 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10760 no-exclude)
10761 "Prompt the user for a refile location, using PROMPT.
10762 PROMPT should not be suffixed with a colon and a space, because
10763 this function appends the default value from
10764 `org-refile-history' automatically, if that is not empty.
10765 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10766 this is used for the GOTO interface."
10767 (let ((org-refile-targets org-refile-targets)
10768 (org-refile-use-outline-path org-refile-use-outline-path)
10769 excluded-entries)
10770 (when (and (eq major-mode 'org-mode)
10771 (not org-refile-use-cache)
10772 (not no-exclude))
10773 (org-map-tree
10774 (lambda()
10775 (setq excluded-entries
10776 (append excluded-entries (list (org-get-heading t t)))))))
10777 (setq org-refile-target-table
10778 (org-refile-get-targets default-buffer excluded-entries)))
10779 (unless org-refile-target-table
10780 (error "No refile targets"))
10781 (let* ((prompt (concat prompt
10782 (and (car org-refile-history)
10783 (concat " (default " (car org-refile-history) ")"))
10784 ": "))
10785 (cbuf (current-buffer))
10786 (partial-completion-mode nil)
10787 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10788 (cfunc (if (and org-refile-use-outline-path
10789 org-outline-path-complete-in-steps)
10790 'org-olpath-completing-read
10791 'org-icompleting-read))
10792 (extra (if org-refile-use-outline-path "/" ""))
10793 (filename (and cfn (expand-file-name cfn)))
10794 (tbl (mapcar
10795 (lambda (x)
10796 (if (and (not (member org-refile-use-outline-path
10797 '(file full-file-path)))
10798 (not (equal filename (nth 1 x))))
10799 (cons (concat (car x) extra " ("
10800 (file-name-nondirectory (nth 1 x)) ")")
10801 (cdr x))
10802 (cons (concat (car x) extra) (cdr x))))
10803 org-refile-target-table))
10804 (completion-ignore-case t)
10805 pa answ parent-target child parent old-hist)
10806 (setq old-hist org-refile-history)
10807 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10808 nil 'org-refile-history (car org-refile-history)))
10809 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10810 (org-refile-check-position pa)
10811 (if pa
10812 (progn
10813 (when (or (not org-refile-history)
10814 (not (eq old-hist org-refile-history))
10815 (not (equal (car pa) (car org-refile-history))))
10816 (setq org-refile-history
10817 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10818 org-refile-history
10819 (cdr org-refile-history))))
10820 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10821 (pop org-refile-history)))
10823 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10824 (progn
10825 (setq parent (match-string 1 answ)
10826 child (match-string 2 answ))
10827 (setq parent-target (or (assoc parent tbl)
10828 (assoc (concat parent "/") tbl)))
10829 (when (and parent-target
10830 (or (eq new-nodes t)
10831 (and (eq new-nodes 'confirm)
10832 (y-or-n-p (format "Create new node \"%s\"? "
10833 child)))))
10834 (org-refile-new-child parent-target child)))
10835 (error "Invalid target location")))))
10837 (defun org-refile-check-position (refile-pointer)
10838 "Check if the refile pointer matches the readline to which it points."
10839 (let* ((file (nth 1 refile-pointer))
10840 (re (nth 2 refile-pointer))
10841 (pos (nth 3 refile-pointer))
10842 buffer)
10843 (when (org-string-nw-p re)
10844 (setq buffer (if (markerp pos)
10845 (marker-buffer pos)
10846 (or (find-buffer-visiting file)
10847 (find-file-noselect file))))
10848 (with-current-buffer buffer
10849 (save-excursion
10850 (save-restriction
10851 (widen)
10852 (goto-char pos)
10853 (beginning-of-line 1)
10854 (unless (org-looking-at-p re)
10855 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10857 (defun org-refile-new-child (parent-target child)
10858 "Use refile target PARENT-TARGET to add new CHILD below it."
10859 (unless parent-target
10860 (error "Cannot find parent for new node"))
10861 (let ((file (nth 1 parent-target))
10862 (pos (nth 3 parent-target))
10863 level)
10864 (with-current-buffer (or (find-buffer-visiting file)
10865 (find-file-noselect file))
10866 (save-excursion
10867 (save-restriction
10868 (widen)
10869 (if pos
10870 (goto-char pos)
10871 (goto-char (point-max))
10872 (if (not (bolp)) (newline)))
10873 (when (looking-at org-outline-regexp)
10874 (setq level (funcall outline-level))
10875 (org-end-of-subtree t t))
10876 (org-back-over-empty-lines)
10877 (insert "\n" (make-string
10878 (if pos (org-get-valid-level level 1) 1) ?*)
10879 " " child "\n")
10880 (beginning-of-line 0)
10881 (list (concat (car parent-target) "/" child) file "" (point)))))))
10883 (defun org-olpath-completing-read (prompt collection &rest args)
10884 "Read an outline path like a file name."
10885 (let ((thetable collection)
10886 (org-completion-use-ido nil) ; does not work with ido.
10887 (org-completion-use-iswitchb nil)) ; or iswitchb
10888 (apply
10889 'org-icompleting-read prompt
10890 (lambda (string predicate &optional flag)
10891 (let (rtn r f (l (length string)))
10892 (cond
10893 ((eq flag nil)
10894 ;; try completion
10895 (try-completion string thetable))
10896 ((eq flag t)
10897 ;; all-completions
10898 (setq rtn (all-completions string thetable predicate))
10899 (mapcar
10900 (lambda (x)
10901 (setq r (substring x l))
10902 (if (string-match " ([^)]*)$" x)
10903 (setq f (match-string 0 x))
10904 (setq f ""))
10905 (if (string-match "/" r)
10906 (concat string (substring r 0 (match-end 0)) f)
10908 rtn))
10909 ((eq flag 'lambda)
10910 ;; exact match?
10911 (assoc string thetable)))
10913 args)))
10915 ;;;; Dynamic blocks
10917 (defun org-find-dblock (name)
10918 "Find the first dynamic block with name NAME in the buffer.
10919 If not found, stay at current position and return nil."
10920 (let (pos)
10921 (save-excursion
10922 (goto-char (point-min))
10923 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10924 nil t)
10925 (match-beginning 0))))
10926 (if pos (goto-char pos))
10927 pos))
10929 (defconst org-dblock-start-re
10930 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10931 "Matches the start line of a dynamic block, with parameters.")
10933 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10934 "Matches the end of a dynamic block.")
10936 (defun org-create-dblock (plist)
10937 "Create a dynamic block section, with parameters taken from PLIST.
10938 PLIST must contain a :name entry which is used as name of the block."
10939 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10940 (end-of-line 1)
10941 (newline))
10942 (let ((col (current-column))
10943 (name (plist-get plist :name)))
10944 (insert "#+BEGIN: " name)
10945 (while plist
10946 (if (eq (car plist) :name)
10947 (setq plist (cddr plist))
10948 (insert " " (prin1-to-string (pop plist)))))
10949 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10950 (beginning-of-line -2)))
10952 (defun org-prepare-dblock ()
10953 "Prepare dynamic block for refresh.
10954 This empties the block, puts the cursor at the insert position and returns
10955 the property list including an extra property :name with the block name."
10956 (unless (looking-at org-dblock-start-re)
10957 (error "Not at a dynamic block"))
10958 (let* ((begdel (1+ (match-end 0)))
10959 (name (org-no-properties (match-string 1)))
10960 (params (append (list :name name)
10961 (read (concat "(" (match-string 3) ")")))))
10962 (save-excursion
10963 (beginning-of-line 1)
10964 (skip-chars-forward " \t")
10965 (setq params (plist-put params :indentation-column (current-column))))
10966 (unless (re-search-forward org-dblock-end-re nil t)
10967 (error "Dynamic block not terminated"))
10968 (setq params
10969 (append params
10970 (list :content (buffer-substring
10971 begdel (match-beginning 0)))))
10972 (delete-region begdel (match-beginning 0))
10973 (goto-char begdel)
10974 (open-line 1)
10975 params))
10977 (defun org-map-dblocks (&optional command)
10978 "Apply COMMAND to all dynamic blocks in the current buffer.
10979 If COMMAND is not given, use `org-update-dblock'."
10980 (let ((cmd (or command 'org-update-dblock)))
10981 (save-excursion
10982 (goto-char (point-min))
10983 (while (re-search-forward org-dblock-start-re nil t)
10984 (goto-char (match-beginning 0))
10985 (save-excursion
10986 (condition-case nil
10987 (funcall cmd)
10988 (error (message "Error during update of dynamic block"))))
10989 (unless (re-search-forward org-dblock-end-re nil t)
10990 (error "Dynamic block not terminated"))))))
10992 (defun org-dblock-update (&optional arg)
10993 "User command for updating dynamic blocks.
10994 Update the dynamic block at point. With prefix ARG, update all dynamic
10995 blocks in the buffer."
10996 (interactive "P")
10997 (if arg
10998 (org-update-all-dblocks)
10999 (or (looking-at org-dblock-start-re)
11000 (org-beginning-of-dblock))
11001 (org-update-dblock)))
11003 (defun org-update-dblock ()
11004 "Update the dynamic block at point.
11005 This means to empty the block, parse for parameters and then call
11006 the correct writing function."
11007 (interactive)
11008 (save-window-excursion
11009 (let* ((pos (point))
11010 (line (org-current-line))
11011 (params (org-prepare-dblock))
11012 (name (plist-get params :name))
11013 (indent (plist-get params :indentation-column))
11014 (cmd (intern (concat "org-dblock-write:" name))))
11015 (message "Updating dynamic block `%s' at line %d..." name line)
11016 (funcall cmd params)
11017 (message "Updating dynamic block `%s' at line %d...done" name line)
11018 (goto-char pos)
11019 (when (and indent (> indent 0))
11020 (setq indent (make-string indent ?\ ))
11021 (save-excursion
11022 (org-beginning-of-dblock)
11023 (forward-line 1)
11024 (while (not (looking-at org-dblock-end-re))
11025 (insert indent)
11026 (beginning-of-line 2))
11027 (when (looking-at org-dblock-end-re)
11028 (and (looking-at "[ \t]+")
11029 (replace-match ""))
11030 (insert indent)))))))
11032 (defun org-beginning-of-dblock ()
11033 "Find the beginning of the dynamic block at point.
11034 Error if there is no such block at point."
11035 (let ((pos (point))
11036 beg)
11037 (end-of-line 1)
11038 (if (and (re-search-backward org-dblock-start-re nil t)
11039 (setq beg (match-beginning 0))
11040 (re-search-forward org-dblock-end-re nil t)
11041 (> (match-end 0) pos))
11042 (goto-char beg)
11043 (goto-char pos)
11044 (error "Not in a dynamic block"))))
11046 (defun org-update-all-dblocks ()
11047 "Update all dynamic blocks in the buffer.
11048 This function can be used in a hook."
11049 (interactive)
11050 (when (eq major-mode 'org-mode)
11051 (org-map-dblocks 'org-update-dblock)))
11054 ;;;; Completion
11056 (defconst org-additional-option-like-keywords
11057 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11058 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11059 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11060 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11061 "BEGIN:" "END:"
11062 "ORGTBL" "TBLFM:" "TBLNAME:"
11063 "BEGIN_EXAMPLE" "END_EXAMPLE"
11064 "BEGIN_QUOTE" "END_QUOTE"
11065 "BEGIN_VERSE" "END_VERSE"
11066 "BEGIN_CENTER" "END_CENTER"
11067 "BEGIN_SRC" "END_SRC"
11068 "BEGIN_RESULT" "END_RESULT"
11069 "NAME:" "RESULTS:"
11070 "HEADER:" "HEADERS:"
11071 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11072 "CAPTION:" "LABEL:"
11073 "SETUPFILE:"
11074 "INCLUDE:"
11075 "BIND:"
11076 "MACRO:"))
11078 (defcustom org-structure-template-alist
11080 ("s" "#+begin_src ?\n\n#+end_src"
11081 "<src lang=\"?\">\n\n</src>")
11082 ("e" "#+begin_example\n?\n#+end_example"
11083 "<example>\n?\n</example>")
11084 ("q" "#+begin_quote\n?\n#+end_quote"
11085 "<quote>\n?\n</quote>")
11086 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11087 "<verse>\n?\n</verse>")
11088 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11089 "<center>\n?\n</center>")
11090 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11091 "<literal style=\"latex\">\n?\n</literal>")
11092 ("L" "#+latex: "
11093 "<literal style=\"latex\">?</literal>")
11094 ("h" "#+begin_html\n?\n#+end_html"
11095 "<literal style=\"html\">\n?\n</literal>")
11096 ("H" "#+html: "
11097 "<literal style=\"html\">?</literal>")
11098 ("a" "#+begin_ascii\n?\n#+end_ascii")
11099 ("A" "#+ascii: ")
11100 ("i" "#+index: ?"
11101 "#+index: ?")
11102 ("I" "#+include %file ?"
11103 "<include file=%file markup=\"?\">")
11105 "Structure completion elements.
11106 This is a list of abbreviation keys and values. The value gets inserted
11107 if you type `<' followed by the key and then press the completion key,
11108 usually `M-TAB'. %file will be replaced by a file name after prompting
11109 for the file using completion. The cursor will be placed at the position
11110 of the `?` in the template.
11111 There are two templates for each key, the first uses the original Org syntax,
11112 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11113 the default when the /org-mtags.el/ module has been loaded. See also the
11114 variable `org-mtags-prefer-muse-templates'.
11115 This is an experimental feature, it is undecided if it is going to stay in."
11116 :group 'org-completion
11117 :type '(repeat
11118 (string :tag "Key")
11119 (string :tag "Template")
11120 (string :tag "Muse Template")))
11122 (defun org-try-structure-completion ()
11123 "Try to complete a structure template before point.
11124 This looks for strings like \"<e\" on an otherwise empty line and
11125 expands them."
11126 (let ((l (buffer-substring (point-at-bol) (point)))
11128 (when (and (looking-at "[ \t]*$")
11129 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11130 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11131 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11132 (match-beginning 1)) a)
11133 t)))
11135 (defun org-complete-expand-structure-template (start cell)
11136 "Expand a structure template."
11137 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11138 (rpl (nth (if musep 2 1) cell))
11139 (ind ""))
11140 (delete-region start (point))
11141 (when (string-match "\\`#\\+" rpl)
11142 (cond
11143 ((bolp))
11144 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11145 (setq ind (buffer-substring (point-at-bol) (point))))
11146 (t (newline))))
11147 (setq start (point))
11148 (if (string-match "%file" rpl)
11149 (setq rpl (replace-match
11150 (concat
11151 "\""
11152 (save-match-data
11153 (abbreviate-file-name (read-file-name "Include file: ")))
11154 "\"")
11155 t t rpl)))
11156 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11157 (concat "\n" ind)))
11158 (insert rpl)
11159 (if (re-search-backward "\\?" start t) (delete-char 1))))
11161 ;;;; TODO, DEADLINE, Comments
11163 (defun org-toggle-comment ()
11164 "Change the COMMENT state of an entry."
11165 (interactive)
11166 (save-excursion
11167 (org-back-to-heading)
11168 (let (case-fold-search)
11169 (cond
11170 ((looking-at (format org-heading-keyword-regexp-format
11171 org-comment-string))
11172 (goto-char (match-end 1))
11173 (looking-at (concat " +" org-comment-string))
11174 (replace-match "" t t)
11175 (when (eolp) (insert " ")))
11176 ((looking-at org-outline-regexp)
11177 (goto-char (match-end 0))
11178 (insert org-comment-string " "))))))
11180 (defvar org-last-todo-state-is-todo nil
11181 "This is non-nil when the last TODO state change led to a TODO state.
11182 If the last change removed the TODO tag or switched to DONE, then
11183 this is nil.")
11185 (defvar org-setting-tags nil) ; dynamically skipped
11187 (defvar org-todo-setup-filter-hook nil
11188 "Hook for functions that pre-filter todo specs.
11189 Each function takes a todo spec and returns either nil or the spec
11190 transformed into canonical form." )
11192 (defvar org-todo-get-default-hook nil
11193 "Hook for functions that get a default item for todo.
11194 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11195 nil or a string to be used for the todo mark." )
11197 (defvar org-agenda-headline-snapshot-before-repeat)
11199 (defun org-current-effective-time ()
11200 "Return current time adjusted for `org-extend-today-until' variable"
11201 (let* ((ct (org-current-time))
11202 (dct (decode-time ct))
11203 (ct1
11204 (if (and org-use-effective-time
11205 (< (nth 2 dct) org-extend-today-until))
11206 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11207 ct)))
11208 ct1))
11210 (defun org-todo-yesterday (&optional arg)
11211 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11212 (interactive "P")
11213 (if (eq major-mode 'org-agenda-mode)
11214 (apply 'org-agenda-todo-yesterday arg)
11215 (let* ((hour (third (decode-time
11216 (org-current-time))))
11217 (org-extend-today-until (1+ hour)))
11218 (org-todo arg))))
11220 (defun org-todo (&optional arg)
11221 "Change the TODO state of an item.
11222 The state of an item is given by a keyword at the start of the heading,
11223 like
11224 *** TODO Write paper
11225 *** DONE Call mom
11227 The different keywords are specified in the variable `org-todo-keywords'.
11228 By default the available states are \"TODO\" and \"DONE\".
11229 So for this example: when the item starts with TODO, it is changed to DONE.
11230 When it starts with DONE, the DONE is removed. And when neither TODO nor
11231 DONE are present, add TODO at the beginning of the heading.
11233 With \\[universal-argument] prefix arg, use completion to determine the new \
11234 state.
11235 With numeric prefix arg, switch to that state.
11236 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11237 keywords (nextset).
11238 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11239 With a numeric prefix arg of 0, inhibit note taking for the change.
11241 For calling through lisp, arg is also interpreted in the following way:
11242 'none -> empty state
11243 \"\"(empty string) -> switch to empty state
11244 'done -> switch to DONE
11245 'nextset -> switch to the next set of keywords
11246 'previousset -> switch to the previous set of keywords
11247 \"WAITING\" -> switch to the specified keyword, but only if it
11248 really is a member of `org-todo-keywords'."
11249 (interactive "P")
11250 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11251 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11252 'region-start-level 'region))
11253 org-loop-over-headlines-in-active-region)
11254 (org-map-entries
11255 `(org-todo ,arg)
11256 org-loop-over-headlines-in-active-region
11257 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11258 (if (equal arg '(16)) (setq arg 'nextset))
11259 (let ((org-blocker-hook org-blocker-hook)
11260 (case-fold-search nil))
11261 (when (equal arg '(64))
11262 (setq arg nil org-blocker-hook nil))
11263 (when (and org-blocker-hook
11264 (or org-inhibit-blocking
11265 (org-entry-get nil "NOBLOCKING")))
11266 (setq org-blocker-hook nil))
11267 (save-excursion
11268 (catch 'exit
11269 (org-back-to-heading t)
11270 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11271 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11272 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11273 (let* ((match-data (match-data))
11274 (startpos (point-at-bol))
11275 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11276 (org-log-done org-log-done)
11277 (org-log-repeat org-log-repeat)
11278 (org-todo-log-states org-todo-log-states)
11279 (org-inhibit-logging
11280 (if (equal arg 0)
11281 (progn (setq arg nil) 'note) org-inhibit-logging))
11282 (this (match-string 1))
11283 (hl-pos (match-beginning 0))
11284 (head (org-get-todo-sequence-head this))
11285 (ass (assoc head org-todo-kwd-alist))
11286 (interpret (nth 1 ass))
11287 (done-word (nth 3 ass))
11288 (final-done-word (nth 4 ass))
11289 (org-last-state (or this ""))
11290 (completion-ignore-case t)
11291 (member (member this org-todo-keywords-1))
11292 (tail (cdr member))
11293 (org-state (cond
11294 ((and org-todo-key-trigger
11295 (or (and (equal arg '(4))
11296 (eq org-use-fast-todo-selection 'prefix))
11297 (and (not arg) org-use-fast-todo-selection
11298 (not (eq org-use-fast-todo-selection
11299 'prefix)))))
11300 ;; Use fast selection
11301 (org-fast-todo-selection))
11302 ((and (equal arg '(4))
11303 (or (not org-use-fast-todo-selection)
11304 (not org-todo-key-trigger)))
11305 ;; Read a state with completion
11306 (org-icompleting-read
11307 "State: " (mapcar (lambda(x) (list x))
11308 org-todo-keywords-1)
11309 nil t))
11310 ((eq arg 'right)
11311 (if this
11312 (if tail (car tail) nil)
11313 (car org-todo-keywords-1)))
11314 ((eq arg 'left)
11315 (if (equal member org-todo-keywords-1)
11317 (if this
11318 (nth (- (length org-todo-keywords-1)
11319 (length tail) 2)
11320 org-todo-keywords-1)
11321 (org-last org-todo-keywords-1))))
11322 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11323 (setq arg nil))) ; hack to fall back to cycling
11324 (arg
11325 ;; user or caller requests a specific state
11326 (cond
11327 ((equal arg "") nil)
11328 ((eq arg 'none) nil)
11329 ((eq arg 'done) (or done-word (car org-done-keywords)))
11330 ((eq arg 'nextset)
11331 (or (car (cdr (member head org-todo-heads)))
11332 (car org-todo-heads)))
11333 ((eq arg 'previousset)
11334 (let ((org-todo-heads (reverse org-todo-heads)))
11335 (or (car (cdr (member head org-todo-heads)))
11336 (car org-todo-heads))))
11337 ((car (member arg org-todo-keywords-1)))
11338 ((stringp arg)
11339 (error "State `%s' not valid in this file" arg))
11340 ((nth (1- (prefix-numeric-value arg))
11341 org-todo-keywords-1))))
11342 ((null member) (or head (car org-todo-keywords-1)))
11343 ((equal this final-done-word) nil) ;; -> make empty
11344 ((null tail) nil) ;; -> first entry
11345 ((memq interpret '(type priority))
11346 (if (eq this-command last-command)
11347 (car tail)
11348 (if (> (length tail) 0)
11349 (or done-word (car org-done-keywords))
11350 nil)))
11352 (car tail))))
11353 (org-state (or
11354 (run-hook-with-args-until-success
11355 'org-todo-get-default-hook org-state org-last-state)
11356 org-state))
11357 (next (if org-state (concat " " org-state " ") " "))
11358 (change-plist (list :type 'todo-state-change :from this :to org-state
11359 :position startpos))
11360 dolog now-done-p)
11361 (when org-blocker-hook
11362 (setq org-last-todo-state-is-todo
11363 (not (member this org-done-keywords)))
11364 (unless (save-excursion
11365 (save-match-data
11366 (org-with-wide-buffer
11367 (run-hook-with-args-until-failure
11368 'org-blocker-hook change-plist))))
11369 (if (org-called-interactively-p 'interactive)
11370 (error "TODO state change from %s to %s blocked" this org-state)
11371 ;; fail silently
11372 (message "TODO state change from %s to %s blocked" this org-state)
11373 (throw 'exit nil))))
11374 (store-match-data match-data)
11375 (replace-match next t t)
11376 (unless (pos-visible-in-window-p hl-pos)
11377 (message "TODO state changed to %s" (org-trim next)))
11378 (unless head
11379 (setq head (org-get-todo-sequence-head org-state)
11380 ass (assoc head org-todo-kwd-alist)
11381 interpret (nth 1 ass)
11382 done-word (nth 3 ass)
11383 final-done-word (nth 4 ass)))
11384 (when (memq arg '(nextset previousset))
11385 (message "Keyword-Set %d/%d: %s"
11386 (- (length org-todo-sets) -1
11387 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11388 (length org-todo-sets)
11389 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11390 (setq org-last-todo-state-is-todo
11391 (not (member org-state org-done-keywords)))
11392 (setq now-done-p (and (member org-state org-done-keywords)
11393 (not (member this org-done-keywords))))
11394 (and logging (org-local-logging logging))
11395 (when (and (or org-todo-log-states org-log-done)
11396 (not (eq org-inhibit-logging t))
11397 (not (memq arg '(nextset previousset))))
11398 ;; we need to look at recording a time and note
11399 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11400 (nth 2 (assoc this org-todo-log-states))))
11401 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11402 (setq dolog 'time))
11403 (when (and org-state
11404 (member org-state org-not-done-keywords)
11405 (not (member this org-not-done-keywords)))
11406 ;; This is now a todo state and was not one before
11407 ;; If there was a CLOSED time stamp, get rid of it.
11408 (org-add-planning-info nil nil 'closed))
11409 (when (and now-done-p org-log-done)
11410 ;; It is now done, and it was not done before
11411 (org-add-planning-info 'closed (org-current-effective-time))
11412 (if (and (not dolog) (eq 'note org-log-done))
11413 (org-add-log-setup 'done org-state this 'findpos 'note)))
11414 (when (and org-state dolog)
11415 ;; This is a non-nil state, and we need to log it
11416 (org-add-log-setup 'state org-state this 'findpos dolog)))
11417 ;; Fixup tag positioning
11418 (org-todo-trigger-tag-changes org-state)
11419 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11420 (when org-provide-todo-statistics
11421 (org-update-parent-todo-statistics))
11422 (run-hooks 'org-after-todo-state-change-hook)
11423 (if (and arg (not (member org-state org-done-keywords)))
11424 (setq head (org-get-todo-sequence-head org-state)))
11425 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11426 ;; Do we need to trigger a repeat?
11427 (when now-done-p
11428 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11429 ;; This is for the agenda, take a snapshot of the headline.
11430 (save-match-data
11431 (setq org-agenda-headline-snapshot-before-repeat
11432 (org-get-heading))))
11433 (org-auto-repeat-maybe org-state))
11434 ;; Fixup cursor location if close to the keyword
11435 (if (and (outline-on-heading-p)
11436 (not (bolp))
11437 (save-excursion (beginning-of-line 1)
11438 (looking-at org-todo-line-regexp))
11439 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11440 (progn
11441 (goto-char (or (match-end 2) (match-end 1)))
11442 (and (looking-at " ") (just-one-space))))
11443 (when org-trigger-hook
11444 (save-excursion
11445 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11447 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11448 "Block turning an entry into a TODO, using the hierarchy.
11449 This checks whether the current task should be blocked from state
11450 changes. Such blocking occurs when:
11452 1. The task has children which are not all in a completed state.
11454 2. A task has a parent with the property :ORDERED:, and there
11455 are siblings prior to the current task with incomplete
11456 status.
11458 3. The parent of the task is blocked because it has siblings that should
11459 be done first, or is child of a block grandparent TODO entry."
11461 (if (not org-enforce-todo-dependencies)
11462 t ; if locally turned off don't block
11463 (catch 'dont-block
11464 ;; If this is not a todo state change, or if this entry is already DONE,
11465 ;; do not block
11466 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11467 (member (plist-get change-plist :from)
11468 (cons 'done org-done-keywords))
11469 (member (plist-get change-plist :to)
11470 (cons 'todo org-not-done-keywords))
11471 (not (plist-get change-plist :to)))
11472 (throw 'dont-block t))
11473 ;; If this task has children, and any are undone, it's blocked
11474 (save-excursion
11475 (org-back-to-heading t)
11476 (let ((this-level (funcall outline-level)))
11477 (outline-next-heading)
11478 (let ((child-level (funcall outline-level)))
11479 (while (and (not (eobp))
11480 (> child-level this-level))
11481 ;; this todo has children, check whether they are all
11482 ;; completed
11483 (if (and (not (org-entry-is-done-p))
11484 (org-entry-is-todo-p))
11485 (throw 'dont-block nil))
11486 (outline-next-heading)
11487 (setq child-level (funcall outline-level))))))
11488 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11489 ;; any previous siblings are undone, it's blocked
11490 (save-excursion
11491 (org-back-to-heading t)
11492 (let* ((pos (point))
11493 (parent-pos (and (org-up-heading-safe) (point))))
11494 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11495 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11496 (forward-line 1)
11497 (re-search-forward org-not-done-heading-regexp pos t))
11498 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11499 ;; Search further up the hierarchy, to see if an ancestor is blocked
11500 (while t
11501 (goto-char parent-pos)
11502 (if (not (looking-at org-not-done-heading-regexp))
11503 (throw 'dont-block t)) ; do not block, parent is not a TODO
11504 (setq pos (point))
11505 (setq parent-pos (and (org-up-heading-safe) (point)))
11506 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11507 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11508 (forward-line 1)
11509 (re-search-forward org-not-done-heading-regexp pos t))
11510 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11512 (defcustom org-track-ordered-property-with-tag nil
11513 "Should the ORDERED property also be shown as a tag?
11514 The ORDERED property decides if an entry should require subtasks to be
11515 completed in sequence. Since a property is not very visible, setting
11516 this option means that toggling the ORDERED property with the command
11517 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11518 not relevant for the behavior, but it makes things more visible.
11520 Note that toggling the tag with tags commands will not change the property
11521 and therefore not influence behavior!
11523 This can be t, meaning the tag ORDERED should be used, It can also be a
11524 string to select a different tag for this task."
11525 :group 'org-todo
11526 :type '(choice
11527 (const :tag "No tracking" nil)
11528 (const :tag "Track with ORDERED tag" t)
11529 (string :tag "Use other tag")))
11531 (defun org-toggle-ordered-property ()
11532 "Toggle the ORDERED property of the current entry.
11533 For better visibility, you can track the value of this property with a tag.
11534 See variable `org-track-ordered-property-with-tag'."
11535 (interactive)
11536 (let* ((t1 org-track-ordered-property-with-tag)
11537 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11538 (save-excursion
11539 (org-back-to-heading)
11540 (if (org-entry-get nil "ORDERED")
11541 (progn
11542 (org-delete-property "ORDERED")
11543 (and tag (org-toggle-tag tag 'off))
11544 (message "Subtasks can be completed in arbitrary order"))
11545 (org-entry-put nil "ORDERED" "t")
11546 (and tag (org-toggle-tag tag 'on))
11547 (message "Subtasks must be completed in sequence")))))
11549 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11550 (defun org-block-todo-from-checkboxes (change-plist)
11551 "Block turning an entry into a TODO, using checkboxes.
11552 This checks whether the current task should be blocked from state
11553 changes because there are unchecked boxes in this entry."
11554 (if (not org-enforce-todo-checkbox-dependencies)
11555 t ; if locally turned off don't block
11556 (catch 'dont-block
11557 ;; If this is not a todo state change, or if this entry is already DONE,
11558 ;; do not block
11559 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11560 (member (plist-get change-plist :from)
11561 (cons 'done org-done-keywords))
11562 (member (plist-get change-plist :to)
11563 (cons 'todo org-not-done-keywords))
11564 (not (plist-get change-plist :to)))
11565 (throw 'dont-block t))
11566 ;; If this task has checkboxes that are not checked, it's blocked
11567 (save-excursion
11568 (org-back-to-heading t)
11569 (let ((beg (point)) end)
11570 (outline-next-heading)
11571 (setq end (point))
11572 (goto-char beg)
11573 (if (org-list-search-forward
11574 (concat (org-item-beginning-re)
11575 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11576 "\\[[- ]\\]")
11577 end t)
11578 (progn
11579 (if (boundp 'org-blocked-by-checkboxes)
11580 (setq org-blocked-by-checkboxes t))
11581 (throw 'dont-block nil)))))
11582 t))) ; do not block
11584 (defun org-entry-blocked-p ()
11585 "Is the current entry blocked?"
11586 (if (org-entry-get nil "NOBLOCKING")
11587 nil ;; Never block this entry
11588 (not
11589 (run-hook-with-args-until-failure
11590 'org-blocker-hook
11591 (list :type 'todo-state-change
11592 :position (point)
11593 :from 'todo
11594 :to 'done)))))
11596 (defun org-update-statistics-cookies (all)
11597 "Update the statistics cookie, either from TODO or from checkboxes.
11598 This should be called with the cursor in a line with a statistics cookie."
11599 (interactive "P")
11600 (if all
11601 (progn
11602 (org-update-checkbox-count 'all)
11603 (org-map-entries 'org-update-parent-todo-statistics))
11604 (if (not (org-at-heading-p))
11605 (org-update-checkbox-count)
11606 (let ((pos (move-marker (make-marker) (point)))
11607 end l1 l2)
11608 (ignore-errors (org-back-to-heading t))
11609 (if (not (org-at-heading-p))
11610 (org-update-checkbox-count)
11611 (setq l1 (org-outline-level))
11612 (setq end (save-excursion
11613 (outline-next-heading)
11614 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11615 (point)))
11616 (if (and (save-excursion
11617 (re-search-forward
11618 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11619 (not (save-excursion (re-search-forward
11620 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11621 (org-update-checkbox-count)
11622 (if (and l2 (> l2 l1))
11623 (progn
11624 (goto-char end)
11625 (org-update-parent-todo-statistics))
11626 (goto-char pos)
11627 (beginning-of-line 1)
11628 (while (re-search-forward
11629 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11630 (point-at-eol) t)
11631 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11632 (goto-char pos)
11633 (move-marker pos nil)))))
11635 (defvar org-entry-property-inherited-from) ;; defined below
11636 (defun org-update-parent-todo-statistics ()
11637 "Update any statistics cookie in the parent of the current headline.
11638 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11639 the entire subtree and this will travel up the hierarchy and update
11640 statistics everywhere."
11641 (let* ((prop (save-excursion (org-up-heading-safe)
11642 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11643 (recursive (or (not org-hierarchical-todo-statistics)
11644 (and prop (string-match "\\<recursive\\>" prop))))
11645 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11647 (first t)
11648 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11649 level ltoggle l1 new ndel
11650 (cnt-all 0) (cnt-done 0) is-percent kwd
11651 checkbox-beg ov ovs ove cookie-present)
11652 (catch 'exit
11653 (save-excursion
11654 (beginning-of-line 1)
11655 (setq ltoggle (funcall outline-level))
11656 ;; Three situations are to consider:
11658 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11659 ;; to the top-level ancestor on the headline;
11661 ;; 2. If parent has "recursive" property, repeat up to the
11662 ;; headline setting that property, taking inheritance into
11663 ;; account;
11665 ;; 3. Else, move up to direct parent and proceed only once.
11666 (while (and (setq level (org-up-heading-safe))
11667 (or recursive first)
11668 (>= (point) lim))
11669 (setq first nil cookie-present nil)
11670 (unless (and level
11671 (not (string-match
11672 "\\<checkbox\\>"
11673 (downcase (or (org-entry-get nil "COOKIE_DATA")
11674 "")))))
11675 (throw 'exit nil))
11676 (while (re-search-forward box-re (point-at-eol) t)
11677 (setq cnt-all 0 cnt-done 0 cookie-present t)
11678 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11679 (save-match-data
11680 (unless (outline-next-heading) (throw 'exit nil))
11681 (while (and (looking-at org-complex-heading-regexp)
11682 (> (setq l1 (length (match-string 1))) level))
11683 (setq kwd (and (or recursive (= l1 ltoggle))
11684 (match-string 2)))
11685 (if (or (eq org-provide-todo-statistics 'all-headlines)
11686 (and (listp org-provide-todo-statistics)
11687 (or (member kwd org-provide-todo-statistics)
11688 (member kwd org-done-keywords))))
11689 (setq cnt-all (1+ cnt-all))
11690 (if (eq org-provide-todo-statistics t)
11691 (and kwd (setq cnt-all (1+ cnt-all)))))
11692 (and (member kwd org-done-keywords)
11693 (setq cnt-done (1+ cnt-done)))
11694 (outline-next-heading)))
11695 (setq new
11696 (if is-percent
11697 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11698 (format "[%d/%d]" cnt-done cnt-all))
11699 ndel (- (match-end 0) checkbox-beg))
11700 ;; handle overlays when updating cookie from column view
11701 (when (setq ov (car (overlays-at checkbox-beg)))
11702 (setq ovs (overlay-start ov) ove (overlay-end ov))
11703 (delete-overlay ov))
11704 (goto-char checkbox-beg)
11705 (insert new)
11706 (delete-region (point) (+ (point) ndel))
11707 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11708 (when ov (move-overlay ov ovs ove)))
11709 (when cookie-present
11710 (run-hook-with-args 'org-after-todo-statistics-hook
11711 cnt-done (- cnt-all cnt-done))))))
11712 (run-hooks 'org-todo-statistics-hook)))
11714 (defvar org-after-todo-statistics-hook nil
11715 "Hook that is called after a TODO statistics cookie has been updated.
11716 Each function is called with two arguments: the number of not-done entries
11717 and the number of done entries.
11719 For example, the following function, when added to this hook, will switch
11720 an entry to DONE when all children are done, and back to TODO when new
11721 entries are set to a TODO status. Note that this hook is only called
11722 when there is a statistics cookie in the headline!
11724 (defun org-summary-todo (n-done n-not-done)
11725 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11726 (let (org-log-done org-log-states) ; turn off logging
11727 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11730 (defvar org-todo-statistics-hook nil
11731 "Hook that is run whenever Org thinks TODO statistics should be updated.
11732 This hook runs even if there is no statistics cookie present, in which case
11733 `org-after-todo-statistics-hook' would not run.")
11735 (defun org-todo-trigger-tag-changes (state)
11736 "Apply the changes defined in `org-todo-state-tags-triggers'."
11737 (let ((l org-todo-state-tags-triggers)
11738 changes)
11739 (when (or (not state) (equal state ""))
11740 (setq changes (append changes (cdr (assoc "" l)))))
11741 (when (and (stringp state) (> (length state) 0))
11742 (setq changes (append changes (cdr (assoc state l)))))
11743 (when (member state org-not-done-keywords)
11744 (setq changes (append changes (cdr (assoc 'todo l)))))
11745 (when (member state org-done-keywords)
11746 (setq changes (append changes (cdr (assoc 'done l)))))
11747 (dolist (c changes)
11748 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11750 (defun org-local-logging (value)
11751 "Get logging settings from a property VALUE."
11752 (let* (words w a)
11753 ;; directly set the variables, they are already local.
11754 (setq org-log-done nil
11755 org-log-repeat nil
11756 org-todo-log-states nil)
11757 (setq words (org-split-string value))
11758 (while (setq w (pop words))
11759 (cond
11760 ((setq a (assoc w org-startup-options))
11761 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11762 (set (nth 1 a) (nth 2 a))))
11763 ((setq a (org-extract-log-state-settings w))
11764 (and (member (car a) org-todo-keywords-1)
11765 (push a org-todo-log-states)))))))
11767 (defun org-get-todo-sequence-head (kwd)
11768 "Return the head of the TODO sequence to which KWD belongs.
11769 If KWD is not set, check if there is a text property remembering the
11770 right sequence."
11771 (let (p)
11772 (cond
11773 ((not kwd)
11774 (or (get-text-property (point-at-bol) 'org-todo-head)
11775 (progn
11776 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11777 nil (point-at-eol)))
11778 (get-text-property p 'org-todo-head))))
11779 ((not (member kwd org-todo-keywords-1))
11780 (car org-todo-keywords-1))
11781 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11783 (defun org-fast-todo-selection ()
11784 "Fast TODO keyword selection with single keys.
11785 Returns the new TODO keyword, or nil if no state change should occur."
11786 (let* ((fulltable org-todo-key-alist)
11787 (done-keywords org-done-keywords) ;; needed for the faces.
11788 (maxlen (apply 'max (mapcar
11789 (lambda (x)
11790 (if (stringp (car x)) (string-width (car x)) 0))
11791 fulltable)))
11792 (expert nil)
11793 (fwidth (+ maxlen 3 1 3))
11794 (ncol (/ (- (window-width) 4) fwidth))
11795 tg cnt e c tbl
11796 groups ingroup)
11797 (save-excursion
11798 (save-window-excursion
11799 (if expert
11800 (set-buffer (get-buffer-create " *Org todo*"))
11801 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11802 (erase-buffer)
11803 (org-set-local 'org-done-keywords done-keywords)
11804 (setq tbl fulltable cnt 0)
11805 (while (setq e (pop tbl))
11806 (cond
11807 ((equal e '(:startgroup))
11808 (push '() groups) (setq ingroup t)
11809 (when (not (= cnt 0))
11810 (setq cnt 0)
11811 (insert "\n"))
11812 (insert "{ "))
11813 ((equal e '(:endgroup))
11814 (setq ingroup nil cnt 0)
11815 (insert "}\n"))
11816 ((equal e '(:newline))
11817 (when (not (= cnt 0))
11818 (setq cnt 0)
11819 (insert "\n")
11820 (setq e (car tbl))
11821 (while (equal (car tbl) '(:newline))
11822 (insert "\n")
11823 (setq tbl (cdr tbl)))))
11825 (setq tg (car e) c (cdr e))
11826 (if ingroup (push tg (car groups)))
11827 (setq tg (org-add-props tg nil 'face
11828 (org-get-todo-face tg)))
11829 (if (and (= cnt 0) (not ingroup)) (insert " "))
11830 (insert "[" c "] " tg (make-string
11831 (- fwidth 4 (length tg)) ?\ ))
11832 (when (= (setq cnt (1+ cnt)) ncol)
11833 (insert "\n")
11834 (if ingroup (insert " "))
11835 (setq cnt 0)))))
11836 (insert "\n")
11837 (goto-char (point-min))
11838 (if (not expert) (org-fit-window-to-buffer))
11839 (message "[a-z..]:Set [SPC]:clear")
11840 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11841 (cond
11842 ((or (= c ?\C-g)
11843 (and (= c ?q) (not (rassoc c fulltable))))
11844 (setq quit-flag t))
11845 ((= c ?\ ) nil)
11846 ((setq e (rassoc c fulltable) tg (car e))
11848 (t (setq quit-flag t)))))))
11850 (defun org-entry-is-todo-p ()
11851 (member (org-get-todo-state) org-not-done-keywords))
11853 (defun org-entry-is-done-p ()
11854 (member (org-get-todo-state) org-done-keywords))
11856 (defun org-get-todo-state ()
11857 (save-excursion
11858 (org-back-to-heading t)
11859 (and (looking-at org-todo-line-regexp)
11860 (match-end 2)
11861 (match-string 2))))
11863 (defun org-at-date-range-p (&optional inactive-ok)
11864 "Is the cursor inside a date range?"
11865 (interactive)
11866 (save-excursion
11867 (catch 'exit
11868 (let ((pos (point)))
11869 (skip-chars-backward "^[<\r\n")
11870 (skip-chars-backward "<[")
11871 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11872 (>= (match-end 0) pos)
11873 (throw 'exit t))
11874 (skip-chars-backward "^<[\r\n")
11875 (skip-chars-backward "<[")
11876 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11877 (>= (match-end 0) pos)
11878 (throw 'exit t)))
11879 nil)))
11881 (defun org-get-repeat (&optional tagline)
11882 "Check if there is a deadline/schedule with repeater in this entry."
11883 (save-match-data
11884 (save-excursion
11885 (org-back-to-heading t)
11886 (and (re-search-forward (if tagline
11887 (concat tagline "\\s-*" org-repeat-re)
11888 org-repeat-re)
11889 (org-entry-end-position) t)
11890 (match-string-no-properties 1)))))
11892 (defvar org-last-changed-timestamp)
11893 (defvar org-last-inserted-timestamp)
11894 (defvar org-log-post-message)
11895 (defvar org-log-note-purpose)
11896 (defvar org-log-note-how)
11897 (defvar org-log-note-extra)
11898 (defun org-auto-repeat-maybe (done-word)
11899 "Check if the current headline contains a repeated deadline/schedule.
11900 If yes, set TODO state back to what it was and change the base date
11901 of repeating deadline/scheduled time stamps to new date.
11902 This function is run automatically after each state change to a DONE state."
11903 ;; last-state is dynamically scoped into this function
11904 (let* ((repeat (org-get-repeat))
11905 (aa (assoc org-last-state org-todo-kwd-alist))
11906 (interpret (nth 1 aa))
11907 (head (nth 2 aa))
11908 (whata '(("d" . day) ("m" . month) ("y" . year)))
11909 (msg "Entry repeats: ")
11910 (org-log-done nil)
11911 (org-todo-log-states nil)
11912 re type n what ts time to-state)
11913 (when repeat
11914 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11915 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11916 org-todo-repeat-to-state))
11917 (unless (and to-state (member to-state org-todo-keywords-1))
11918 (setq to-state (if (eq interpret 'type) org-last-state head)))
11919 (org-todo to-state)
11920 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11921 (org-entry-put nil "LAST_REPEAT" (format-time-string
11922 (org-time-stamp-format t t))))
11923 (when org-log-repeat
11924 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11925 (memq 'org-add-log-note post-command-hook))
11926 ;; OK, we are already setup for some record
11927 (if (eq org-log-repeat 'note)
11928 ;; make sure we take a note, not only a time stamp
11929 (setq org-log-note-how 'note))
11930 ;; Set up for taking a record
11931 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11932 org-last-state
11933 'findpos org-log-repeat)))
11934 (org-back-to-heading t)
11935 (org-add-planning-info nil nil 'closed)
11936 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11937 org-deadline-time-regexp "\\)\\|\\("
11938 org-ts-regexp "\\)"))
11939 (while (re-search-forward
11940 re (save-excursion (outline-next-heading) (point)) t)
11941 (setq type (if (match-end 1) org-scheduled-string
11942 (if (match-end 3) org-deadline-string "Plain:"))
11943 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11944 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11945 (setq n (string-to-number (match-string 2 ts))
11946 what (match-string 3 ts))
11947 (if (equal what "w") (setq n (* n 7) what "d"))
11948 ;; Preparation, see if we need to modify the start date for the change
11949 (when (match-end 1)
11950 (setq time (save-match-data (org-time-string-to-time ts)))
11951 (cond
11952 ((equal (match-string 1 ts) ".")
11953 ;; Shift starting date to today
11954 (org-timestamp-change
11955 (- (org-today) (time-to-days time))
11956 'day))
11957 ((equal (match-string 1 ts) "+")
11958 (let ((nshiftmax 10) (nshift 0))
11959 (while (or (= nshift 0)
11960 (<= (time-to-days time)
11961 (time-to-days (current-time))))
11962 (when (= (incf nshift) nshiftmax)
11963 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11964 (error "Abort")))
11965 (org-timestamp-change n (cdr (assoc what whata)))
11966 (org-at-timestamp-p t)
11967 (setq ts (match-string 1))
11968 (setq time (save-match-data (org-time-string-to-time ts)))))
11969 (org-timestamp-change (- n) (cdr (assoc what whata)))
11970 ;; rematch, so that we have everything in place for the real shift
11971 (org-at-timestamp-p t)
11972 (setq ts (match-string 1))
11973 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11974 (org-timestamp-change n (cdr (assoc what whata)))
11975 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11976 (setq org-log-post-message msg)
11977 (message "%s" msg))))
11979 (defun org-show-todo-tree (arg)
11980 "Make a compact tree which shows all headlines marked with TODO.
11981 The tree will show the lines where the regexp matches, and all higher
11982 headlines above the match.
11983 With a \\[universal-argument] prefix, prompt for a regexp to match.
11984 With a numeric prefix N, construct a sparse tree for the Nth element
11985 of `org-todo-keywords-1'."
11986 (interactive "P")
11987 (let ((case-fold-search nil)
11988 (kwd-re
11989 (cond ((null arg) org-not-done-regexp)
11990 ((equal arg '(4))
11991 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11992 (mapcar 'list org-todo-keywords-1))))
11993 (concat "\\("
11994 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11995 "\\)\\>")))
11996 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11997 (regexp-quote (nth (1- (prefix-numeric-value arg))
11998 org-todo-keywords-1)))
11999 (t (error "Invalid prefix argument: %s" arg)))))
12000 (message "%d TODO entries found"
12001 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12003 (defun org-deadline (&optional remove time)
12004 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12005 With argument REMOVE, remove any deadline from the item.
12006 With argument TIME, set the deadline at the corresponding date. TIME
12007 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12008 (interactive "P")
12009 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12010 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12011 'region-start-level 'region))
12012 org-loop-over-headlines-in-active-region)
12013 (org-map-entries
12014 `(org-deadline ',remove ,time)
12015 org-loop-over-headlines-in-active-region
12016 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12017 (let* ((old-date (org-entry-get nil "DEADLINE"))
12018 (repeater (and old-date
12019 (string-match
12020 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12021 old-date)
12022 (match-string 1 old-date))))
12023 (if remove
12024 (progn
12025 (when (and old-date org-log-redeadline)
12026 (org-add-log-setup 'deldeadline nil old-date 'findpos
12027 org-log-redeadline))
12028 (org-remove-timestamp-with-keyword org-deadline-string)
12029 (message "Item no longer has a deadline."))
12030 (org-add-planning-info 'deadline time 'closed)
12031 (when (and old-date org-log-redeadline
12032 (not (equal old-date
12033 (substring org-last-inserted-timestamp 1 -1))))
12034 (org-add-log-setup 'redeadline nil old-date 'findpos
12035 org-log-redeadline))
12036 (when repeater
12037 (save-excursion
12038 (org-back-to-heading t)
12039 (when (re-search-forward (concat org-deadline-string " "
12040 org-last-inserted-timestamp)
12041 (save-excursion
12042 (outline-next-heading) (point)) t)
12043 (goto-char (1- (match-end 0)))
12044 (insert " " repeater)
12045 (setq org-last-inserted-timestamp
12046 (concat (substring org-last-inserted-timestamp 0 -1)
12047 " " repeater
12048 (substring org-last-inserted-timestamp -1))))))
12049 (message "Deadline on %s" org-last-inserted-timestamp)))))
12051 (defun org-schedule (&optional remove time)
12052 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12053 With argument REMOVE, remove any scheduling date from the item.
12054 With argument TIME, scheduled at the corresponding date. TIME can
12055 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12056 (interactive "P")
12057 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12058 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12059 'region-start-level 'region))
12060 org-loop-over-headlines-in-active-region)
12061 (org-map-entries
12062 `(org-schedule ',remove ,time)
12063 org-loop-over-headlines-in-active-region
12064 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12065 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12066 (repeater (and old-date
12067 (string-match
12068 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12069 old-date)
12070 (match-string 1 old-date))))
12071 (if remove
12072 (progn
12073 (when (and old-date org-log-reschedule)
12074 (org-add-log-setup 'delschedule nil old-date 'findpos
12075 org-log-reschedule))
12076 (org-remove-timestamp-with-keyword org-scheduled-string)
12077 (message "Item is no longer scheduled."))
12078 (org-add-planning-info 'scheduled time 'closed)
12079 (when (and old-date org-log-reschedule
12080 (not (equal old-date
12081 (substring org-last-inserted-timestamp 1 -1))))
12082 (org-add-log-setup 'reschedule nil old-date 'findpos
12083 org-log-reschedule))
12084 (when repeater
12085 (save-excursion
12086 (org-back-to-heading t)
12087 (when (re-search-forward (concat org-scheduled-string " "
12088 org-last-inserted-timestamp)
12089 (save-excursion
12090 (outline-next-heading) (point)) t)
12091 (goto-char (1- (match-end 0)))
12092 (insert " " repeater)
12093 (setq org-last-inserted-timestamp
12094 (concat (substring org-last-inserted-timestamp 0 -1)
12095 " " repeater
12096 (substring org-last-inserted-timestamp -1))))))
12097 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12099 (defun org-get-scheduled-time (pom &optional inherit)
12100 "Get the scheduled time as a time tuple, of a format suitable
12101 for calling org-schedule with, or if there is no scheduling,
12102 returns nil."
12103 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12104 (when time
12105 (apply 'encode-time (org-parse-time-string time)))))
12107 (defun org-get-deadline-time (pom &optional inherit)
12108 "Get the deadline as a time tuple, of a format suitable for
12109 calling org-deadline with, or if there is no scheduling, returns
12110 nil."
12111 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12112 (when time
12113 (apply 'encode-time (org-parse-time-string time)))))
12115 (defun org-remove-timestamp-with-keyword (keyword)
12116 "Remove all time stamps with KEYWORD in the current entry."
12117 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12118 beg)
12119 (save-excursion
12120 (org-back-to-heading t)
12121 (setq beg (point))
12122 (outline-next-heading)
12123 (while (re-search-backward re beg t)
12124 (replace-match "")
12125 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12126 (equal (char-before) ?\ ))
12127 (backward-delete-char 1)
12128 (if (string-match "^[ \t]*$" (buffer-substring
12129 (point-at-bol) (point-at-eol)))
12130 (delete-region (point-at-bol)
12131 (min (point-max) (1+ (point-at-eol))))))))))
12133 (defun org-add-planning-info (what &optional time &rest remove)
12134 "Insert new timestamp with keyword in the line directly after the headline.
12135 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12136 If non is given, the user is prompted for a date.
12137 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12138 be removed."
12139 (interactive)
12140 (let (org-time-was-given org-end-time-was-given ts
12141 end default-time default-input)
12143 (catch 'exit
12144 (when (and (memq what '(scheduled deadline))
12145 (or (not time)
12146 (and (stringp time)
12147 (string-match "^[-+]+[0-9]" time))))
12148 ;; Try to get a default date/time from existing timestamp
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (setq end (save-excursion (outline-next-heading) (point)))
12152 (when (re-search-forward (if (eq what 'scheduled)
12153 org-scheduled-time-regexp
12154 org-deadline-time-regexp)
12155 end t)
12156 (setq ts (match-string 1)
12157 default-time
12158 (apply 'encode-time (org-parse-time-string ts))
12159 default-input (and ts (org-get-compact-tod ts))))))
12160 (when what
12161 (setq time
12162 (if (stringp time)
12163 ;; This is a string (relative or absolute), set proper date
12164 (apply 'encode-time
12165 (org-read-date-analyze
12166 time default-time (decode-time default-time)))
12167 ;; If necessary, get the time from the user
12168 (or time (org-read-date nil 'to-time nil nil
12169 default-time default-input)))))
12171 (when (and org-insert-labeled-timestamps-at-point
12172 (member what '(scheduled deadline)))
12173 (insert
12174 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12175 (org-insert-time-stamp time org-time-was-given
12176 nil nil nil (list org-end-time-was-given))
12177 (setq what nil))
12178 (save-excursion
12179 (save-restriction
12180 (let (col list elt ts buffer-invisibility-spec)
12181 (org-back-to-heading t)
12182 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12183 (goto-char (match-end 1))
12184 (setq col (current-column))
12185 (goto-char (match-end 0))
12186 (if (eobp) (insert "\n") (forward-char 1))
12187 (when (and (not what)
12188 (not (looking-at
12189 (concat "[ \t]*"
12190 org-keyword-time-not-clock-regexp))))
12191 ;; Nothing to add, nothing to remove...... :-)
12192 (throw 'exit nil))
12193 (if (and (not (looking-at org-outline-regexp))
12194 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12195 "[^\r\n]*"))
12196 (not (equal (match-string 1) org-clock-string)))
12197 (narrow-to-region (match-beginning 0) (match-end 0))
12198 (insert-before-markers "\n")
12199 (backward-char 1)
12200 (narrow-to-region (point) (point))
12201 (and org-adapt-indentation (org-indent-to-column col)))
12202 ;; Check if we have to remove something.
12203 (setq list (cons what remove))
12204 (while list
12205 (setq elt (pop list))
12206 (when (or (and (eq elt 'scheduled)
12207 (re-search-forward org-scheduled-time-regexp nil t))
12208 (and (eq elt 'deadline)
12209 (re-search-forward org-deadline-time-regexp nil t))
12210 (and (eq elt 'closed)
12211 (re-search-forward org-closed-time-regexp nil t)))
12212 (replace-match "")
12213 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12214 (and (looking-at "[ \t]+") (replace-match ""))
12215 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12216 (when what
12217 (insert
12218 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12219 (cond ((eq what 'scheduled) org-scheduled-string)
12220 ((eq what 'deadline) org-deadline-string)
12221 ((eq what 'closed) org-closed-string))
12222 " ")
12223 (setq ts (org-insert-time-stamp
12224 time
12225 (or org-time-was-given
12226 (and (eq what 'closed) org-log-done-with-time))
12227 (eq what 'closed)
12228 nil nil (list org-end-time-was-given)))
12229 (insert
12230 (if (not (or (bolp) (eq (char-before) ?\ )
12231 (memq (char-after) '(32 10))
12232 (eobp))) " " ""))
12233 (end-of-line 1))
12234 (goto-char (point-min))
12235 (widen)
12236 (if (and (looking-at "[ \t]*\n")
12237 (equal (char-before) ?\n))
12238 (delete-region (1- (point)) (point-at-eol)))
12239 ts))))))
12241 (defvar org-log-note-marker (make-marker))
12242 (defvar org-log-note-purpose nil)
12243 (defvar org-log-note-state nil)
12244 (defvar org-log-note-previous-state nil)
12245 (defvar org-log-note-how nil)
12246 (defvar org-log-note-extra nil)
12247 (defvar org-log-note-window-configuration nil)
12248 (defvar org-log-note-return-to (make-marker))
12249 (defvar org-log-note-effective-time nil
12250 "Remembered current time so that dynamically scoped
12251 `org-extend-today-until' affects tha timestamps in state change
12252 log")
12254 (defvar org-log-post-message nil
12255 "Message to be displayed after a log note has been stored.
12256 The auto-repeater uses this.")
12258 (defun org-add-note ()
12259 "Add a note to the current entry.
12260 This is done in the same way as adding a state change note."
12261 (interactive)
12262 (org-add-log-setup 'note nil nil 'findpos nil))
12264 (defvar org-property-end-re)
12265 (defun org-add-log-setup (&optional purpose state prev-state
12266 findpos how extra)
12267 "Set up the post command hook to take a note.
12268 If this is about to TODO state change, the new state is expected in STATE.
12269 When FINDPOS is non-nil, find the correct position for the note in
12270 the current entry. If not, assume that it can be inserted at point.
12271 HOW is an indicator what kind of note should be created.
12272 EXTRA is additional text that will be inserted into the notes buffer."
12273 (let* ((org-log-into-drawer (org-log-into-drawer))
12274 (drawer (cond ((stringp org-log-into-drawer)
12275 org-log-into-drawer)
12276 (org-log-into-drawer "LOGBOOK")
12277 (t nil))))
12278 (save-restriction
12279 (save-excursion
12280 (when findpos
12281 (org-back-to-heading t)
12282 (narrow-to-region (point) (save-excursion
12283 (outline-next-heading) (point)))
12284 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12285 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12286 "[^\r\n]*\\)?"))
12287 (goto-char (match-end 0))
12288 (cond
12289 (drawer
12290 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12291 nil t)
12292 (progn
12293 (goto-char (match-end 0))
12294 (or org-log-states-order-reversed
12295 (and (re-search-forward org-property-end-re nil t)
12296 (goto-char (1- (match-beginning 0))))))
12297 (insert "\n:" drawer ":\n:END:")
12298 (beginning-of-line 0)
12299 (org-indent-line-function)
12300 (beginning-of-line 2)
12301 (org-indent-line-function)
12302 (end-of-line 0)))
12303 ((and org-log-state-notes-insert-after-drawers
12304 (save-excursion
12305 (forward-line) (looking-at org-drawer-regexp)))
12306 (forward-line)
12307 (while (looking-at org-drawer-regexp)
12308 (goto-char (match-end 0))
12309 (re-search-forward org-property-end-re (point-max) t)
12310 (forward-line))
12311 (forward-line -1)))
12312 (unless org-log-states-order-reversed
12313 (and (= (char-after) ?\n) (forward-char 1))
12314 (org-skip-over-state-notes)
12315 (skip-chars-backward " \t\n\r")))
12316 (move-marker org-log-note-marker (point))
12317 (setq org-log-note-purpose purpose
12318 org-log-note-state state
12319 org-log-note-previous-state prev-state
12320 org-log-note-how how
12321 org-log-note-extra extra
12322 org-log-note-effective-time (org-current-effective-time))
12323 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12325 (defun org-skip-over-state-notes ()
12326 "Skip past the list of State notes in an entry."
12327 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12328 (when (ignore-errors (goto-char (org-in-item-p)))
12329 (let* ((struct (org-list-struct))
12330 (prevs (org-list-prevs-alist struct)))
12331 (while (looking-at "[ \t]*- State")
12332 (goto-char (or (org-list-get-next-item (point) struct prevs)
12333 (org-list-get-item-end (point) struct)))))))
12335 (defun org-add-log-note (&optional purpose)
12336 "Pop up a window for taking a note, and add this note later at point."
12337 (remove-hook 'post-command-hook 'org-add-log-note)
12338 (setq org-log-note-window-configuration (current-window-configuration))
12339 (delete-other-windows)
12340 (move-marker org-log-note-return-to (point))
12341 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12342 (goto-char org-log-note-marker)
12343 (org-switch-to-buffer-other-window "*Org Note*")
12344 (erase-buffer)
12345 (if (memq org-log-note-how '(time state))
12346 (let (current-prefix-arg) (org-store-log-note))
12347 (let ((org-inhibit-startup t)) (org-mode))
12348 (insert (format "# Insert note for %s.
12349 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12350 (cond
12351 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12352 ((eq org-log-note-purpose 'done) "closed todo item")
12353 ((eq org-log-note-purpose 'state)
12354 (format "state change from \"%s\" to \"%s\""
12355 (or org-log-note-previous-state "")
12356 (or org-log-note-state "")))
12357 ((eq org-log-note-purpose 'reschedule)
12358 "rescheduling")
12359 ((eq org-log-note-purpose 'delschedule)
12360 "no longer scheduled")
12361 ((eq org-log-note-purpose 'redeadline)
12362 "changing deadline")
12363 ((eq org-log-note-purpose 'deldeadline)
12364 "removing deadline")
12365 ((eq org-log-note-purpose 'refile)
12366 "refiling")
12367 ((eq org-log-note-purpose 'note)
12368 "this entry")
12369 (t (error "This should not happen")))))
12370 (if org-log-note-extra (insert org-log-note-extra))
12371 (org-set-local 'org-finish-function 'org-store-log-note)
12372 (run-hooks 'org-log-buffer-setup-hook)))
12374 (defvar org-note-abort nil) ; dynamically scoped
12375 (defun org-store-log-note ()
12376 "Finish taking a log note, and insert it to where it belongs."
12377 (let ((txt (buffer-string))
12378 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12379 lines ind bul)
12380 (kill-buffer (current-buffer))
12381 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12382 (setq txt (replace-match "" t t txt)))
12383 (if (string-match "\\s-+\\'" txt)
12384 (setq txt (replace-match "" t t txt)))
12385 (setq lines (org-split-string txt "\n"))
12386 (when (and note (string-match "\\S-" note))
12387 (setq note
12388 (org-replace-escapes
12389 note
12390 (list (cons "%u" (user-login-name))
12391 (cons "%U" user-full-name)
12392 (cons "%t" (format-time-string
12393 (org-time-stamp-format 'long 'inactive)
12394 org-log-note-effective-time))
12395 (cons "%T" (format-time-string
12396 (org-time-stamp-format 'long nil)
12397 org-log-note-effective-time))
12398 (cons "%d" (format-time-string
12399 (org-time-stamp-format nil 'inactive)
12400 org-log-note-effective-time))
12401 (cons "%D" (format-time-string
12402 (org-time-stamp-format nil nil)
12403 org-log-note-effective-time))
12404 (cons "%s" (if org-log-note-state
12405 (concat "\"" org-log-note-state "\"")
12406 ""))
12407 (cons "%S" (if org-log-note-previous-state
12408 (concat "\"" org-log-note-previous-state "\"")
12409 "\"\"")))))
12410 (if lines (setq note (concat note " \\\\")))
12411 (push note lines))
12412 (when (or current-prefix-arg org-note-abort)
12413 (when org-log-into-drawer
12414 (org-remove-empty-drawer-at
12415 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12416 org-log-note-marker))
12417 (setq lines nil))
12418 (when lines
12419 (with-current-buffer (marker-buffer org-log-note-marker)
12420 (save-excursion
12421 (goto-char org-log-note-marker)
12422 (move-marker org-log-note-marker nil)
12423 (end-of-line 1)
12424 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12425 (setq ind (save-excursion
12426 (if (ignore-errors (goto-char (org-in-item-p)))
12427 (let ((struct (org-list-struct)))
12428 (org-list-get-ind
12429 (org-list-get-top-point struct) struct))
12430 (skip-chars-backward " \r\t\n")
12431 (cond
12432 ((and (org-at-heading-p)
12433 org-adapt-indentation)
12434 (1+ (org-current-level)))
12435 ((org-at-heading-p) 0)
12436 (t (org-get-indentation))))))
12437 (setq bul (org-list-bullet-string "-"))
12438 (org-indent-line-to ind)
12439 (insert bul (pop lines))
12440 (let ((ind-body (+ (length bul) ind)))
12441 (while lines
12442 (insert "\n")
12443 (org-indent-line-to ind-body)
12444 (insert (pop lines))))
12445 (message "Note stored")
12446 (org-back-to-heading t)
12447 (org-cycle-hide-drawers 'children)))))
12448 (set-window-configuration org-log-note-window-configuration)
12449 (with-current-buffer (marker-buffer org-log-note-return-to)
12450 (goto-char org-log-note-return-to))
12451 (move-marker org-log-note-return-to nil)
12452 (and org-log-post-message (message "%s" org-log-post-message)))
12454 (defun org-remove-empty-drawer-at (drawer pos)
12455 "Remove an empty drawer DRAWER at position POS.
12456 POS may also be a marker."
12457 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12458 (save-excursion
12459 (save-restriction
12460 (widen)
12461 (goto-char pos)
12462 (if (org-in-regexp
12463 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12464 (replace-match ""))))))
12466 (defun org-sparse-tree (&optional arg)
12467 "Create a sparse tree, prompt for the details.
12468 This command can create sparse trees. You first need to select the type
12469 of match used to create the tree:
12471 t Show all TODO entries.
12472 T Show entries with a specific TODO keyword.
12473 m Show entries selected by a tags/property match.
12474 p Enter a property name and its value (both with completion on existing
12475 names/values) and show entries with that property.
12476 r Show entries matching a regular expression (`/' can be used as well)
12477 d Show deadlines due within `org-deadline-warning-days'.
12478 b Show deadlines and scheduled items before a date.
12479 a Show deadlines and scheduled items after a date."
12480 (interactive "P")
12481 (let (ans kwd value)
12482 (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")
12483 (setq ans (read-char-exclusive))
12484 (cond
12485 ((equal ans ?d)
12486 (call-interactively 'org-check-deadlines))
12487 ((equal ans ?b)
12488 (call-interactively 'org-check-before-date))
12489 ((equal ans ?a)
12490 (call-interactively 'org-check-after-date))
12491 ((equal ans ?D)
12492 (call-interactively 'org-check-dates-range))
12493 ((equal ans ?t)
12494 (org-show-todo-tree nil))
12495 ((equal ans ?T)
12496 (org-show-todo-tree '(4)))
12497 ((member ans '(?T ?m))
12498 (call-interactively 'org-match-sparse-tree))
12499 ((member ans '(?p ?P))
12500 (setq kwd (org-icompleting-read "Property: "
12501 (mapcar 'list (org-buffer-property-keys))))
12502 (setq value (org-icompleting-read "Value: "
12503 (mapcar 'list (org-property-values kwd))))
12504 (unless (string-match "\\`{.*}\\'" value)
12505 (setq value (concat "\"" value "\"")))
12506 (org-match-sparse-tree arg (concat kwd "=" value)))
12507 ((member ans '(?r ?R ?/))
12508 (call-interactively 'org-occur))
12509 (t (error "No such sparse tree command \"%c\"" ans)))))
12511 (defvar org-occur-highlights nil
12512 "List of overlays used for occur matches.")
12513 (make-variable-buffer-local 'org-occur-highlights)
12514 (defvar org-occur-parameters nil
12515 "Parameters of the active org-occur calls.
12516 This is a list, each call to org-occur pushes as cons cell,
12517 containing the regular expression and the callback, onto the list.
12518 The list can contain several entries if `org-occur' has been called
12519 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12520 will only contain one set of parameters. When the highlights are
12521 removed (for example with `C-c C-c', or with the next edit (depending
12522 on `org-remove-highlights-with-change'), this variable is emptied
12523 as well.")
12524 (make-variable-buffer-local 'org-occur-parameters)
12526 (defun org-occur (regexp &optional keep-previous callback)
12527 "Make a compact tree which shows all matches of REGEXP.
12528 The tree will show the lines where the regexp matches, and all higher
12529 headlines above the match. It will also show the heading after the match,
12530 to make sure editing the matching entry is easy.
12531 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12532 call to `org-occur' will be kept, to allow stacking of calls to this
12533 command.
12534 If CALLBACK is non-nil, it is a function which is called to confirm
12535 that the match should indeed be shown."
12536 (interactive "sRegexp: \nP")
12537 (when (equal regexp "")
12538 (error "Regexp cannot be empty"))
12539 (unless keep-previous
12540 (org-remove-occur-highlights nil nil t))
12541 (push (cons regexp callback) org-occur-parameters)
12542 (let ((cnt 0))
12543 (save-excursion
12544 (goto-char (point-min))
12545 (if (or (not keep-previous) ; do not want to keep
12546 (not org-occur-highlights)) ; no previous matches
12547 ;; hide everything
12548 (org-overview))
12549 (while (re-search-forward regexp nil t)
12550 (when (or (not callback)
12551 (save-match-data (funcall callback)))
12552 (setq cnt (1+ cnt))
12553 (when org-highlight-sparse-tree-matches
12554 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12555 (org-show-context 'occur-tree))))
12556 (when org-remove-highlights-with-change
12557 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12558 nil 'local))
12559 (unless org-sparse-tree-open-archived-trees
12560 (org-hide-archived-subtrees (point-min) (point-max)))
12561 (run-hooks 'org-occur-hook)
12562 (if (org-called-interactively-p 'interactive)
12563 (message "%d match(es) for regexp %s" cnt regexp))
12564 cnt))
12566 (defun org-occur-next-match (&optional n reset)
12567 "Function for `next-error-function' to find sparse tree matches.
12568 N is the number of matches to move, when negative move backwards.
12569 RESET is entirely ignored - this function always goes back to the
12570 starting point when no match is found."
12571 (let* ((limit (if (< n 0) (point-min) (point-max)))
12572 (search-func (if (< n 0)
12573 'previous-single-char-property-change
12574 'next-single-char-property-change))
12575 (n (abs n))
12576 (pos (point))
12578 (catch 'exit
12579 (while (setq p1 (funcall search-func (point) 'org-type))
12580 (when (equal p1 limit)
12581 (goto-char pos)
12582 (error "No more matches"))
12583 (when (equal (get-char-property p1 'org-type) 'org-occur)
12584 (setq n (1- n))
12585 (when (= n 0)
12586 (goto-char p1)
12587 (throw 'exit (point))))
12588 (goto-char p1))
12589 (goto-char p1)
12590 (error "No more matches"))))
12592 (defun org-show-context (&optional key)
12593 "Make sure point and context are visible.
12594 How much context is shown depends upon the variables
12595 `org-show-hierarchy-above', `org-show-following-heading',
12596 `org-show-entry-below' and `org-show-siblings'."
12597 (let ((heading-p (org-at-heading-p t))
12598 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12599 (following-p (org-get-alist-option org-show-following-heading key))
12600 (entry-p (org-get-alist-option org-show-entry-below key))
12601 (siblings-p (org-get-alist-option org-show-siblings key)))
12602 (catch 'exit
12603 ;; Show heading or entry text
12604 (if (and heading-p (not entry-p))
12605 (org-flag-heading nil) ; only show the heading
12606 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12607 (org-show-hidden-entry))) ; show entire entry
12608 (when following-p
12609 ;; Show next sibling, or heading below text
12610 (save-excursion
12611 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12612 (org-flag-heading nil))))
12613 (when siblings-p (org-show-siblings))
12614 (when hierarchy-p
12615 ;; show all higher headings, possibly with siblings
12616 (save-excursion
12617 (while (and (condition-case nil
12618 (progn (org-up-heading-all 1) t)
12619 (error nil))
12620 (not (bobp)))
12621 (org-flag-heading nil)
12622 (when siblings-p (org-show-siblings))))))))
12624 (defvar org-reveal-start-hook nil
12625 "Hook run before revealing a location.")
12627 (defun org-reveal (&optional siblings)
12628 "Show current entry, hierarchy above it, and the following headline.
12629 This can be used to show a consistent set of context around locations
12630 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12631 not t for the search context.
12633 With optional argument SIBLINGS, on each level of the hierarchy all
12634 siblings are shown. This repairs the tree structure to what it would
12635 look like when opened with hierarchical calls to `org-cycle'.
12636 With double optional argument \\[universal-argument] \\[universal-argument], \
12637 go to the parent and show the
12638 entire tree."
12639 (interactive "P")
12640 (run-hooks 'org-reveal-start-hook)
12641 (let ((org-show-hierarchy-above t)
12642 (org-show-following-heading t)
12643 (org-show-siblings (if siblings t org-show-siblings)))
12644 (org-show-context nil))
12645 (when (equal siblings '(16))
12646 (save-excursion
12647 (when (org-up-heading-safe)
12648 (org-show-subtree)
12649 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12651 (defun org-highlight-new-match (beg end)
12652 "Highlight from BEG to END and mark the highlight is an occur headline."
12653 (let ((ov (make-overlay beg end)))
12654 (overlay-put ov 'face 'secondary-selection)
12655 (overlay-put ov 'org-type 'org-occur)
12656 (push ov org-occur-highlights)))
12658 (defun org-remove-occur-highlights (&optional beg end noremove)
12659 "Remove the occur highlights from the buffer.
12660 BEG and END are ignored. If NOREMOVE is nil, remove this function
12661 from the `before-change-functions' in the current buffer."
12662 (interactive)
12663 (unless org-inhibit-highlight-removal
12664 (mapc 'delete-overlay org-occur-highlights)
12665 (setq org-occur-highlights nil)
12666 (setq org-occur-parameters nil)
12667 (unless noremove
12668 (remove-hook 'before-change-functions
12669 'org-remove-occur-highlights 'local))))
12671 ;;;; Priorities
12673 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12674 "Regular expression matching the priority indicator.")
12676 (defvar org-remove-priority-next-time nil)
12678 (defun org-priority-up ()
12679 "Increase the priority of the current item."
12680 (interactive)
12681 (org-priority 'up))
12683 (defun org-priority-down ()
12684 "Decrease the priority of the current item."
12685 (interactive)
12686 (org-priority 'down))
12688 (defun org-priority (&optional action)
12689 "Change the priority of an item by ARG.
12690 ACTION can be `set', `up', `down', or a character."
12691 (interactive)
12692 (unless org-enable-priority-commands
12693 (error "Priority commands are disabled"))
12694 (setq action (or action 'set))
12695 (let (current new news have remove)
12696 (save-excursion
12697 (org-back-to-heading t)
12698 (if (looking-at org-priority-regexp)
12699 (setq current (string-to-char (match-string 2))
12700 have t))
12701 (cond
12702 ((eq action 'remove)
12703 (setq remove t new ?\ ))
12704 ((or (eq action 'set)
12705 (if (featurep 'xemacs) (characterp action) (integerp action)))
12706 (if (not (eq action 'set))
12707 (setq new action)
12708 (message "Priority %c-%c, SPC to remove: "
12709 org-highest-priority org-lowest-priority)
12710 (save-match-data
12711 (setq new (read-char-exclusive))))
12712 (if (and (= (upcase org-highest-priority) org-highest-priority)
12713 (= (upcase org-lowest-priority) org-lowest-priority))
12714 (setq new (upcase new)))
12715 (cond ((equal new ?\ ) (setq remove t))
12716 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12717 (error "Priority must be between `%c' and `%c'"
12718 org-highest-priority org-lowest-priority))))
12719 ((eq action 'up)
12720 (setq new (if have
12721 (1- current) ; normal cycling
12722 ;; last priority was empty
12723 (if (eq last-command this-command)
12724 org-lowest-priority ; wrap around empty to lowest
12725 ;; default
12726 (if org-priority-start-cycle-with-default
12727 org-default-priority
12728 (1- org-default-priority))))))
12729 ((eq action 'down)
12730 (setq new (if have
12731 (1+ current) ; normal cycling
12732 ;; last priority was empty
12733 (if (eq last-command this-command)
12734 org-highest-priority ; wrap around empty to highest
12735 ;; default
12736 (if org-priority-start-cycle-with-default
12737 org-default-priority
12738 (1+ org-default-priority))))))
12739 (t (error "Invalid action")))
12740 (if (or (< (upcase new) org-highest-priority)
12741 (> (upcase new) org-lowest-priority))
12742 (if (and (memq action '(up down))
12743 (not have) (not (eq last-command this-command)))
12744 ;; `new' is from default priority
12745 (error
12746 "The default can not be set, see `org-default-priority' why")
12747 ;; normal cycling: `new' is beyond highest/lowest priority
12748 ;; and is wrapped around to the empty priority
12749 (setq remove t)))
12750 (setq news (format "%c" new))
12751 (if have
12752 (if remove
12753 (replace-match "" t t nil 1)
12754 (replace-match news t t nil 2))
12755 (if remove
12756 (error "No priority cookie found in line")
12757 (let ((case-fold-search nil))
12758 (looking-at org-todo-line-regexp))
12759 (if (match-end 2)
12760 (progn
12761 (goto-char (match-end 2))
12762 (insert " [#" news "]"))
12763 (goto-char (match-beginning 3))
12764 (insert "[#" news "] "))))
12765 (org-preserve-lc (org-set-tags nil 'align)))
12766 (if remove
12767 (message "Priority removed")
12768 (message "Priority of current item set to %s" news))))
12770 (defun org-get-priority (s)
12771 "Find priority cookie and return priority."
12772 (if (functionp org-get-priority-function)
12773 (funcall org-get-priority-function)
12774 (save-match-data
12775 (if (not (string-match org-priority-regexp s))
12776 (* 1000 (- org-lowest-priority org-default-priority))
12777 (* 1000 (- org-lowest-priority
12778 (string-to-char (match-string 2 s))))))))
12780 ;;;; Tags
12782 (defvar org-agenda-archives-mode)
12783 (defvar org-map-continue-from nil
12784 "Position from where mapping should continue.
12785 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12787 (defvar org-scanner-tags nil
12788 "The current tag list while the tags scanner is running.")
12789 (defvar org-trust-scanner-tags nil
12790 "Should `org-get-tags-at' use the tags for the scanner.
12791 This is for internal dynamical scoping only.
12792 When this is non-nil, the function `org-get-tags-at' will return the value
12793 of `org-scanner-tags' instead of building the list by itself. This
12794 can lead to large speed-ups when the tags scanner is used in a file with
12795 many entries, and when the list of tags is retrieved, for example to
12796 obtain a list of properties. Building the tags list for each entry in such
12797 a file becomes an N^2 operation - but with this variable set, it scales
12798 as N.")
12800 (defun org-scan-tags (action matcher todo-only &optional start-level)
12801 "Scan headline tags with inheritance and produce output ACTION.
12803 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12804 or `agenda' to produce an entry list for an agenda view. It can also be
12805 a Lisp form or a function that should be called at each matched headline, in
12806 this case the return value is a list of all return values from these calls.
12808 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12809 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12810 only lines with a not-done TODO keyword are included in the output.
12811 This should be the same variable that was scoped into
12812 and set by `org-make-tags-matcher' when it constructed MATCHER.
12814 START-LEVEL can be a string with asterisks, reducing the scope to
12815 headlines matching this string."
12816 (require 'org-agenda)
12817 (let* ((re (concat "^"
12818 (if start-level
12819 ;; Get the correct level to match
12820 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12821 org-outline-regexp)
12822 " *\\(\\<\\("
12823 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12824 (org-re
12825 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12826 (props (list 'face 'default
12827 'done-face 'org-agenda-done
12828 'undone-face 'default
12829 'mouse-face 'highlight
12830 'org-not-done-regexp org-not-done-regexp
12831 'org-todo-regexp org-todo-regexp
12832 'org-complex-heading-regexp org-complex-heading-regexp
12833 'help-echo
12834 (format "mouse-2 or RET jump to org file %s"
12835 (abbreviate-file-name
12836 (or (buffer-file-name (buffer-base-buffer))
12837 (buffer-name (buffer-base-buffer)))))))
12838 (case-fold-search nil)
12839 (org-map-continue-from nil)
12840 lspos tags tags-list
12841 (tags-alist (list (cons 0 org-file-tags)))
12842 (llast 0) rtn rtn1 level category i txt
12843 todo marker entry priority)
12844 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12845 (setq action (list 'lambda nil action)))
12846 (save-excursion
12847 (goto-char (point-min))
12848 (when (eq action 'sparse-tree)
12849 (org-overview)
12850 (org-remove-occur-highlights))
12851 (while (re-search-forward re nil t)
12852 (setq org-map-continue-from nil)
12853 (catch :skip
12854 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12855 tags (if (match-end 4) (org-match-string-no-properties 4)))
12856 (goto-char (setq lspos (match-beginning 0)))
12857 (setq level (org-reduced-level (funcall outline-level))
12858 category (org-get-category))
12859 (setq i llast llast level)
12860 ;; remove tag lists from same and sublevels
12861 (while (>= i level)
12862 (when (setq entry (assoc i tags-alist))
12863 (setq tags-alist (delete entry tags-alist)))
12864 (setq i (1- i)))
12865 ;; add the next tags
12866 (when tags
12867 (setq tags (org-split-string tags ":")
12868 tags-alist
12869 (cons (cons level tags) tags-alist)))
12870 ;; compile tags for current headline
12871 (setq tags-list
12872 (if org-use-tag-inheritance
12873 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12874 tags)
12875 org-scanner-tags tags-list)
12876 (when org-use-tag-inheritance
12877 (setcdr (car tags-alist)
12878 (mapcar (lambda (x)
12879 (setq x (copy-sequence x))
12880 (org-add-prop-inherited x))
12881 (cdar tags-alist))))
12882 (when (and tags org-use-tag-inheritance
12883 (or (not (eq t org-use-tag-inheritance))
12884 org-tags-exclude-from-inheritance))
12885 ;; selective inheritance, remove uninherited ones
12886 (setcdr (car tags-alist)
12887 (org-remove-uninherited-tags (cdar tags-alist))))
12888 (when (and
12890 ;; eval matcher only when the todo condition is OK
12891 (and (or (not todo-only) (member todo org-not-done-keywords))
12892 (let ((case-fold-search t)) (eval matcher)))
12894 ;; Call the skipper, but return t if it does not skip,
12895 ;; so that the `and' form continues evaluating
12896 (progn
12897 (unless (eq action 'sparse-tree) (org-agenda-skip))
12900 ;; Check if timestamps are deselecting this entry
12901 (or (not todo-only)
12902 (and (member todo org-not-done-keywords)
12903 (or (not org-agenda-tags-todo-honor-ignore-options)
12904 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12906 ;; Extra check for the archive tag
12907 ;; FIXME: Does the skipper already do this????
12909 (not (member org-archive-tag tags-list))
12910 ;; we have an archive tag, should we use this anyway?
12911 (or (not org-agenda-skip-archived-trees)
12912 (and (eq action 'agenda) org-agenda-archives-mode))))
12914 ;; select this headline
12916 (cond
12917 ((eq action 'sparse-tree)
12918 (and org-highlight-sparse-tree-matches
12919 (org-get-heading) (match-end 0)
12920 (org-highlight-new-match
12921 (match-beginning 1) (match-end 1)))
12922 (org-show-context 'tags-tree))
12923 ((eq action 'agenda)
12924 (setq txt (org-agenda-format-item
12926 (concat
12927 (if (eq org-tags-match-list-sublevels 'indented)
12928 (make-string (1- level) ?.) "")
12929 (org-get-heading))
12930 category
12931 tags-list
12933 priority (org-get-priority txt))
12934 (goto-char lspos)
12935 (setq marker (org-agenda-new-marker))
12936 (org-add-props txt props
12937 'org-marker marker 'org-hd-marker marker 'org-category category
12938 'todo-state todo
12939 'priority priority 'type "tagsmatch")
12940 (push txt rtn))
12941 ((functionp action)
12942 (setq org-map-continue-from nil)
12943 (save-excursion
12944 (setq rtn1 (funcall action))
12945 (push rtn1 rtn)))
12946 (t (error "Invalid action")))
12948 ;; if we are to skip sublevels, jump to end of subtree
12949 (unless org-tags-match-list-sublevels
12950 (org-end-of-subtree t)
12951 (backward-char 1))))
12952 ;; Get the correct position from where to continue
12953 (if org-map-continue-from
12954 (goto-char org-map-continue-from)
12955 (and (= (point) lspos) (end-of-line 1)))))
12956 (when (and (eq action 'sparse-tree)
12957 (not org-sparse-tree-open-archived-trees))
12958 (org-hide-archived-subtrees (point-min) (point-max)))
12959 (nreverse rtn)))
12961 (defun org-remove-uninherited-tags (tags)
12962 "Remove all tags that are not inherited from the list TAGS."
12963 (cond
12964 ((eq org-use-tag-inheritance t)
12965 (if org-tags-exclude-from-inheritance
12966 (org-delete-all org-tags-exclude-from-inheritance tags)
12967 tags))
12968 ((not org-use-tag-inheritance) nil)
12969 ((stringp org-use-tag-inheritance)
12970 (delq nil (mapcar
12971 (lambda (x)
12972 (if (and (string-match org-use-tag-inheritance x)
12973 (not (member x org-tags-exclude-from-inheritance)))
12974 x nil))
12975 tags)))
12976 ((listp org-use-tag-inheritance)
12977 (delq nil (mapcar
12978 (lambda (x)
12979 (if (member x org-use-tag-inheritance) x nil))
12980 tags)))))
12982 (defun org-match-sparse-tree (&optional todo-only match)
12983 "Create a sparse tree according to tags string MATCH.
12984 MATCH can contain positive and negative selection of tags, like
12985 \"+WORK+URGENT-WITHBOSS\".
12986 If optional argument TODO-ONLY is non-nil, only select lines that are
12987 also TODO lines."
12988 (interactive "P")
12989 (org-prepare-agenda-buffers (list (current-buffer)))
12990 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12992 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12994 (defvar org-cached-props nil)
12995 (defun org-cached-entry-get (pom property)
12996 (if (or (eq t org-use-property-inheritance)
12997 (and (stringp org-use-property-inheritance)
12998 (string-match org-use-property-inheritance property))
12999 (and (listp org-use-property-inheritance)
13000 (member property org-use-property-inheritance)))
13001 ;; Caching is not possible, check it directly
13002 (org-entry-get pom property 'inherit)
13003 ;; Get all properties, so that we can do complicated checks easily
13004 (cdr (assoc property (or org-cached-props
13005 (setq org-cached-props
13006 (org-entry-properties pom)))))))
13008 (defun org-global-tags-completion-table (&optional files)
13009 "Return the list of all tags in all agenda buffer/files.
13010 Optional FILES argument is a list of files to which can be used
13011 instead of the agenda files."
13012 (save-excursion
13013 (org-uniquify
13014 (delq nil
13015 (apply 'append
13016 (mapcar
13017 (lambda (file)
13018 (set-buffer (find-file-noselect file))
13019 (append (org-get-buffer-tags)
13020 (mapcar (lambda (x) (if (stringp (car-safe x))
13021 (list (car-safe x)) nil))
13022 org-tag-alist)))
13023 (if (and files (car files))
13024 files
13025 (org-agenda-files))))))))
13027 (defun org-make-tags-matcher (match)
13028 "Create the TAGS/TODO matcher form for the selection string MATCH.
13030 The variable `todo-only' is scoped dynamically into this function; it will be
13031 set to t if the matcher restricts matching to TODO entries,
13032 otherwise will not be touched.
13034 Returns a cons of the selection string MATCH and the constructed
13035 lisp form implementing the matcher. The matcher is to be
13036 evaluated at an Org entry, with point on the headline,
13037 and returns t if the entry matches the
13038 selection string MATCH. The returned lisp form references
13039 two variables with information about the entry, which must be
13040 bound around the form's evaluation: todo, the TODO keyword at the
13041 entry (or nil of none); and tags-list, the list of all tags at the
13042 entry including inherited ones. Additionally, the category
13043 of the entry (if any) must be specified as the text property
13044 'org-category on the headline.
13046 See also `org-scan-tags'.
13048 (declare (special todo-only))
13049 (unless (boundp 'todo-only)
13050 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13051 (unless match
13052 ;; Get a new match request, with completion
13053 (let ((org-last-tags-completion-table
13054 (org-global-tags-completion-table)))
13055 (setq match (org-completing-read-no-i
13056 "Match: " 'org-tags-completion-function nil nil nil
13057 'org-tags-history))))
13059 ;; Parse the string and create a lisp form
13060 (let ((match0 match)
13061 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13062 minus tag mm
13063 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13064 orterms term orlist re-p str-p level-p level-op time-p
13065 prop-p pn pv po gv rest)
13066 (if (string-match "/+" match)
13067 ;; match contains also a todo-matching request
13068 (progn
13069 (setq tagsmatch (substring match 0 (match-beginning 0))
13070 todomatch (substring match (match-end 0)))
13071 (if (string-match "^!" todomatch)
13072 (setq todo-only t todomatch (substring todomatch 1)))
13073 (if (string-match "^\\s-*$" todomatch)
13074 (setq todomatch nil)))
13075 ;; only matching tags
13076 (setq tagsmatch match todomatch nil))
13078 ;; Make the tags matcher
13079 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13080 (setq tagsmatcher t)
13081 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13082 (while (setq term (pop orterms))
13083 (while (and (equal (substring term -1) "\\") orterms)
13084 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13085 (while (string-match re term)
13086 (setq rest (substring term (match-end 0))
13087 minus (and (match-end 1)
13088 (equal (match-string 1 term) "-"))
13089 tag (save-match-data (replace-regexp-in-string
13090 "\\\\-" "-"
13091 (match-string 2 term)))
13092 re-p (equal (string-to-char tag) ?{)
13093 level-p (match-end 4)
13094 prop-p (match-end 5)
13095 mm (cond
13096 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13097 (level-p
13098 (setq level-op (org-op-to-function (match-string 3 term)))
13099 `(,level-op level ,(string-to-number
13100 (match-string 4 term))))
13101 (prop-p
13102 (setq pn (match-string 5 term)
13103 po (match-string 6 term)
13104 pv (match-string 7 term)
13105 re-p (equal (string-to-char pv) ?{)
13106 str-p (equal (string-to-char pv) ?\")
13107 time-p (save-match-data
13108 (string-match "^\"[[<].*[]>]\"$" pv))
13109 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13110 (if time-p (setq pv (org-matcher-time pv)))
13111 (setq po (org-op-to-function po (if time-p 'time str-p)))
13112 (cond
13113 ((equal pn "CATEGORY")
13114 (setq gv '(get-text-property (point) 'org-category)))
13115 ((equal pn "TODO")
13116 (setq gv 'todo))
13118 (setq gv `(org-cached-entry-get nil ,pn))))
13119 (if re-p
13120 (if (eq po 'org<>)
13121 `(not (string-match ,pv (or ,gv "")))
13122 `(string-match ,pv (or ,gv "")))
13123 (if str-p
13124 `(,po (or ,gv "") ,pv)
13125 `(,po (string-to-number (or ,gv ""))
13126 ,(string-to-number pv) ))))
13127 (t `(member ,tag tags-list)))
13128 mm (if minus (list 'not mm) mm)
13129 term rest)
13130 (push mm tagsmatcher))
13131 (push (if (> (length tagsmatcher) 1)
13132 (cons 'and tagsmatcher)
13133 (car tagsmatcher))
13134 orlist)
13135 (setq tagsmatcher nil))
13136 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13137 (setq tagsmatcher
13138 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13139 ;; Make the todo matcher
13140 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13141 (setq todomatcher t)
13142 (setq orterms (org-split-string todomatch "|") orlist nil)
13143 (while (setq term (pop orterms))
13144 (while (string-match re term)
13145 (setq minus (and (match-end 1)
13146 (equal (match-string 1 term) "-"))
13147 kwd (match-string 2 term)
13148 re-p (equal (string-to-char kwd) ?{)
13149 term (substring term (match-end 0))
13150 mm (if re-p
13151 `(string-match ,(substring kwd 1 -1) todo)
13152 (list 'equal 'todo kwd))
13153 mm (if minus (list 'not mm) mm))
13154 (push mm todomatcher))
13155 (push (if (> (length todomatcher) 1)
13156 (cons 'and todomatcher)
13157 (car todomatcher))
13158 orlist)
13159 (setq todomatcher nil))
13160 (setq todomatcher (if (> (length orlist) 1)
13161 (cons 'or orlist) (car orlist))))
13163 ;; Return the string and lisp forms of the matcher
13164 (setq matcher (if todomatcher
13165 (list 'and tagsmatcher todomatcher)
13166 tagsmatcher))
13167 (when todo-only
13168 (setq matcher (list 'and '(member todo org-not-done-keywords)
13169 matcher)))
13170 (cons match0 matcher)))
13172 (defun org-op-to-function (op &optional stringp)
13173 "Turn an operator into the appropriate function."
13174 (setq op
13175 (cond
13176 ((equal op "<" ) '(< string< org-time<))
13177 ((equal op ">" ) '(> org-string> org-time>))
13178 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13179 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13180 ((member op '("=" "==")) '(= string= org-time=))
13181 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13182 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13184 (defun org<> (a b) (not (= a b)))
13185 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13186 (defun org-string>= (a b) (not (string< a b)))
13187 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13188 (defun org-string<> (a b) (not (string= a b)))
13189 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13190 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13195 (defun org-2ft (s)
13196 "Convert S to a floating point time.
13197 If S is already a number, just return it. If it is a string, parse
13198 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13199 (cond
13200 ((numberp s) s)
13201 ((stringp s)
13202 (condition-case nil
13203 (float-time (apply 'encode-time (org-parse-time-string s)))
13204 (error 0.)))
13205 (t 0.)))
13207 (defun org-time-today ()
13208 "Time in seconds today at 0:00.
13209 Returns the float number of seconds since the beginning of the
13210 epoch to the beginning of today (00:00)."
13211 (float-time (apply 'encode-time
13212 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13214 (defun org-matcher-time (s)
13215 "Interpret a time comparison value."
13216 (save-match-data
13217 (cond
13218 ((string= s "<now>") (float-time))
13219 ((string= s "<today>") (org-time-today))
13220 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13221 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13222 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13223 (+ (org-time-today)
13224 (* (string-to-number (match-string 1 s))
13225 (cdr (assoc (match-string 2 s)
13226 '(("d" . 86400.0) ("w" . 604800.0)
13227 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13228 (t (org-2ft s)))))
13230 (defun org-match-any-p (re list)
13231 "Does re match any element of list?"
13232 (setq list (mapcar (lambda (x) (string-match re x)) list))
13233 (delq nil list))
13235 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13236 (defvar org-tags-overlay (make-overlay 1 1))
13237 (org-detach-overlay org-tags-overlay)
13239 (defun org-get-local-tags-at (&optional pos)
13240 "Get a list of tags defined in the current headline."
13241 (org-get-tags-at pos 'local))
13243 (defun org-get-local-tags ()
13244 "Get a list of tags defined in the current headline."
13245 (org-get-tags-at nil 'local))
13247 (defun org-get-tags-at (&optional pos local)
13248 "Get a list of all headline tags applicable at POS.
13249 POS defaults to point. If tags are inherited, the list contains
13250 the targets in the same sequence as the headlines appear, i.e.
13251 the tags of the current headline come last.
13252 When LOCAL is non-nil, only return tags from the current headline,
13253 ignore inherited ones."
13254 (interactive)
13255 (if (and org-trust-scanner-tags
13256 (or (not pos) (equal pos (point)))
13257 (not local))
13258 org-scanner-tags
13259 (let (tags ltags lastpos parent)
13260 (save-excursion
13261 (save-restriction
13262 (widen)
13263 (goto-char (or pos (point)))
13264 (save-match-data
13265 (catch 'done
13266 (condition-case nil
13267 (progn
13268 (org-back-to-heading t)
13269 (while (not (equal lastpos (point)))
13270 (setq lastpos (point))
13271 (when (looking-at
13272 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13273 (setq ltags (org-split-string
13274 (org-match-string-no-properties 1) ":"))
13275 (when parent
13276 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13277 (setq tags (append
13278 (if parent
13279 (org-remove-uninherited-tags ltags)
13280 ltags)
13281 tags)))
13282 (or org-use-tag-inheritance (throw 'done t))
13283 (if local (throw 'done t))
13284 (or (org-up-heading-safe) (error nil))
13285 (setq parent t)))
13286 (error nil)))))
13287 (if local
13288 tags
13289 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13291 (defun org-add-prop-inherited (s)
13292 (add-text-properties 0 (length s) '(inherited t) s)
13295 (defun org-toggle-tag (tag &optional onoff)
13296 "Toggle the tag TAG for the current line.
13297 If ONOFF is `on' or `off', don't toggle but set to this state."
13298 (let (res current)
13299 (save-excursion
13300 (org-back-to-heading t)
13301 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13302 (point-at-eol) t)
13303 (progn
13304 (setq current (match-string 1))
13305 (replace-match ""))
13306 (setq current ""))
13307 (setq current (nreverse (org-split-string current ":")))
13308 (cond
13309 ((eq onoff 'on)
13310 (setq res t)
13311 (or (member tag current) (push tag current)))
13312 ((eq onoff 'off)
13313 (or (not (member tag current)) (setq current (delete tag current))))
13314 (t (if (member tag current)
13315 (setq current (delete tag current))
13316 (setq res t)
13317 (push tag current))))
13318 (end-of-line 1)
13319 (if current
13320 (progn
13321 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13322 (org-set-tags nil t))
13323 (delete-horizontal-space))
13324 (run-hooks 'org-after-tags-change-hook))
13325 res))
13327 (defun org-align-tags-here (to-col)
13328 ;; Assumes that this is a headline
13329 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13330 (beginning-of-line 1)
13331 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13332 (< pos (match-beginning 2)))
13333 (progn
13334 (setq tags-l (- (match-end 2) (match-beginning 2)))
13335 (goto-char (match-beginning 1))
13336 (insert " ")
13337 (delete-region (point) (1+ (match-beginning 2)))
13338 (setq ncol (max (current-column)
13339 (1+ col)
13340 (if (> to-col 0)
13341 to-col
13342 (- (abs to-col) tags-l))))
13343 (setq p (point))
13344 (insert (make-string (- ncol (current-column)) ?\ ))
13345 (setq ncol (current-column))
13346 (when indent-tabs-mode (tabify p (point-at-eol)))
13347 (org-move-to-column (min ncol col) t))
13348 (goto-char pos))))
13350 (defun org-set-tags-command (&optional arg just-align)
13351 "Call the set-tags command for the current entry."
13352 (interactive "P")
13353 (if (org-at-heading-p)
13354 (org-set-tags arg just-align)
13355 (save-excursion
13356 (org-back-to-heading t)
13357 (org-set-tags arg just-align))))
13359 (defun org-set-tags-to (data)
13360 "Set the tags of the current entry to DATA, replacing the current tags.
13361 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13362 If DATA is nil or the empty string, any tags will be removed."
13363 (interactive "sTags: ")
13364 (setq data
13365 (cond
13366 ((eq data nil) "")
13367 ((equal data "") "")
13368 ((stringp data)
13369 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13370 ":"))
13371 ((listp data)
13372 (concat ":" (mapconcat 'identity data ":") ":"))
13373 (t nil)))
13374 (when data
13375 (save-excursion
13376 (org-back-to-heading t)
13377 (when (looking-at org-complex-heading-regexp)
13378 (if (match-end 5)
13379 (progn
13380 (goto-char (match-beginning 5))
13381 (insert data)
13382 (delete-region (point) (point-at-eol))
13383 (org-set-tags nil 'align))
13384 (goto-char (point-at-eol))
13385 (insert " " data)
13386 (org-set-tags nil 'align)))
13387 (beginning-of-line 1)
13388 (if (looking-at ".*?\\([ \t]+\\)$")
13389 (delete-region (match-beginning 1) (match-end 1))))))
13391 (defun org-align-all-tags ()
13392 "Align the tags i all headings."
13393 (interactive)
13394 (save-excursion
13395 (or (ignore-errors (org-back-to-heading t))
13396 (outline-next-heading))
13397 (if (org-at-heading-p)
13398 (org-set-tags t)
13399 (message "No headings"))))
13401 (defvar org-indent-indentation-per-level)
13402 (defun org-set-tags (&optional arg just-align)
13403 "Set the tags for the current headline.
13404 With prefix ARG, realign all tags in headings in the current buffer."
13405 (interactive "P")
13406 (let* ((re org-outline-regexp-bol)
13407 (current (org-get-tags-string))
13408 (col (current-column))
13409 (org-setting-tags t)
13410 table current-tags inherited-tags ; computed below when needed
13411 tags p0 c0 c1 rpl di tc level)
13412 (if arg
13413 (save-excursion
13414 (goto-char (point-min))
13415 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13416 (while (re-search-forward re nil t)
13417 (org-set-tags nil t)
13418 (end-of-line 1)))
13419 (message "All tags realigned to column %d" org-tags-column))
13420 (if just-align
13421 (setq tags current)
13422 ;; Get a new set of tags from the user
13423 (save-excursion
13424 (setq table (append org-tag-persistent-alist
13425 org-tag-alist
13426 (org-get-buffer-tags)
13427 (and
13428 org-complete-tags-always-offer-all-agenda-tags
13429 (org-global-tags-completion-table
13430 (org-agenda-files))))
13431 org-last-tags-completion-table table
13432 current-tags (org-split-string current ":")
13433 inherited-tags (nreverse
13434 (nthcdr (length current-tags)
13435 (nreverse (org-get-tags-at))))
13436 tags
13437 (if (or (eq t org-use-fast-tag-selection)
13438 (and org-use-fast-tag-selection
13439 (delq nil (mapcar 'cdr table))))
13440 (org-fast-tag-selection
13441 current-tags inherited-tags table
13442 (if org-fast-tag-selection-include-todo
13443 org-todo-key-alist))
13444 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13445 (org-trim
13446 (org-icompleting-read "Tags: "
13447 'org-tags-completion-function
13448 nil nil current 'org-tags-history))))))
13449 (while (string-match "[-+&]+" tags)
13450 ;; No boolean logic, just a list
13451 (setq tags (replace-match ":" t t tags))))
13453 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13455 (if org-tags-sort-function
13456 (setq tags (mapconcat 'identity
13457 (sort (org-split-string
13458 tags (org-re "[^[:alnum:]_@#%]+"))
13459 org-tags-sort-function) ":")))
13461 (if (string-match "\\`[\t ]*\\'" tags)
13462 (setq tags "")
13463 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13464 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13466 ;; Insert new tags at the correct column
13467 (beginning-of-line 1)
13468 (setq level (or (and (looking-at org-outline-regexp)
13469 (- (match-end 0) (point) 1))
13471 (cond
13472 ((and (equal current "") (equal tags "")))
13473 ((re-search-forward
13474 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13475 (point-at-eol) t)
13476 (if (equal tags "")
13477 (setq rpl "")
13478 (goto-char (match-beginning 0))
13479 (setq c0 (current-column)
13480 ;; compute offset for the case of org-indent-mode active
13481 di (if org-indent-mode
13482 (* (1- org-indent-indentation-per-level) (1- level))
13484 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13485 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13486 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13487 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13488 (replace-match rpl t t)
13489 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13490 tags)
13491 (t (error "Tags alignment failed")))
13492 (org-move-to-column col)
13493 (unless just-align
13494 (run-hooks 'org-after-tags-change-hook)))))
13496 (defun org-change-tag-in-region (beg end tag off)
13497 "Add or remove TAG for each entry in the region.
13498 This works in the agenda, and also in an org-mode buffer."
13499 (interactive
13500 (list (region-beginning) (region-end)
13501 (let ((org-last-tags-completion-table
13502 (if (eq major-mode 'org-mode)
13503 (org-get-buffer-tags)
13504 (org-global-tags-completion-table))))
13505 (org-icompleting-read
13506 "Tag: " 'org-tags-completion-function nil nil nil
13507 'org-tags-history))
13508 (progn
13509 (message "[s]et or [r]emove? ")
13510 (equal (read-char-exclusive) ?r))))
13511 (if (fboundp 'deactivate-mark) (deactivate-mark))
13512 (let ((agendap (equal major-mode 'org-agenda-mode))
13513 l1 l2 m buf pos newhead (cnt 0))
13514 (goto-char end)
13515 (setq l2 (1- (org-current-line)))
13516 (goto-char beg)
13517 (setq l1 (org-current-line))
13518 (loop for l from l1 to l2 do
13519 (org-goto-line l)
13520 (setq m (get-text-property (point) 'org-hd-marker))
13521 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13522 (and agendap m))
13523 (setq buf (if agendap (marker-buffer m) (current-buffer))
13524 pos (if agendap m (point)))
13525 (with-current-buffer buf
13526 (save-excursion
13527 (save-restriction
13528 (goto-char pos)
13529 (setq cnt (1+ cnt))
13530 (org-toggle-tag tag (if off 'off 'on))
13531 (setq newhead (org-get-heading)))))
13532 (and agendap (org-agenda-change-all-lines newhead m))))
13533 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13535 (defun org-tags-completion-function (string predicate &optional flag)
13536 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13537 (confirm (lambda (x) (stringp (car x)))))
13538 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13539 (setq s1 (match-string 1 string)
13540 s2 (match-string 2 string))
13541 (setq s1 "" s2 string))
13542 (cond
13543 ((eq flag nil)
13544 ;; try completion
13545 (setq rtn (try-completion s2 ctable confirm))
13546 (if (stringp rtn)
13547 (setq rtn
13548 (concat s1 s2 (substring rtn (length s2))
13549 (if (and org-add-colon-after-tag-completion
13550 (assoc rtn ctable))
13551 ":" ""))))
13552 rtn)
13553 ((eq flag t)
13554 ;; all-completions
13555 (all-completions s2 ctable confirm)
13557 ((eq flag 'lambda)
13558 ;; exact match?
13559 (assoc s2 ctable)))
13562 (defun org-fast-tag-insert (kwd tags face &optional end)
13563 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13564 (insert (format "%-12s" (concat kwd ":"))
13565 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13566 (or end "")))
13568 (defun org-fast-tag-show-exit (flag)
13569 (save-excursion
13570 (org-goto-line 3)
13571 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13572 (replace-match ""))
13573 (when flag
13574 (end-of-line 1)
13575 (org-move-to-column (- (window-width) 19) t)
13576 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13578 (defun org-set-current-tags-overlay (current prefix)
13579 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13580 (if (featurep 'xemacs)
13581 (org-overlay-display org-tags-overlay (concat prefix s)
13582 'secondary-selection)
13583 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13584 (org-overlay-display org-tags-overlay (concat prefix s)))))
13586 (defvar org-last-tag-selection-key nil)
13587 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13588 "Fast tag selection with single keys.
13589 CURRENT is the current list of tags in the headline, INHERITED is the
13590 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13591 possibly with grouping information. TODO-TABLE is a similar table with
13592 TODO keywords, should these have keys assigned to them.
13593 If the keys are nil, a-z are automatically assigned.
13594 Returns the new tags string, or nil to not change the current settings."
13595 (let* ((fulltable (append table todo-table))
13596 (maxlen (apply 'max (mapcar
13597 (lambda (x)
13598 (if (stringp (car x)) (string-width (car x)) 0))
13599 fulltable)))
13600 (buf (current-buffer))
13601 (expert (eq org-fast-tag-selection-single-key 'expert))
13602 (buffer-tags nil)
13603 (fwidth (+ maxlen 3 1 3))
13604 (ncol (/ (- (window-width) 4) fwidth))
13605 (i-face 'org-done)
13606 (c-face 'org-todo)
13607 tg cnt e c char c1 c2 ntable tbl rtn
13608 ov-start ov-end ov-prefix
13609 (exit-after-next org-fast-tag-selection-single-key)
13610 (done-keywords org-done-keywords)
13611 groups ingroup)
13612 (save-excursion
13613 (beginning-of-line 1)
13614 (if (looking-at
13615 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13616 (setq ov-start (match-beginning 1)
13617 ov-end (match-end 1)
13618 ov-prefix "")
13619 (setq ov-start (1- (point-at-eol))
13620 ov-end (1+ ov-start))
13621 (skip-chars-forward "^\n\r")
13622 (setq ov-prefix
13623 (concat
13624 (buffer-substring (1- (point)) (point))
13625 (if (> (current-column) org-tags-column)
13627 (make-string (- org-tags-column (current-column)) ?\ ))))))
13628 (move-overlay org-tags-overlay ov-start ov-end)
13629 (save-window-excursion
13630 (if expert
13631 (set-buffer (get-buffer-create " *Org tags*"))
13632 (delete-other-windows)
13633 (split-window-vertically)
13634 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13635 (erase-buffer)
13636 (org-set-local 'org-done-keywords done-keywords)
13637 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13638 (org-fast-tag-insert "Current" current c-face "\n\n")
13639 (org-fast-tag-show-exit exit-after-next)
13640 (org-set-current-tags-overlay current ov-prefix)
13641 (setq tbl fulltable char ?a cnt 0)
13642 (while (setq e (pop tbl))
13643 (cond
13644 ((equal (car e) :startgroup)
13645 (push '() groups) (setq ingroup t)
13646 (when (not (= cnt 0))
13647 (setq cnt 0)
13648 (insert "\n"))
13649 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13650 ((equal (car e) :endgroup)
13651 (setq ingroup nil cnt 0)
13652 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13653 ((equal e '(:newline))
13654 (when (not (= cnt 0))
13655 (setq cnt 0)
13656 (insert "\n")
13657 (setq e (car tbl))
13658 (while (equal (car tbl) '(:newline))
13659 (insert "\n")
13660 (setq tbl (cdr tbl)))))
13662 (setq tg (copy-sequence (car e)) c2 nil)
13663 (if (cdr e)
13664 (setq c (cdr e))
13665 ;; automatically assign a character.
13666 (setq c1 (string-to-char
13667 (downcase (substring
13668 tg (if (= (string-to-char tg) ?@) 1 0)))))
13669 (if (or (rassoc c1 ntable) (rassoc c1 table))
13670 (while (or (rassoc char ntable) (rassoc char table))
13671 (setq char (1+ char)))
13672 (setq c2 c1))
13673 (setq c (or c2 char)))
13674 (if ingroup (push tg (car groups)))
13675 (setq tg (org-add-props tg nil 'face
13676 (cond
13677 ((not (assoc tg table))
13678 (org-get-todo-face tg))
13679 ((member tg current) c-face)
13680 ((member tg inherited) i-face)
13681 (t nil))))
13682 (if (and (= cnt 0) (not ingroup)) (insert " "))
13683 (insert "[" c "] " tg (make-string
13684 (- fwidth 4 (length tg)) ?\ ))
13685 (push (cons tg c) ntable)
13686 (when (= (setq cnt (1+ cnt)) ncol)
13687 (insert "\n")
13688 (if ingroup (insert " "))
13689 (setq cnt 0)))))
13690 (setq ntable (nreverse ntable))
13691 (insert "\n")
13692 (goto-char (point-min))
13693 (if (not expert) (org-fit-window-to-buffer))
13694 (setq rtn
13695 (catch 'exit
13696 (while t
13697 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13698 (if (not groups) "no " "")
13699 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13700 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13701 (setq org-last-tag-selection-key c)
13702 (cond
13703 ((= c ?\r) (throw 'exit t))
13704 ((= c ?!)
13705 (setq groups (not groups))
13706 (goto-char (point-min))
13707 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13708 ((= c ?\C-c)
13709 (if (not expert)
13710 (org-fast-tag-show-exit
13711 (setq exit-after-next (not exit-after-next)))
13712 (setq expert nil)
13713 (delete-other-windows)
13714 (set-window-buffer (split-window-vertically) " *Org tags*")
13715 (org-switch-to-buffer-other-window " *Org tags*")
13716 (org-fit-window-to-buffer)))
13717 ((or (= c ?\C-g)
13718 (and (= c ?q) (not (rassoc c ntable))))
13719 (org-detach-overlay org-tags-overlay)
13720 (setq quit-flag t))
13721 ((= c ?\ )
13722 (setq current nil)
13723 (if exit-after-next (setq exit-after-next 'now)))
13724 ((= c ?\t)
13725 (condition-case nil
13726 (setq tg (org-icompleting-read
13727 "Tag: "
13728 (delete-dups
13729 (append (or buffer-tags
13730 (with-current-buffer buf
13731 (mapcar 'car (org-get-buffer-tags))))
13732 (delq nil
13733 (mapcar (lambda (x)
13734 (if (stringp
13735 (car x)) x)) table))))))
13736 (quit (setq tg "")))
13737 (when (string-match "\\S-" tg)
13738 (add-to-list 'buffer-tags (list tg))
13739 (if (member tg current)
13740 (setq current (delete tg current))
13741 (push tg current)))
13742 (if exit-after-next (setq exit-after-next 'now)))
13743 ((setq e (rassoc c todo-table) tg (car e))
13744 (with-current-buffer buf
13745 (save-excursion (org-todo tg)))
13746 (if exit-after-next (setq exit-after-next 'now)))
13747 ((setq e (rassoc c ntable) tg (car e))
13748 (if (member tg current)
13749 (setq current (delete tg current))
13750 (loop for g in groups do
13751 (if (member tg g)
13752 (mapc (lambda (x)
13753 (setq current (delete x current)))
13754 g)))
13755 (push tg current))
13756 (if exit-after-next (setq exit-after-next 'now))))
13758 ;; Create a sorted list
13759 (setq current
13760 (sort current
13761 (lambda (a b)
13762 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13763 (if (eq exit-after-next 'now) (throw 'exit t))
13764 (goto-char (point-min))
13765 (beginning-of-line 2)
13766 (delete-region (point) (point-at-eol))
13767 (org-fast-tag-insert "Current" current c-face)
13768 (org-set-current-tags-overlay current ov-prefix)
13769 (while (re-search-forward
13770 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13771 (setq tg (match-string 1))
13772 (add-text-properties
13773 (match-beginning 1) (match-end 1)
13774 (list 'face
13775 (cond
13776 ((member tg current) c-face)
13777 ((member tg inherited) i-face)
13778 (t (get-text-property (match-beginning 1) 'face))))))
13779 (goto-char (point-min)))))
13780 (org-detach-overlay org-tags-overlay)
13781 (if rtn
13782 (mapconcat 'identity current ":")
13783 nil))))
13785 (defun org-get-tags-string ()
13786 "Get the TAGS string in the current headline."
13787 (unless (org-at-heading-p t)
13788 (error "Not on a heading"))
13789 (save-excursion
13790 (beginning-of-line 1)
13791 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13792 (org-match-string-no-properties 1)
13793 "")))
13795 (defun org-get-tags ()
13796 "Get the list of tags specified in the current headline."
13797 (org-split-string (org-get-tags-string) ":"))
13799 (defun org-get-buffer-tags ()
13800 "Get a table of all tags used in the buffer, for completion."
13801 (let (tags)
13802 (save-excursion
13803 (goto-char (point-min))
13804 (while (re-search-forward
13805 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13806 (when (equal (char-after (point-at-bol 0)) ?*)
13807 (mapc (lambda (x) (add-to-list 'tags x))
13808 (org-split-string (org-match-string-no-properties 1) ":")))))
13809 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13810 (mapcar 'list tags)))
13812 ;;;; The mapping API
13814 ;;;###autoload
13815 (defun org-map-entries (func &optional match scope &rest skip)
13816 "Call FUNC at each headline selected by MATCH in SCOPE.
13818 FUNC is a function or a lisp form. The function will be called without
13819 arguments, with the cursor positioned at the beginning of the headline.
13820 The return values of all calls to the function will be collected and
13821 returned as a list.
13823 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13824 does not need to preserve point. After evaluation, the cursor will be
13825 moved to the end of the line (presumably of the headline of the
13826 processed entry) and search continues from there. Under some
13827 circumstances, this may not produce the wanted results. For example,
13828 if you have removed (e.g. archived) the current (sub)tree it could
13829 mean that the next entry will be skipped entirely. In such cases, you
13830 can specify the position from where search should continue by making
13831 FUNC set the variable `org-map-continue-from' to the desired buffer
13832 position.
13834 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13835 Only headlines that are matched by this query will be considered during
13836 the iteration. When MATCH is nil or t, all headlines will be
13837 visited by the iteration.
13839 SCOPE determines the scope of this command. It can be any of:
13841 nil The current buffer, respecting the restriction if any
13842 tree The subtree started with the entry at point
13843 region The entries within the active region, if any
13844 region-start-level
13845 The entries within the active region, but only those at
13846 the same level than the first one.
13847 file The current buffer, without restriction
13848 file-with-archives
13849 The current buffer, and any archives associated with it
13850 agenda All agenda files
13851 agenda-with-archives
13852 All agenda files with any archive files associated with them
13853 \(file1 file2 ...)
13854 If this is a list, all files in the list will be scanned
13856 The remaining args are treated as settings for the skipping facilities of
13857 the scanner. The following items can be given here:
13859 archive skip trees with the archive tag.
13860 comment skip trees with the COMMENT keyword
13861 function or Emacs Lisp form:
13862 will be used as value for `org-agenda-skip-function', so whenever
13863 the function returns t, FUNC will not be called for that
13864 entry and search will continue from the point where the
13865 function leaves it.
13867 If your function needs to retrieve the tags including inherited tags
13868 at the *current* entry, you can use the value of the variable
13869 `org-scanner-tags' which will be much faster than getting the value
13870 with `org-get-tags-at'. If your function gets properties with
13871 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13872 to t around the call to `org-entry-properties' to get the same speedup.
13873 Note that if your function moves around to retrieve tags and properties at
13874 a *different* entry, you cannot use these techniques."
13875 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13876 (not (org-region-active-p)))
13877 (let* ((org-agenda-archives-mode nil) ; just to make sure
13878 (org-agenda-skip-archived-trees (memq 'archive skip))
13879 (org-agenda-skip-comment-trees (memq 'comment skip))
13880 (org-agenda-skip-function
13881 (car (org-delete-all '(comment archive) skip)))
13882 (org-tags-match-list-sublevels t)
13883 (start-level (eq scope 'region-start-level))
13884 matcher file res
13885 org-todo-keywords-for-agenda
13886 org-done-keywords-for-agenda
13887 org-todo-keyword-alist-for-agenda
13888 org-drawers-for-agenda
13889 org-tag-alist-for-agenda
13890 todo-only)
13892 (cond
13893 ((eq match t) (setq matcher t))
13894 ((eq match nil) (setq matcher t))
13895 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13897 (save-excursion
13898 (save-restriction
13899 (cond ((eq scope 'tree)
13900 (org-back-to-heading t)
13901 (org-narrow-to-subtree)
13902 (setq scope nil))
13903 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13904 (org-region-active-p))
13905 ;; If needed, set start-level to a string like "2"
13906 (when start-level
13907 (save-excursion
13908 (goto-char (region-beginning))
13909 (unless (org-at-heading-p) (outline-next-heading))
13910 (setq start-level (org-current-level))))
13911 (narrow-to-region (region-beginning)
13912 (save-excursion
13913 (goto-char (region-end))
13914 (unless (and (bolp) (org-at-heading-p))
13915 (outline-next-heading))
13916 (point)))
13917 (setq scope nil)))
13919 (if (not scope)
13920 (progn
13921 (org-prepare-agenda-buffers
13922 (list (buffer-file-name (current-buffer))))
13923 (setq res (org-scan-tags func matcher todo-only start-level)))
13924 ;; Get the right scope
13925 (cond
13926 ((and scope (listp scope) (symbolp (car scope)))
13927 (setq scope (eval scope)))
13928 ((eq scope 'agenda)
13929 (setq scope (org-agenda-files t)))
13930 ((eq scope 'agenda-with-archives)
13931 (setq scope (org-agenda-files t))
13932 (setq scope (org-add-archive-files scope)))
13933 ((eq scope 'file)
13934 (setq scope (list (buffer-file-name))))
13935 ((eq scope 'file-with-archives)
13936 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13937 (org-prepare-agenda-buffers scope)
13938 (while (setq file (pop scope))
13939 (with-current-buffer (org-find-base-buffer-visiting file)
13940 (save-excursion
13941 (save-restriction
13942 (widen)
13943 (goto-char (point-min))
13944 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13945 res)))
13947 ;;;; Properties
13949 ;;; Setting and retrieving properties
13951 (defconst org-special-properties
13952 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13953 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13954 "The special properties valid in Org-mode.
13956 These are properties that are not defined in the property drawer,
13957 but in some other way.")
13959 (defconst org-default-properties
13960 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13961 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13962 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13963 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13964 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13965 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13966 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13967 "Some properties that are used by Org-mode for various purposes.
13968 Being in this list makes sure that they are offered for completion.")
13970 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13971 "Regular expression matching the first line of a property drawer.")
13973 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13974 "Regular expression matching the last line of a property drawer.")
13976 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13977 "Regular expression matching the first line of a property drawer.")
13979 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13980 "Regular expression matching the first line of a property drawer.")
13982 (defconst org-property-drawer-re
13983 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13984 org-property-end-re "\\)\n?")
13985 "Matches an entire property drawer.")
13987 (defconst org-clock-drawer-re
13988 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13989 org-property-end-re "\\)\n?")
13990 "Matches an entire clock drawer.")
13992 (defsubst org-re-property (property)
13993 "Return a regexp matching PROPERTY.
13994 Match group 1 will be set to the value "
13995 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13997 (defun org-property-action ()
13998 "Do an action on properties."
13999 (interactive)
14000 (let (c)
14001 (org-at-property-p)
14002 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14003 (setq c (read-char-exclusive))
14004 (cond
14005 ((equal c ?s)
14006 (call-interactively 'org-set-property))
14007 ((equal c ?d)
14008 (call-interactively 'org-delete-property))
14009 ((equal c ?D)
14010 (call-interactively 'org-delete-property-globally))
14011 ((equal c ?c)
14012 (call-interactively 'org-compute-property-at-point))
14013 (t (error "No such property action %c" c)))))
14015 (defun org-set-effort (&optional value)
14016 "Set the effort property of the current entry.
14017 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14018 allowed value."
14019 (interactive "P")
14020 (if (equal value 0) (setq value 10))
14021 (let* ((completion-ignore-case t)
14022 (prop org-effort-property)
14023 (cur (org-entry-get nil prop))
14024 (allowed (org-property-get-allowed-values nil prop 'table))
14025 (existing (mapcar 'list (org-property-values prop)))
14027 (val (cond
14028 ((stringp value) value)
14029 ((and allowed (integerp value))
14030 (or (car (nth (1- value) allowed))
14031 (car (org-last allowed))))
14032 (allowed
14033 (message "Select 1-9,0, [RET%s]: %s"
14034 (if cur (concat "=" cur) "")
14035 (mapconcat 'car allowed " "))
14036 (setq rpl (read-char-exclusive))
14037 (if (equal rpl ?\r)
14039 (setq rpl (- rpl ?0))
14040 (if (equal rpl 0) (setq rpl 10))
14041 (if (and (> rpl 0) (<= rpl (length allowed)))
14042 (car (nth (1- rpl) allowed))
14043 (org-completing-read "Effort: " allowed nil))))
14045 (let (org-completion-use-ido org-completion-use-iswitchb)
14046 (org-completing-read
14047 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14048 (concat "[" cur "]") "")
14049 ": ")
14050 existing nil nil "" nil cur))))))
14051 (unless (equal (org-entry-get nil prop) val)
14052 (org-entry-put nil prop val))
14053 (message "%s is now %s" prop val)))
14055 (defun org-at-property-p ()
14056 "Is cursor inside a property drawer?"
14057 (save-excursion
14058 (beginning-of-line 1)
14059 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14060 (save-match-data ;; Used by calling procedures
14061 (let ((p (point))
14062 (range (unless (org-before-first-heading-p)
14063 (org-get-property-block))))
14064 (and range (<= (car range) p) (< p (cdr range))))))))
14066 (defun org-get-property-block (&optional beg end force)
14067 "Return the (beg . end) range of the body of the property drawer.
14068 BEG and END can be beginning and end of subtree, if not given
14069 they will be found.
14070 If the drawer does not exist and FORCE is non-nil, create the drawer."
14071 (catch 'exit
14072 (save-excursion
14073 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14074 (end (or end (progn (outline-next-heading) (point)))))
14075 (goto-char beg)
14076 (if (re-search-forward org-property-start-re end t)
14077 (setq beg (1+ (match-end 0)))
14078 (if force
14079 (save-excursion
14080 (org-insert-property-drawer)
14081 (setq end (progn (outline-next-heading) (point))))
14082 (throw 'exit nil))
14083 (goto-char beg)
14084 (if (re-search-forward org-property-start-re end t)
14085 (setq beg (1+ (match-end 0)))))
14086 (if (re-search-forward org-property-end-re end t)
14087 (setq end (match-beginning 0))
14088 (or force (throw 'exit nil))
14089 (goto-char beg)
14090 (setq end beg)
14091 (org-indent-line-function)
14092 (insert ":END:\n"))
14093 (cons beg end)))))
14095 (defun org-entry-properties (&optional pom which specific)
14096 "Get all properties of the entry at point-or-marker POM.
14097 This includes the TODO keyword, the tags, time strings for deadline,
14098 scheduled, and clocking, and any additional properties defined in the
14099 entry. The return value is an alist, keys may occur multiple times
14100 if the property key was used several times.
14101 POM may also be nil, in which case the current entry is used.
14102 If WHICH is nil or `all', get all properties. If WHICH is
14103 `special' or `standard', only get that subclass. If WHICH
14104 is a string only get exactly this property. SPECIFIC can be a string, the
14105 specific property we are interested in. Specifying it can speed
14106 things up because then unnecessary parsing is avoided."
14107 (setq which (or which 'all))
14108 (org-with-point-at pom
14109 (let ((clockstr (substring org-clock-string 0 -1))
14110 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14111 (case-fold-search nil)
14112 beg end range props sum-props key key1 value string clocksum)
14113 (save-excursion
14114 (when (condition-case nil
14115 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14116 (error nil))
14117 (setq beg (point))
14118 (setq sum-props (get-text-property (point) 'org-summaries))
14119 (setq clocksum (get-text-property (point) :org-clock-minutes))
14120 (outline-next-heading)
14121 (setq end (point))
14122 (when (memq which '(all special))
14123 ;; Get the special properties, like TODO and tags
14124 (goto-char beg)
14125 (when (and (or (not specific) (string= specific "TODO"))
14126 (looking-at org-todo-line-regexp) (match-end 2))
14127 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14128 (when (and (or (not specific) (string= specific "PRIORITY"))
14129 (looking-at org-priority-regexp))
14130 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14131 (when (or (not specific) (string= specific "FILE"))
14132 (push (cons "FILE" buffer-file-name) props))
14133 (when (and (or (not specific) (string= specific "TAGS"))
14134 (setq value (org-get-tags-string))
14135 (string-match "\\S-" value))
14136 (push (cons "TAGS" value) props))
14137 (when (and (or (not specific) (string= specific "ALLTAGS"))
14138 (setq value (org-get-tags-at)))
14139 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14140 ":"))
14141 props))
14142 (when (or (not specific) (string= specific "BLOCKED"))
14143 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14144 (when (or (not specific)
14145 (member specific
14146 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14147 "TIMESTAMP" "TIMESTAMP_IA")))
14148 (catch 'match
14149 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14150 (setq key (if (match-end 1)
14151 (substring (org-match-string-no-properties 1)
14152 0 -1))
14153 string (if (equal key clockstr)
14154 (org-no-properties
14155 (org-trim
14156 (buffer-substring
14157 (match-beginning 3) (goto-char
14158 (point-at-eol)))))
14159 (substring (org-match-string-no-properties 3)
14160 1 -1)))
14161 ;; Get the correct property name from the key. This is
14162 ;; necessary if the user has configured time keywords.
14163 (setq key1 (concat key ":"))
14164 (cond
14165 ((not key)
14166 (setq key
14167 (if (= (char-after (match-beginning 3)) ?\[)
14168 "TIMESTAMP_IA" "TIMESTAMP")))
14169 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14170 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14171 ((equal key1 org-closed-string) (setq key "CLOSED"))
14172 ((equal key1 org-clock-string) (setq key "CLOCK")))
14173 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14174 (progn
14175 (push (cons key string) props)
14176 ;; no need to search further if match is found
14177 (throw 'match t))
14178 (when (or (equal key "CLOCK") (not (assoc key props)))
14179 (push (cons key string) props))))))
14182 (when (memq which '(all standard))
14183 ;; Get the standard properties, like :PROP: ...
14184 (setq range (org-get-property-block beg end))
14185 (when range
14186 (goto-char (car range))
14187 (while (re-search-forward
14188 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14189 (cdr range) t)
14190 (setq key (org-match-string-no-properties 1)
14191 value (org-trim (or (org-match-string-no-properties 2) "")))
14192 (unless (member key excluded)
14193 (push (cons key (or value "")) props)))))
14194 (if clocksum
14195 (push (cons "CLOCKSUM"
14196 (org-columns-number-to-string (/ (float clocksum) 60.)
14197 'add_times))
14198 props))
14199 (unless (assoc "CATEGORY" props)
14200 (push (cons "CATEGORY" (org-get-category)) props))
14201 (append sum-props (nreverse props)))))))
14203 (defun org-entry-get (pom property &optional inherit literal-nil)
14204 "Get value of PROPERTY for entry at point-or-marker POM.
14205 If INHERIT is non-nil and the entry does not have the property,
14206 then also check higher levels of the hierarchy.
14207 If INHERIT is the symbol `selective', use inheritance only if the setting
14208 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14209 If the property is present but empty, the return value is the empty string.
14210 If the property is not present at all, nil is returned.
14212 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14213 do not interpret it as the list atom nil. This is used for inheritance
14214 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14215 (org-with-point-at pom
14216 (if (and inherit (if (eq inherit 'selective)
14217 (org-property-inherit-p property)
14219 (org-entry-get-with-inheritance property literal-nil)
14220 (if (member property org-special-properties)
14221 ;; We need a special property. Use `org-entry-properties' to
14222 ;; retrieve it, but specify the wanted property
14223 (cdr (assoc property (org-entry-properties nil 'special property)))
14224 (let ((range (unless (org-before-first-heading-p)
14225 (org-get-property-block)))
14226 (props (list (or (assoc property org-file-properties)
14227 (assoc property org-global-properties)
14228 (assoc property org-global-properties-fixed))))
14229 val)
14230 (flet ((ap (key)
14231 (when (re-search-forward
14232 (org-re-property key) (cdr range) t)
14233 (setq props
14234 (org-update-property-plist
14236 (if (match-end 1)
14237 (org-match-string-no-properties 1) "")
14238 props)))))
14239 (when (and range (goto-char (car range)))
14240 (ap property)
14241 (goto-char (car range))
14242 (while (ap (concat property "+")))
14243 (setq val (cdr (assoc property props)))
14244 (when val (if literal-nil val (org-not-nil val))))))))))
14246 (defun org-property-or-variable-value (var &optional inherit)
14247 "Check if there is a property fixing the value of VAR.
14248 If yes, return this value. If not, return the current value of the variable."
14249 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14250 (if (and prop (stringp prop) (string-match "\\S-" prop))
14251 (read prop)
14252 (symbol-value var))))
14254 (defun org-entry-delete (pom property)
14255 "Delete the property PROPERTY from entry at point-or-marker POM."
14256 (org-with-point-at pom
14257 (if (member property org-special-properties)
14258 nil ; cannot delete these properties.
14259 (let ((range (org-get-property-block)))
14260 (if (and range
14261 (goto-char (car range))
14262 (re-search-forward
14263 (org-re-property property)
14264 (cdr range) t))
14265 (progn
14266 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14268 nil)))))
14270 ;; Multi-values properties are properties that contain multiple values
14271 ;; These values are assumed to be single words, separated by whitespace.
14272 (defun org-entry-add-to-multivalued-property (pom property value)
14273 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14274 (let* ((old (org-entry-get pom property))
14275 (values (and old (org-split-string old "[ \t]"))))
14276 (setq value (org-entry-protect-space value))
14277 (unless (member value values)
14278 (setq values (cons value values))
14279 (org-entry-put pom property
14280 (mapconcat 'identity values " ")))))
14282 (defun org-entry-remove-from-multivalued-property (pom property value)
14283 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14284 (let* ((old (org-entry-get pom property))
14285 (values (and old (org-split-string old "[ \t]"))))
14286 (setq value (org-entry-protect-space value))
14287 (when (member value values)
14288 (setq values (delete value values))
14289 (org-entry-put pom property
14290 (mapconcat 'identity values " ")))))
14292 (defun org-entry-member-in-multivalued-property (pom property value)
14293 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14294 (let* ((old (org-entry-get pom property))
14295 (values (and old (org-split-string old "[ \t]"))))
14296 (setq value (org-entry-protect-space value))
14297 (member value values)))
14299 (defun org-entry-get-multivalued-property (pom property)
14300 "Return a list of values in a multivalued property."
14301 (let* ((value (org-entry-get pom property))
14302 (values (and value (org-split-string value "[ \t]"))))
14303 (mapcar 'org-entry-restore-space values)))
14305 (defun org-entry-put-multivalued-property (pom property &rest values)
14306 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14307 VALUES should be a list of strings. Spaces will be protected."
14308 (org-entry-put pom property
14309 (mapconcat 'org-entry-protect-space values " "))
14310 (let* ((value (org-entry-get pom property))
14311 (values (and value (org-split-string value "[ \t]"))))
14312 (mapcar 'org-entry-restore-space values)))
14314 (defun org-entry-protect-space (s)
14315 "Protect spaces and newline in string S."
14316 (while (string-match " " s)
14317 (setq s (replace-match "%20" t t s)))
14318 (while (string-match "\n" s)
14319 (setq s (replace-match "%0A" t t s)))
14322 (defun org-entry-restore-space (s)
14323 "Restore spaces and newline in string S."
14324 (while (string-match "%20" s)
14325 (setq s (replace-match " " t t s)))
14326 (while (string-match "%0A" s)
14327 (setq s (replace-match "\n" t t s)))
14330 (defvar org-entry-property-inherited-from (make-marker)
14331 "Marker pointing to the entry from where a property was inherited.
14332 Each call to `org-entry-get-with-inheritance' will set this marker to the
14333 location of the entry where the inheritance search matched. If there was
14334 no match, the marker will point nowhere.
14335 Note that also `org-entry-get' calls this function, if the INHERIT flag
14336 is set.")
14338 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14339 "Get entry property, and search higher levels if not present.
14340 The search will stop at the first ancestor which has the property defined.
14341 If the value found is \"nil\", return nil to show that the property
14342 should be considered as undefined (this is the meaning of nil here).
14343 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14344 (move-marker org-entry-property-inherited-from nil)
14345 (let (tmp)
14346 (unless (org-before-first-heading-p)
14347 (save-excursion
14348 (save-restriction
14349 (widen)
14350 (catch 'ex
14351 (while t
14352 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14353 (org-back-to-heading t)
14354 (move-marker org-entry-property-inherited-from (point))
14355 (throw 'ex tmp))
14356 (or (org-up-heading-safe) (throw 'ex nil)))))))
14357 (setq tmp (or tmp
14358 (cdr (assoc property org-file-properties))
14359 (cdr (assoc property org-global-properties))
14360 (cdr (assoc property org-global-properties-fixed))))
14361 (if literal-nil tmp (org-not-nil tmp))))
14363 (defvar org-property-changed-functions nil
14364 "Hook called when the value of a property has changed.
14365 Each hook function should accept two arguments, the name of the property
14366 and the new value.")
14368 (defun org-entry-put (pom property value)
14369 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14370 (org-with-point-at pom
14371 (org-back-to-heading t)
14372 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14373 range)
14374 (cond
14375 ((equal property "TODO")
14376 (when (and (stringp value) (string-match "\\S-" value)
14377 (not (member value org-todo-keywords-1)))
14378 (error "\"%s\" is not a valid TODO state" value))
14379 (if (or (not value)
14380 (not (string-match "\\S-" value)))
14381 (setq value 'none))
14382 (org-todo value)
14383 (org-set-tags nil 'align))
14384 ((equal property "PRIORITY")
14385 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14386 (string-to-char value) ?\ ))
14387 (org-set-tags nil 'align))
14388 ((equal property "SCHEDULED")
14389 (if (re-search-forward org-scheduled-time-regexp end t)
14390 (cond
14391 ((eq value 'earlier) (org-timestamp-change -1 'day))
14392 ((eq value 'later) (org-timestamp-change 1 'day))
14393 (t (call-interactively 'org-schedule)))
14394 (call-interactively 'org-schedule)))
14395 ((equal property "DEADLINE")
14396 (if (re-search-forward org-deadline-time-regexp end t)
14397 (cond
14398 ((eq value 'earlier) (org-timestamp-change -1 'day))
14399 ((eq value 'later) (org-timestamp-change 1 'day))
14400 (t (call-interactively 'org-deadline)))
14401 (call-interactively 'org-deadline)))
14402 ((member property org-special-properties)
14403 (error "The %s property can not yet be set with `org-entry-put'"
14404 property))
14405 (t ; a non-special property
14406 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14407 (setq range (org-get-property-block beg end 'force))
14408 (goto-char (car range))
14409 (if (re-search-forward
14410 (org-re-property property) (cdr range) t)
14411 (progn
14412 (delete-region (match-beginning 0) (match-end 0))
14413 (goto-char (match-beginning 0)))
14414 (goto-char (cdr range))
14415 (insert "\n")
14416 (backward-char 1)
14417 (org-indent-line-function))
14418 (insert ":" property ":")
14419 (and value (insert " " value))
14420 (org-indent-line-function)))))
14421 (run-hook-with-args 'org-property-changed-functions property value)))
14423 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14424 "Get all property keys in the current buffer.
14425 With INCLUDE-SPECIALS, also list the special properties that reflect things
14426 like tags and TODO state.
14427 With INCLUDE-DEFAULTS, also include properties that has special meaning
14428 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14429 and others.
14430 With INCLUDE-COLUMNS, also include property names given in COLUMN
14431 formats in the current buffer."
14432 (let (rtn range cfmt s p)
14433 (save-excursion
14434 (save-restriction
14435 (widen)
14436 (goto-char (point-min))
14437 (while (re-search-forward org-property-start-re nil t)
14438 (setq range (org-get-property-block))
14439 (goto-char (car range))
14440 (while (re-search-forward
14441 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14442 (cdr range) t)
14443 (add-to-list 'rtn (org-match-string-no-properties 1)))
14444 (outline-next-heading))))
14446 (when include-specials
14447 (setq rtn (append org-special-properties rtn)))
14449 (when include-defaults
14450 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14451 (add-to-list 'rtn org-effort-property))
14453 (when include-columns
14454 (save-excursion
14455 (save-restriction
14456 (widen)
14457 (goto-char (point-min))
14458 (while (re-search-forward
14459 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14460 nil t)
14461 (setq cfmt (match-string 2) s 0)
14462 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14463 cfmt s)
14464 (setq s (match-end 0)
14465 p (match-string 1 cfmt))
14466 (unless (or (equal p "ITEM")
14467 (member p org-special-properties))
14468 (add-to-list 'rtn (match-string 1 cfmt))))))))
14470 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14472 (defun org-property-values (key)
14473 "Return a list of all values of property KEY in the current buffer."
14474 (save-excursion
14475 (save-restriction
14476 (widen)
14477 (goto-char (point-min))
14478 (let ((re (org-re-property key))
14479 values)
14480 (while (re-search-forward re nil t)
14481 (add-to-list 'values (org-trim (match-string 1))))
14482 (delete "" values)))))
14484 (defun org-insert-property-drawer ()
14485 "Insert a property drawer into the current entry."
14486 (interactive)
14487 (org-back-to-heading t)
14488 (looking-at org-outline-regexp)
14489 (let ((indent (if org-adapt-indentation
14490 (- (match-end 0)(match-beginning 0))
14492 (beg (point))
14493 (re (concat "^[ \t]*" org-keyword-time-regexp))
14494 end hiddenp)
14495 (outline-next-heading)
14496 (setq end (point))
14497 (goto-char beg)
14498 (while (re-search-forward re end t))
14499 (setq hiddenp (outline-invisible-p))
14500 (end-of-line 1)
14501 (and (equal (char-after) ?\n) (forward-char 1))
14502 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14503 (if (member (match-string 1) '("CLOCK:" ":END:"))
14504 ;; just skip this line
14505 (beginning-of-line 2)
14506 ;; Drawer start, find the end
14507 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14508 (beginning-of-line 1)))
14509 (org-skip-over-state-notes)
14510 (skip-chars-backward " \t\n\r")
14511 (if (eq (char-before) ?*) (forward-char 1))
14512 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14513 (beginning-of-line 0)
14514 (org-indent-to-column indent)
14515 (beginning-of-line 2)
14516 (org-indent-to-column indent)
14517 (beginning-of-line 0)
14518 (if hiddenp
14519 (save-excursion
14520 (org-back-to-heading t)
14521 (hide-entry))
14522 (org-flag-drawer t))))
14524 (defvar org-property-set-functions-alist nil
14525 "Property set function alist.
14526 Each entry should have the following format:
14528 (PROPERTY . READ-FUNCTION)
14530 The read function will be called with the same argument as
14531 `org-completing-read'.")
14533 (defun org-set-property-function (property)
14534 "Get the function that should be used to set PROPERTY.
14535 This is computed according to `org-property-set-functions-alist'."
14536 (or (cdr (assoc property org-property-set-functions-alist))
14537 'org-completing-read))
14539 (defun org-read-property-value (property)
14540 "Read PROPERTY value from user."
14541 (let* ((completion-ignore-case t)
14542 (allowed (org-property-get-allowed-values nil property 'table))
14543 (cur (org-entry-get nil property))
14544 (prompt (concat property " value"
14545 (if (and cur (string-match "\\S-" cur))
14546 (concat " [" cur "]") "") ": "))
14547 (set-function (org-set-property-function property))
14548 (val (if allowed
14549 (funcall set-function prompt allowed nil
14550 (not (get-text-property 0 'org-unrestricted
14551 (caar allowed))))
14552 (let (org-completion-use-ido org-completion-use-iswitchb)
14553 (funcall set-function prompt
14554 (mapcar 'list (org-property-values property))
14555 nil nil "" nil cur)))))
14556 (if (equal val "")
14558 val)))
14560 (defvar org-last-set-property nil)
14561 (defun org-read-property-name ()
14562 "Read a property name."
14563 (let* ((completion-ignore-case t)
14564 (keys (org-buffer-property-keys nil t t))
14565 (default-prop (or (save-excursion
14566 (save-match-data
14567 (beginning-of-line)
14568 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14569 (null (string= (match-string 1) "END"))
14570 (match-string 1))))
14571 org-last-set-property))
14572 (property (org-icompleting-read
14573 (concat "Property"
14574 (if default-prop (concat " [" default-prop "]") "")
14575 ": ")
14576 (mapcar 'list keys)
14577 nil nil nil nil
14578 default-prop
14580 (if (member property keys)
14581 property
14582 (or (cdr (assoc (downcase property)
14583 (mapcar (lambda (x) (cons (downcase x) x))
14584 keys)))
14585 property))))
14587 (defun org-set-property (property value)
14588 "In the current entry, set PROPERTY to VALUE.
14589 When called interactively, this will prompt for a property name, offering
14590 completion on existing and default properties. And then it will prompt
14591 for a value, offering completion either on allowed values (via an inherited
14592 xxx_ALL property) or on existing values in other instances of this property
14593 in the current file."
14594 (interactive (list nil nil))
14595 (let* ((property (or property (org-read-property-name)))
14596 (value (or value (org-read-property-value property)))
14597 (fn (assoc property org-properties-postprocess-alist)))
14598 (setq org-last-set-property property)
14599 ;; Possibly postprocess the inserted value:
14600 (when fn (setq value (funcall (cadr fn) value)))
14601 (unless (equal (org-entry-get nil property) value)
14602 (org-entry-put nil property value))))
14604 (defun org-delete-property (property)
14605 "In the current entry, delete PROPERTY."
14606 (interactive
14607 (let* ((completion-ignore-case t)
14608 (prop (org-icompleting-read "Property: "
14609 (org-entry-properties nil 'standard))))
14610 (list prop)))
14611 (message "Property %s %s" property
14612 (if (org-entry-delete nil property)
14613 "deleted"
14614 "was not present in the entry")))
14616 (defun org-delete-property-globally (property)
14617 "Remove PROPERTY globally, from all entries."
14618 (interactive
14619 (let* ((completion-ignore-case t)
14620 (prop (org-icompleting-read
14621 "Globally remove property: "
14622 (mapcar 'list (org-buffer-property-keys)))))
14623 (list prop)))
14624 (save-excursion
14625 (save-restriction
14626 (widen)
14627 (goto-char (point-min))
14628 (let ((cnt 0))
14629 (while (re-search-forward
14630 (org-re-property property)
14631 nil t)
14632 (setq cnt (1+ cnt))
14633 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14634 (message "Property \"%s\" removed from %d entries" property cnt)))))
14636 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14638 (defun org-compute-property-at-point ()
14639 "Compute the property at point.
14640 This looks for an enclosing column format, extracts the operator and
14641 then applies it to the property in the column format's scope."
14642 (interactive)
14643 (unless (org-at-property-p)
14644 (error "Not at a property"))
14645 (let ((prop (org-match-string-no-properties 2)))
14646 (org-columns-get-format-and-top-level)
14647 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14648 (error "No operator defined for property %s" prop))
14649 (org-columns-compute prop)))
14651 (defvar org-property-allowed-value-functions nil
14652 "Hook for functions supplying allowed values for a specific property.
14653 The functions must take a single argument, the name of the property, and
14654 return a flat list of allowed values. If \":ETC\" is one of
14655 the values, this means that these values are intended as defaults for
14656 completion, but that other values should be allowed too.
14657 The functions must return nil if they are not responsible for this
14658 property.")
14660 (defun org-property-get-allowed-values (pom property &optional table)
14661 "Get allowed values for the property PROPERTY.
14662 When TABLE is non-nil, return an alist that can directly be used for
14663 completion."
14664 (let (vals)
14665 (cond
14666 ((equal property "TODO")
14667 (setq vals (org-with-point-at pom
14668 (append org-todo-keywords-1 '("")))))
14669 ((equal property "PRIORITY")
14670 (let ((n org-lowest-priority))
14671 (while (>= n org-highest-priority)
14672 (push (char-to-string n) vals)
14673 (setq n (1- n)))))
14674 ((member property org-special-properties))
14675 ((setq vals (run-hook-with-args-until-success
14676 'org-property-allowed-value-functions property)))
14678 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14679 (when (and vals (string-match "\\S-" vals))
14680 (setq vals (car (read-from-string (concat "(" vals ")"))))
14681 (setq vals (mapcar (lambda (x)
14682 (cond ((stringp x) x)
14683 ((numberp x) (number-to-string x))
14684 ((symbolp x) (symbol-name x))
14685 (t "???")))
14686 vals)))))
14687 (when (member ":ETC" vals)
14688 (setq vals (remove ":ETC" vals))
14689 (org-add-props (car vals) '(org-unrestricted t)))
14690 (if table (mapcar 'list vals) vals)))
14692 (defun org-property-previous-allowed-value (&optional previous)
14693 "Switch to the next allowed value for this property."
14694 (interactive)
14695 (org-property-next-allowed-value t))
14697 (defun org-property-next-allowed-value (&optional previous)
14698 "Switch to the next allowed value for this property."
14699 (interactive)
14700 (unless (org-at-property-p)
14701 (error "Not at a property"))
14702 (let* ((key (match-string 2))
14703 (value (match-string 3))
14704 (allowed (or (org-property-get-allowed-values (point) key)
14705 (and (member value '("[ ]" "[-]" "[X]"))
14706 '("[ ]" "[X]"))))
14707 nval)
14708 (unless allowed
14709 (error "Allowed values for this property have not been defined"))
14710 (if previous (setq allowed (reverse allowed)))
14711 (if (member value allowed)
14712 (setq nval (car (cdr (member value allowed)))))
14713 (setq nval (or nval (car allowed)))
14714 (if (equal nval value)
14715 (error "Only one allowed value for this property"))
14716 (org-at-property-p)
14717 (replace-match (concat " :" key ": " nval) t t)
14718 (org-indent-line-function)
14719 (beginning-of-line 1)
14720 (skip-chars-forward " \t")
14721 (run-hook-with-args 'org-property-changed-functions key nval)))
14723 (defun org-find-olp (path &optional this-buffer)
14724 "Return a marker pointing to the entry at outline path OLP.
14725 If anything goes wrong, throw an error.
14726 You can wrap this call to catch the error like this:
14728 (condition-case msg
14729 (org-mobile-locate-entry (match-string 4))
14730 (error (nth 1 msg)))
14732 The return value will then be either a string with the error message,
14733 or a marker if everything is OK.
14735 If THIS-BUFFER is set, the outline path does not contain a file,
14736 only headings."
14737 (let* ((file (if this-buffer buffer-file-name (pop path)))
14738 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14739 (level 1)
14740 (lmin 1)
14741 (lmax 1)
14742 limit re end found pos heading cnt flevel)
14743 (unless buffer (error "File not found :%s" file))
14744 (with-current-buffer buffer
14745 (save-excursion
14746 (save-restriction
14747 (widen)
14748 (setq limit (point-max))
14749 (goto-char (point-min))
14750 (while (setq heading (pop path))
14751 (setq re (format org-complex-heading-regexp-format
14752 (regexp-quote heading)))
14753 (setq cnt 0 pos (point))
14754 (while (re-search-forward re end t)
14755 (setq level (- (match-end 1) (match-beginning 1)))
14756 (if (and (>= level lmin) (<= level lmax))
14757 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14758 (when (= cnt 0) (error "Heading not found on level %d: %s"
14759 lmax heading))
14760 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14761 lmax heading))
14762 (goto-char found)
14763 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14764 (setq end (save-excursion (org-end-of-subtree t t))))
14765 (when (org-at-heading-p)
14766 (move-marker (make-marker) (point))))))))
14768 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14769 "Find node HEADING in BUFFER.
14770 Return a marker to the heading if it was found, or nil if not.
14771 If POS-ONLY is set, return just the position instead of a marker.
14773 The heading text must match exact, but it may have a TODO keyword,
14774 a priority cookie and tags in the standard locations."
14775 (with-current-buffer (or buffer (current-buffer))
14776 (save-excursion
14777 (save-restriction
14778 (widen)
14779 (goto-char (point-min))
14780 (let (case-fold-search)
14781 (if (re-search-forward
14782 (format org-complex-heading-regexp-format
14783 (regexp-quote heading)) nil t)
14784 (if pos-only
14785 (match-beginning 0)
14786 (move-marker (make-marker) (match-beginning 0)))))))))
14788 (defun org-find-exact-heading-in-directory (heading &optional dir)
14789 "Find Org node headline HEADING in all .org files in directory DIR.
14790 When the target headline is found, return a marker to this location."
14791 (let ((files (directory-files (or dir default-directory)
14792 nil "\\`[^.#].*\\.org\\'"))
14793 file visiting m buffer)
14794 (catch 'found
14795 (while (setq file (pop files))
14796 (message "trying %s" file)
14797 (setq visiting (org-find-base-buffer-visiting file))
14798 (setq buffer (or visiting (find-file-noselect file)))
14799 (setq m (org-find-exact-headline-in-buffer
14800 heading buffer))
14801 (when (and (not m) (not visiting)) (kill-buffer buffer))
14802 (and m (throw 'found m))))))
14804 (defun org-find-entry-with-id (ident)
14805 "Locate the entry that contains the ID property with exact value IDENT.
14806 IDENT can be a string, a symbol or a number, this function will search for
14807 the string representation of it.
14808 Return the position where this entry starts, or nil if there is no such entry."
14809 (interactive "sID: ")
14810 (let ((id (cond
14811 ((stringp ident) ident)
14812 ((symbol-name ident) (symbol-name ident))
14813 ((numberp ident) (number-to-string ident))
14814 (t (error "IDENT %s must be a string, symbol or number" ident))))
14815 (case-fold-search nil))
14816 (save-excursion
14817 (save-restriction
14818 (widen)
14819 (goto-char (point-min))
14820 (when (re-search-forward
14821 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14822 nil t)
14823 (org-back-to-heading t)
14824 (point))))))
14826 ;;;; Timestamps
14828 (defvar org-last-changed-timestamp nil)
14829 (defvar org-last-inserted-timestamp nil
14830 "The last time stamp inserted with `org-insert-time-stamp'.")
14831 (defvar org-time-was-given) ; dynamically scoped parameter
14832 (defvar org-end-time-was-given) ; dynamically scoped parameter
14833 (defvar org-ts-what) ; dynamically scoped parameter
14835 (defun org-time-stamp (arg &optional inactive)
14836 "Prompt for a date/time and insert a time stamp.
14837 If the user specifies a time like HH:MM, or if this command is called
14838 with a prefix argument, the time stamp will contain date and time.
14839 Otherwise, only the date will be included. All parts of a date not
14840 specified by the user will be filled in from the current date/time.
14841 So if you press just return without typing anything, the time stamp
14842 will represent the current date/time. If there is already a timestamp
14843 at the cursor, it will be modified."
14844 (interactive "P")
14845 (let* ((ts nil)
14846 (default-time
14847 ;; Default time is either today, or, when entering a range,
14848 ;; the range start.
14849 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14850 (save-excursion
14851 (re-search-backward
14852 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14853 (- (point) 20) t)))
14854 (apply 'encode-time (org-parse-time-string (match-string 1)))
14855 (current-time)))
14856 (default-input (and ts (org-get-compact-tod ts)))
14857 (repeater (save-excursion
14858 (save-match-data
14859 (beginning-of-line)
14860 (when (re-search-forward
14861 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14862 (save-excursion (progn (end-of-line) (point))) t)
14863 (match-string 0)))))
14864 org-time-was-given org-end-time-was-given time)
14865 (cond
14866 ((and (org-at-timestamp-p t)
14867 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14868 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14869 (insert "--")
14870 (setq time (let ((this-command this-command))
14871 (org-read-date arg 'totime nil nil
14872 default-time default-input)))
14873 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14874 ((org-at-timestamp-p t)
14875 (setq time (let ((this-command this-command))
14876 (org-read-date arg 'totime nil nil default-time default-input)))
14877 (when (org-at-timestamp-p t) ; just to get the match data
14878 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14879 (replace-match "")
14880 (setq org-last-changed-timestamp
14881 (org-insert-time-stamp
14882 time (or org-time-was-given arg)
14883 inactive nil nil (list org-end-time-was-given)))
14884 (when repeater (goto-char (1- (point))) (insert " " repeater)
14885 (setq org-last-changed-timestamp
14886 (concat (substring org-last-inserted-timestamp 0 -1)
14887 " " repeater ">"))))
14888 (message "Timestamp updated"))
14890 (setq time (let ((this-command this-command))
14891 (org-read-date arg 'totime nil nil default-time default-input)))
14892 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14893 nil nil (list org-end-time-was-given))))))
14895 ;; FIXME: can we use this for something else, like computing time differences?
14896 (defun org-get-compact-tod (s)
14897 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14898 (let* ((t1 (match-string 1 s))
14899 (h1 (string-to-number (match-string 2 s)))
14900 (m1 (string-to-number (match-string 3 s)))
14901 (t2 (and (match-end 4) (match-string 5 s)))
14902 (h2 (and t2 (string-to-number (match-string 6 s))))
14903 (m2 (and t2 (string-to-number (match-string 7 s))))
14904 dh dm)
14905 (if (not t2)
14907 (setq dh (- h2 h1) dm (- m2 m1))
14908 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14909 (concat t1 "+" (number-to-string dh)
14910 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14912 (defun org-time-stamp-inactive (&optional arg)
14913 "Insert an inactive time stamp.
14914 An inactive time stamp is enclosed in square brackets instead of angle
14915 brackets. It is inactive in the sense that it does not trigger agenda entries,
14916 does not link to the calendar and cannot be changed with the S-cursor keys.
14917 So these are more for recording a certain time/date."
14918 (interactive "P")
14919 (org-time-stamp arg 'inactive))
14921 (defvar org-date-ovl (make-overlay 1 1))
14922 (overlay-put org-date-ovl 'face 'org-warning)
14923 (org-detach-overlay org-date-ovl)
14925 (defvar org-ans1) ; dynamically scoped parameter
14926 (defvar org-ans2) ; dynamically scoped parameter
14928 (defvar org-plain-time-of-day-regexp) ; defined below
14930 (defvar org-overriding-default-time nil) ; dynamically scoped
14931 (defvar org-read-date-overlay nil)
14932 (defvar org-dcst nil) ; dynamically scoped
14933 (defvar org-read-date-history nil)
14934 (defvar org-read-date-final-answer nil)
14935 (defvar org-read-date-analyze-futurep nil)
14936 (defvar org-read-date-analyze-forced-year nil)
14938 (defun org-read-date (&optional org-with-time to-time from-string prompt
14939 default-time default-input)
14940 "Read a date, possibly a time, and make things smooth for the user.
14941 The prompt will suggest to enter an ISO date, but you can also enter anything
14942 which will at least partially be understood by `parse-time-string'.
14943 Unrecognized parts of the date will default to the current day, month, year,
14944 hour and minute. If this command is called to replace a timestamp at point,
14945 or to enter the second timestamp of a range, the default time is taken
14946 from the existing stamp. Furthermore, the command prefers the future,
14947 so if you are giving a date where the year is not given, and the day-month
14948 combination is already past in the current year, it will assume you
14949 mean next year. For details, see the manual. A few examples:
14951 3-2-5 --> 2003-02-05
14952 feb 15 --> currentyear-02-15
14953 2/15 --> currentyear-02-15
14954 sep 12 9 --> 2009-09-12
14955 12:45 --> today 12:45
14956 22 sept 0:34 --> currentyear-09-22 0:34
14957 12 --> currentyear-currentmonth-12
14958 Fri --> nearest Friday (today or later)
14959 etc.
14961 Furthermore you can specify a relative date by giving, as the *first* thing
14962 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14963 change in days weeks, months, years.
14964 With a single plus or minus, the date is relative to today. With a double
14965 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14966 +4d --> four days from today
14967 +4 --> same as above
14968 +2w --> two weeks from today
14969 ++5 --> five days from default date
14971 The function understands only English month and weekday abbreviations.
14973 While prompting, a calendar is popped up - you can also select the
14974 date with the mouse (button 1). The calendar shows a period of three
14975 months. To scroll it to other months, use the keys `>' and `<'.
14976 If you don't like the calendar, turn it off with
14977 \(setq org-read-date-popup-calendar nil)
14979 With optional argument TO-TIME, the date will immediately be converted
14980 to an internal time.
14981 With an optional argument WITH-TIME, the prompt will suggest to also
14982 insert a time. Note that when WITH-TIME is not set, you can still
14983 enter a time, and this function will inform the calling routine about
14984 this change. The calling routine may then choose to change the format
14985 used to insert the time stamp into the buffer to include the time.
14986 With optional argument FROM-STRING, read from this string instead from
14987 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14988 the time/date that is used for everything that is not specified by the
14989 user."
14990 (require 'parse-time)
14991 (let* ((org-time-stamp-rounding-minutes
14992 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14993 (org-dcst org-display-custom-times)
14994 (ct (org-current-time))
14995 (org-def (or org-overriding-default-time default-time ct))
14996 (org-defdecode (decode-time org-def))
14997 (dummy (progn
14998 (when (< (nth 2 org-defdecode) org-extend-today-until)
14999 (setcar (nthcdr 2 org-defdecode) -1)
15000 (setcar (nthcdr 1 org-defdecode) 59)
15001 (setq org-def (apply 'encode-time org-defdecode)
15002 org-defdecode (decode-time org-def)))))
15003 (calendar-frame-setup nil)
15004 (calendar-setup nil)
15005 (calendar-move-hook nil)
15006 (calendar-view-diary-initially-flag nil)
15007 (calendar-view-holidays-initially-flag nil)
15008 (timestr (format-time-string
15009 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15010 (prompt (concat (if prompt (concat prompt " ") "")
15011 (format "Date+time [%s]: " timestr)))
15012 ans (org-ans0 "") org-ans1 org-ans2 final)
15014 (cond
15015 (from-string (setq ans from-string))
15016 (org-read-date-popup-calendar
15017 (save-excursion
15018 (save-window-excursion
15019 (calendar)
15020 (unwind-protect
15021 (progn
15022 (calendar-forward-day (- (time-to-days org-def)
15023 (calendar-absolute-from-gregorian
15024 (calendar-current-date))))
15025 (org-eval-in-calendar nil t)
15026 (let* ((old-map (current-local-map))
15027 (map (copy-keymap calendar-mode-map))
15028 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15029 (org-defkey map (kbd "RET") 'org-calendar-select)
15030 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15031 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15032 (org-defkey minibuffer-local-map [(meta shift left)]
15033 (lambda () (interactive)
15034 (org-eval-in-calendar '(calendar-backward-month 1))))
15035 (org-defkey minibuffer-local-map [(meta shift right)]
15036 (lambda () (interactive)
15037 (org-eval-in-calendar '(calendar-forward-month 1))))
15038 (org-defkey minibuffer-local-map [(meta shift up)]
15039 (lambda () (interactive)
15040 (org-eval-in-calendar '(calendar-backward-year 1))))
15041 (org-defkey minibuffer-local-map [(meta shift down)]
15042 (lambda () (interactive)
15043 (org-eval-in-calendar '(calendar-forward-year 1))))
15044 (org-defkey minibuffer-local-map [?\e (shift left)]
15045 (lambda () (interactive)
15046 (org-eval-in-calendar '(calendar-backward-month 1))))
15047 (org-defkey minibuffer-local-map [?\e (shift right)]
15048 (lambda () (interactive)
15049 (org-eval-in-calendar '(calendar-forward-month 1))))
15050 (org-defkey minibuffer-local-map [?\e (shift up)]
15051 (lambda () (interactive)
15052 (org-eval-in-calendar '(calendar-backward-year 1))))
15053 (org-defkey minibuffer-local-map [?\e (shift down)]
15054 (lambda () (interactive)
15055 (org-eval-in-calendar '(calendar-forward-year 1))))
15056 (org-defkey minibuffer-local-map [(shift up)]
15057 (lambda () (interactive)
15058 (org-eval-in-calendar '(calendar-backward-week 1))))
15059 (org-defkey minibuffer-local-map [(shift down)]
15060 (lambda () (interactive)
15061 (org-eval-in-calendar '(calendar-forward-week 1))))
15062 (org-defkey minibuffer-local-map [(shift left)]
15063 (lambda () (interactive)
15064 (org-eval-in-calendar '(calendar-backward-day 1))))
15065 (org-defkey minibuffer-local-map [(shift right)]
15066 (lambda () (interactive)
15067 (org-eval-in-calendar '(calendar-forward-day 1))))
15068 (org-defkey minibuffer-local-map ">"
15069 (lambda () (interactive)
15070 (org-eval-in-calendar '(scroll-calendar-left 1))))
15071 (org-defkey minibuffer-local-map "<"
15072 (lambda () (interactive)
15073 (org-eval-in-calendar '(scroll-calendar-right 1))))
15074 (org-defkey minibuffer-local-map "\C-v"
15075 (lambda () (interactive)
15076 (org-eval-in-calendar
15077 '(calendar-scroll-left-three-months 1))))
15078 (org-defkey minibuffer-local-map "\M-v"
15079 (lambda () (interactive)
15080 (org-eval-in-calendar
15081 '(calendar-scroll-right-three-months 1))))
15082 (run-hooks 'org-read-date-minibuffer-setup-hook)
15083 (unwind-protect
15084 (progn
15085 (use-local-map map)
15086 (add-hook 'post-command-hook 'org-read-date-display)
15087 (setq org-ans0 (read-string prompt default-input
15088 'org-read-date-history nil))
15089 ;; org-ans0: from prompt
15090 ;; org-ans1: from mouse click
15091 ;; org-ans2: from calendar motion
15092 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15093 (remove-hook 'post-command-hook 'org-read-date-display)
15094 (use-local-map old-map)
15095 (when org-read-date-overlay
15096 (delete-overlay org-read-date-overlay)
15097 (setq org-read-date-overlay nil)))))
15098 (bury-buffer "*Calendar*")))))
15100 (t ; Naked prompt only
15101 (unwind-protect
15102 (setq ans (read-string prompt default-input
15103 'org-read-date-history timestr))
15104 (when org-read-date-overlay
15105 (delete-overlay org-read-date-overlay)
15106 (setq org-read-date-overlay nil)))))
15108 (setq final (org-read-date-analyze ans org-def org-defdecode))
15110 (when org-read-date-analyze-forced-year
15111 (message "Year was forced into %s"
15112 (if org-read-date-force-compatible-dates
15113 "compatible range (1970-2037)"
15114 "range representable on this machine"))
15115 (ding))
15117 ;; One round trip to get rid of 34th of August and stuff like that....
15118 (setq final (decode-time (apply 'encode-time final)))
15120 (setq org-read-date-final-answer ans)
15122 (if to-time
15123 (apply 'encode-time final)
15124 (if (and (boundp 'org-time-was-given) org-time-was-given)
15125 (format "%04d-%02d-%02d %02d:%02d"
15126 (nth 5 final) (nth 4 final) (nth 3 final)
15127 (nth 2 final) (nth 1 final))
15128 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15130 (defvar org-def)
15131 (defvar org-defdecode)
15132 (defvar org-with-time)
15133 (defun org-read-date-display ()
15134 "Display the current date prompt interpretation in the minibuffer."
15135 (when org-read-date-display-live
15136 (when org-read-date-overlay
15137 (delete-overlay org-read-date-overlay))
15138 (let ((p (point)))
15139 (end-of-line 1)
15140 (while (not (equal (buffer-substring
15141 (max (point-min) (- (point) 4)) (point))
15142 " "))
15143 (insert " "))
15144 (goto-char p))
15145 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15146 " " (or org-ans1 org-ans2)))
15147 (org-end-time-was-given nil)
15148 (f (org-read-date-analyze ans org-def org-defdecode))
15149 (fmts (if org-dcst
15150 org-time-stamp-custom-formats
15151 org-time-stamp-formats))
15152 (fmt (if (or org-with-time
15153 (and (boundp 'org-time-was-given) org-time-was-given))
15154 (cdr fmts)
15155 (car fmts)))
15156 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15157 (when (and org-end-time-was-given
15158 (string-match org-plain-time-of-day-regexp txt))
15159 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15160 org-end-time-was-given
15161 (substring txt (match-end 0)))))
15162 (when org-read-date-analyze-futurep
15163 (setq txt (concat txt " (=>F)")))
15164 (setq org-read-date-overlay
15165 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15166 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15168 (defun org-read-date-analyze (ans org-def org-defdecode)
15169 "Analyze the combined answer of the date prompt."
15170 ;; FIXME: cleanup and comment
15171 (let ((nowdecode (decode-time (current-time)))
15172 delta deltan deltaw deltadef year month day
15173 hour minute second wday pm h2 m2 tl wday1
15174 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15175 (setq org-read-date-analyze-futurep nil
15176 org-read-date-analyze-forced-year nil)
15177 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15178 (setq ans "+0"))
15180 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15181 (setq ans (replace-match "" t t ans)
15182 deltan (car delta)
15183 deltaw (nth 1 delta)
15184 deltadef (nth 2 delta)))
15186 ;; Check if there is an iso week date in there
15187 ;; If yes, store the info and postpone interpreting it until the rest
15188 ;; of the parsing is done
15189 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15190 (setq iso-year (if (match-end 1)
15191 (org-small-year-to-year
15192 (string-to-number (match-string 1 ans))))
15193 iso-weekday (if (match-end 3)
15194 (string-to-number (match-string 3 ans)))
15195 iso-week (string-to-number (match-string 2 ans)))
15196 (setq ans (replace-match "" t t ans)))
15198 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15199 (when (string-match
15200 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15201 (setq year (if (match-end 2)
15202 (string-to-number (match-string 2 ans))
15203 (progn (setq kill-year t)
15204 (string-to-number (format-time-string "%Y"))))
15205 month (string-to-number (match-string 3 ans))
15206 day (string-to-number (match-string 4 ans)))
15207 (if (< year 100) (setq year (+ 2000 year)))
15208 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15209 t nil ans)))
15211 ;; Help matching dotted european dates
15212 (when (string-match
15213 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15214 (setq year (if (match-end 3)
15215 (string-to-number (match-string 3 ans))
15216 (progn (setq kill-year t)
15217 (string-to-number (format-time-string "%Y"))))
15218 day (string-to-number (match-string 1 ans))
15219 month (string-to-number (match-string 2 ans))
15220 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15221 t nil ans)))
15223 ;; Help matching american dates, like 5/30 or 5/30/7
15224 (when (string-match
15225 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15226 (setq year (if (match-end 4)
15227 (string-to-number (match-string 4 ans))
15228 (progn (setq kill-year t)
15229 (string-to-number (format-time-string "%Y"))))
15230 month (string-to-number (match-string 1 ans))
15231 day (string-to-number (match-string 2 ans)))
15232 (if (< year 100) (setq year (+ 2000 year)))
15233 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15234 t nil ans)))
15235 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15236 ;; If there is a time with am/pm, and *no* time without it, we convert
15237 ;; so that matching will be successful.
15238 (loop for i from 1 to 2 do ; twice, for end time as well
15239 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15240 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15241 (setq hour (string-to-number (match-string 1 ans))
15242 minute (if (match-end 3)
15243 (string-to-number (match-string 3 ans))
15245 pm (equal ?p
15246 (string-to-char (downcase (match-string 4 ans)))))
15247 (if (and (= hour 12) (not pm))
15248 (setq hour 0)
15249 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15250 (setq ans (replace-match (format "%02d:%02d" hour minute)
15251 t t ans))))
15253 ;; Check if a time range is given as a duration
15254 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15255 (setq hour (string-to-number (match-string 1 ans))
15256 h2 (+ hour (string-to-number (match-string 3 ans)))
15257 minute (string-to-number (match-string 2 ans))
15258 m2 (+ minute (if (match-end 5) (string-to-number
15259 (match-string 5 ans))0)))
15260 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15261 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15262 t t ans)))
15264 ;; Check if there is a time range
15265 (when (boundp 'org-end-time-was-given)
15266 (setq org-time-was-given nil)
15267 (when (and (string-match org-plain-time-of-day-regexp ans)
15268 (match-end 8))
15269 (setq org-end-time-was-given (match-string 8 ans))
15270 (setq ans (concat (substring ans 0 (match-beginning 7))
15271 (substring ans (match-end 7))))))
15273 (setq tl (parse-time-string ans)
15274 day (or (nth 3 tl) (nth 3 org-defdecode))
15275 month (or (nth 4 tl)
15276 (if (and org-read-date-prefer-future
15277 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15278 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15279 (nth 4 org-defdecode)))
15280 year (or (and (not kill-year) (nth 5 tl))
15281 (if (and org-read-date-prefer-future
15282 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15283 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15284 (nth 5 org-defdecode)))
15285 hour (or (nth 2 tl) (nth 2 org-defdecode))
15286 minute (or (nth 1 tl) (nth 1 org-defdecode))
15287 second (or (nth 0 tl) 0)
15288 wday (nth 6 tl))
15290 (when (and (eq org-read-date-prefer-future 'time)
15291 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15292 (equal day (nth 3 nowdecode))
15293 (equal month (nth 4 nowdecode))
15294 (equal year (nth 5 nowdecode))
15295 (nth 2 tl)
15296 (or (< (nth 2 tl) (nth 2 nowdecode))
15297 (and (= (nth 2 tl) (nth 2 nowdecode))
15298 (nth 1 tl)
15299 (< (nth 1 tl) (nth 1 nowdecode)))))
15300 (setq day (1+ day)
15301 futurep t))
15303 ;; Special date definitions below
15304 (cond
15305 (iso-week
15306 ;; There was an iso week
15307 (require 'cal-iso)
15308 (setq futurep nil)
15309 (setq year (or iso-year year)
15310 day (or iso-weekday wday 1)
15311 wday nil ; to make sure that the trigger below does not match
15312 iso-date (calendar-gregorian-from-absolute
15313 (calendar-absolute-from-iso
15314 (list iso-week day year))))
15315 ; FIXME: Should we also push ISO weeks into the future?
15316 ; (when (and org-read-date-prefer-future
15317 ; (not iso-year)
15318 ; (< (calendar-absolute-from-gregorian iso-date)
15319 ; (time-to-days (current-time))))
15320 ; (setq year (1+ year)
15321 ; iso-date (calendar-gregorian-from-absolute
15322 ; (calendar-absolute-from-iso
15323 ; (list iso-week day year)))))
15324 (setq month (car iso-date)
15325 year (nth 2 iso-date)
15326 day (nth 1 iso-date)))
15327 (deltan
15328 (setq futurep nil)
15329 (unless deltadef
15330 (let ((now (decode-time (current-time))))
15331 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15332 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15333 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15334 ((equal deltaw "m") (setq month (+ month deltan)))
15335 ((equal deltaw "y") (setq year (+ year deltan)))))
15336 ((and wday (not (nth 3 tl)))
15337 (setq futurep nil)
15338 ;; Weekday was given, but no day, so pick that day in the week
15339 ;; on or after the derived date.
15340 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15341 (unless (equal wday wday1)
15342 (setq day (+ day (% (- wday wday1 -7) 7))))))
15343 (if (and (boundp 'org-time-was-given)
15344 (nth 2 tl))
15345 (setq org-time-was-given t))
15346 (if (< year 100) (setq year (+ 2000 year)))
15347 ;; Check of the date is representable
15348 (if org-read-date-force-compatible-dates
15349 (progn
15350 (if (< year 1970)
15351 (setq year 1970 org-read-date-analyze-forced-year t))
15352 (if (> year 2037)
15353 (setq year 2037 org-read-date-analyze-forced-year t)))
15354 (condition-case nil
15355 (ignore (encode-time second minute hour day month year))
15356 (error
15357 (setq year (nth 5 org-defdecode))
15358 (setq org-read-date-analyze-forced-year t))))
15359 (setq org-read-date-analyze-futurep futurep)
15360 (list second minute hour day month year)))
15362 (defvar parse-time-weekdays)
15363 (defun org-read-date-get-relative (s today default)
15364 "Check string S for special relative date string.
15365 TODAY and DEFAULT are internal times, for today and for a default.
15366 Return shift list (N what def-flag)
15367 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15368 N is the number of WHATs to shift.
15369 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15370 the DEFAULT date rather than TODAY."
15371 (require 'parse-time)
15372 (when (and
15373 (string-match
15374 (concat
15375 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15376 "\\([0-9]+\\)?"
15377 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15378 "\\([ \t]\\|$\\)") s)
15379 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15380 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15381 (string-to-char (substring (match-string 1 s) -1))
15382 ?+))
15383 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15384 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15385 (what (if (match-end 3) (match-string 3 s) "d"))
15386 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15387 (date (if rel default today))
15388 (wday (nth 6 (decode-time date)))
15389 delta)
15390 (if wday1
15391 (progn
15392 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15393 (if (= dir ?-) (setq delta (- delta 7)))
15394 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15395 (list delta "d" rel))
15396 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15398 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15399 "Turn a user-specified date into the internal representation.
15400 The internal representation needed by the calendar is (month day year).
15401 This is a wrapper to handle the brain-dead convention in calendar that
15402 user function argument order change dependent on argument order."
15403 (if (boundp 'calendar-date-style)
15404 (cond
15405 ((eq calendar-date-style 'american)
15406 (list arg1 arg2 arg3))
15407 ((eq calendar-date-style 'european)
15408 (list arg2 arg1 arg3))
15409 ((eq calendar-date-style 'iso)
15410 (list arg2 arg3 arg1)))
15411 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15412 (if (org-bound-and-true-p european-calendar-style)
15413 (list arg2 arg1 arg3)
15414 (list arg1 arg2 arg3)))))
15416 (defun org-eval-in-calendar (form &optional keepdate)
15417 "Eval FORM in the calendar window and return to current window.
15418 Also, store the cursor date in variable org-ans2."
15419 (let ((sf (selected-frame))
15420 (sw (selected-window)))
15421 (select-window (get-buffer-window "*Calendar*" t))
15422 (eval form)
15423 (when (and (not keepdate) (calendar-cursor-to-date))
15424 (let* ((date (calendar-cursor-to-date))
15425 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15426 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15427 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15428 (select-window sw)
15429 (org-select-frame-set-input-focus sf)))
15431 (defun org-calendar-select ()
15432 "Return to `org-read-date' with the date currently selected.
15433 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15434 (interactive)
15435 (when (calendar-cursor-to-date)
15436 (let* ((date (calendar-cursor-to-date))
15437 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15438 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15439 (if (active-minibuffer-window) (exit-minibuffer))))
15441 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15442 "Insert a date stamp for the date given by the internal TIME.
15443 WITH-HM means use the stamp format that includes the time of the day.
15444 INACTIVE means use square brackets instead of angular ones, so that the
15445 stamp will not contribute to the agenda.
15446 PRE and POST are optional strings to be inserted before and after the
15447 stamp.
15448 The command returns the inserted time stamp."
15449 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15450 stamp)
15451 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15452 (insert-before-markers (or pre ""))
15453 (when (listp extra)
15454 (setq extra (car extra))
15455 (if (and (stringp extra)
15456 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15457 (setq extra (format "-%02d:%02d"
15458 (string-to-number (match-string 1 extra))
15459 (string-to-number (match-string 2 extra))))
15460 (setq extra nil)))
15461 (when extra
15462 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15463 (insert-before-markers (setq stamp (format-time-string fmt time)))
15464 (insert-before-markers (or post ""))
15465 (setq org-last-inserted-timestamp stamp)))
15467 (defun org-toggle-time-stamp-overlays ()
15468 "Toggle the use of custom time stamp formats."
15469 (interactive)
15470 (setq org-display-custom-times (not org-display-custom-times))
15471 (unless org-display-custom-times
15472 (let ((p (point-min)) (bmp (buffer-modified-p)))
15473 (while (setq p (next-single-property-change p 'display))
15474 (if (and (get-text-property p 'display)
15475 (eq (get-text-property p 'face) 'org-date))
15476 (remove-text-properties
15477 p (setq p (next-single-property-change p 'display))
15478 '(display t))))
15479 (set-buffer-modified-p bmp)))
15480 (if (featurep 'xemacs)
15481 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15482 (org-restart-font-lock)
15483 (setq org-table-may-need-update t)
15484 (if org-display-custom-times
15485 (message "Time stamps are overlaid with custom format")
15486 (message "Time stamp overlays removed")))
15488 (defun org-display-custom-time (beg end)
15489 "Overlay modified time stamp format over timestamp between BEG and END."
15490 (let* ((ts (buffer-substring beg end))
15491 t1 w1 with-hm tf time str w2 (off 0))
15492 (save-match-data
15493 (setq t1 (org-parse-time-string ts t))
15494 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15495 (setq off (- (match-end 0) (match-beginning 0)))))
15496 (setq end (- end off))
15497 (setq w1 (- end beg)
15498 with-hm (and (nth 1 t1) (nth 2 t1))
15499 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15500 time (org-fix-decoded-time t1)
15501 str (org-add-props
15502 (format-time-string
15503 (substring tf 1 -1) (apply 'encode-time time))
15504 nil 'mouse-face 'highlight)
15505 w2 (length str))
15506 (if (not (= w2 w1))
15507 (add-text-properties (1+ beg) (+ 2 beg)
15508 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15509 (if (featurep 'xemacs)
15510 (progn
15511 (put-text-property beg end 'invisible t)
15512 (put-text-property beg end 'end-glyph (make-glyph str)))
15513 (put-text-property beg end 'display str))))
15515 (defun org-translate-time (string)
15516 "Translate all timestamps in STRING to custom format.
15517 But do this only if the variable `org-display-custom-times' is set."
15518 (when org-display-custom-times
15519 (save-match-data
15520 (let* ((start 0)
15521 (re org-ts-regexp-both)
15522 t1 with-hm inactive tf time str beg end)
15523 (while (setq start (string-match re string start))
15524 (setq beg (match-beginning 0)
15525 end (match-end 0)
15526 t1 (save-match-data
15527 (org-parse-time-string (substring string beg end) t))
15528 with-hm (and (nth 1 t1) (nth 2 t1))
15529 inactive (equal (substring string beg (1+ beg)) "[")
15530 tf (funcall (if with-hm 'cdr 'car)
15531 org-time-stamp-custom-formats)
15532 time (org-fix-decoded-time t1)
15533 str (format-time-string
15534 (concat
15535 (if inactive "[" "<") (substring tf 1 -1)
15536 (if inactive "]" ">"))
15537 (apply 'encode-time time))
15538 string (replace-match str t t string)
15539 start (+ start (length str)))))))
15540 string)
15542 (defun org-fix-decoded-time (time)
15543 "Set 0 instead of nil for the first 6 elements of time.
15544 Don't touch the rest."
15545 (let ((n 0))
15546 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15548 (defun org-days-to-time (timestamp-string)
15549 "Difference between TIMESTAMP-STRING and now in days."
15550 (- (time-to-days (org-time-string-to-time timestamp-string))
15551 (time-to-days (current-time))))
15553 (defun org-deadline-close (timestamp-string &optional ndays)
15554 "Is the time in TIMESTAMP-STRING close to the current date?"
15555 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15556 (and (< (org-days-to-time timestamp-string) ndays)
15557 (not (org-entry-is-done-p))))
15559 (defun org-get-wdays (ts)
15560 "Get the deadline lead time appropriate for timestring TS."
15561 (cond
15562 ((<= org-deadline-warning-days 0)
15563 ;; 0 or negative, enforce this value no matter what
15564 (- org-deadline-warning-days))
15565 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15566 ;; lead time is specified.
15567 (floor (* (string-to-number (match-string 1 ts))
15568 (cdr (assoc (match-string 2 ts)
15569 '(("d" . 1) ("w" . 7)
15570 ("m" . 30.4) ("y" . 365.25)))))))
15571 ;; go for the default.
15572 (t org-deadline-warning-days)))
15574 (defun org-calendar-select-mouse (ev)
15575 "Return to `org-read-date' with the date currently selected.
15576 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15577 (interactive "e")
15578 (mouse-set-point ev)
15579 (when (calendar-cursor-to-date)
15580 (let* ((date (calendar-cursor-to-date))
15581 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15582 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15583 (if (active-minibuffer-window) (exit-minibuffer))))
15585 (defun org-check-deadlines (ndays)
15586 "Check if there are any deadlines due or past due.
15587 A deadline is considered due if it happens within `org-deadline-warning-days'
15588 days from today's date. If the deadline appears in an entry marked DONE,
15589 it is not shown. The prefix arg NDAYS can be used to test that many
15590 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15591 (interactive "P")
15592 (let* ((org-warn-days
15593 (cond
15594 ((equal ndays '(4)) 100000)
15595 (ndays (prefix-numeric-value ndays))
15596 (t (abs org-deadline-warning-days))))
15597 (case-fold-search nil)
15598 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15599 (callback
15600 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15602 (message "%d deadlines past-due or due within %d days"
15603 (org-occur regexp nil callback)
15604 org-warn-days)))
15606 (defun org-check-before-date (date)
15607 "Check if there are deadlines or scheduled entries before DATE."
15608 (interactive (list (org-read-date)))
15609 (let ((case-fold-search nil)
15610 (regexp (concat "\\<\\(" org-deadline-string
15611 "\\|" org-scheduled-string
15612 "\\) *<\\([^>]+\\)>"))
15613 (callback
15614 (lambda () (time-less-p
15615 (org-time-string-to-time (match-string 2))
15616 (org-time-string-to-time date)))))
15617 (message "%d entries before %s"
15618 (org-occur regexp nil callback) date)))
15620 (defun org-check-after-date (date)
15621 "Check if there are deadlines or scheduled entries after DATE."
15622 (interactive (list (org-read-date)))
15623 (let ((case-fold-search nil)
15624 (regexp (concat "\\<\\(" org-deadline-string
15625 "\\|" org-scheduled-string
15626 "\\) *<\\([^>]+\\)>"))
15627 (callback
15628 (lambda () (not
15629 (time-less-p
15630 (org-time-string-to-time (match-string 2))
15631 (org-time-string-to-time date))))))
15632 (message "%d entries after %s"
15633 (org-occur regexp nil callback) date)))
15635 (defun org-check-dates-range (start-date end-date)
15636 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15637 (interactive (list (org-read-date nil nil nil "Range starts")
15638 (org-read-date nil nil nil "Range end")))
15639 (let ((case-fold-search nil)
15640 (regexp (concat "\\<\\(" org-deadline-string
15641 "\\|" org-scheduled-string
15642 "\\) *<\\([^>]+\\)>"))
15643 (callback
15644 (lambda ()
15645 (let ((match (match-string 2)))
15646 (and
15647 (not (time-less-p
15648 (org-time-string-to-time match)
15649 (org-time-string-to-time start-date)))
15650 (time-less-p
15651 (org-time-string-to-time match)
15652 (org-time-string-to-time end-date)))))))
15653 (message "%d entries between %s and %s"
15654 (org-occur regexp nil callback) start-date end-date)))
15656 (defun org-evaluate-time-range (&optional to-buffer)
15657 "Evaluate a time range by computing the difference between start and end.
15658 Normally the result is just printed in the echo area, but with prefix arg
15659 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15660 If the time range is actually in a table, the result is inserted into the
15661 next column.
15662 For time difference computation, a year is assumed to be exactly 365
15663 days in order to avoid rounding problems."
15664 (interactive "P")
15666 (org-clock-update-time-maybe)
15667 (save-excursion
15668 (unless (org-at-date-range-p t)
15669 (goto-char (point-at-bol))
15670 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15671 (if (not (org-at-date-range-p t))
15672 (error "Not at a time-stamp range, and none found in current line")))
15673 (let* ((ts1 (match-string 1))
15674 (ts2 (match-string 2))
15675 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15676 (match-end (match-end 0))
15677 (time1 (org-time-string-to-time ts1))
15678 (time2 (org-time-string-to-time ts2))
15679 (t1 (org-float-time time1))
15680 (t2 (org-float-time time2))
15681 (diff (abs (- t2 t1)))
15682 (negative (< (- t2 t1) 0))
15683 ;; (ys (floor (* 365 24 60 60)))
15684 (ds (* 24 60 60))
15685 (hs (* 60 60))
15686 (fy "%dy %dd %02d:%02d")
15687 (fy1 "%dy %dd")
15688 (fd "%dd %02d:%02d")
15689 (fd1 "%dd")
15690 (fh "%02d:%02d")
15691 y d h m align)
15692 (if havetime
15693 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15695 d (floor (/ diff ds)) diff (mod diff ds)
15696 h (floor (/ diff hs)) diff (mod diff hs)
15697 m (floor (/ diff 60)))
15698 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15700 d (floor (+ (/ diff ds) 0.5))
15701 h 0 m 0))
15702 (if (not to-buffer)
15703 (message "%s" (org-make-tdiff-string y d h m))
15704 (if (org-at-table-p)
15705 (progn
15706 (goto-char match-end)
15707 (setq align t)
15708 (and (looking-at " *|") (goto-char (match-end 0))))
15709 (goto-char match-end))
15710 (if (looking-at
15711 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15712 (replace-match ""))
15713 (if negative (insert " -"))
15714 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15715 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15716 (insert " " (format fh h m))))
15717 (if align (org-table-align))
15718 (message "Time difference inserted")))))
15720 (defun org-make-tdiff-string (y d h m)
15721 (let ((fmt "")
15722 (l nil))
15723 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15724 l (push y l)))
15725 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15726 l (push d l)))
15727 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15728 l (push h l)))
15729 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15730 l (push m l)))
15731 (apply 'format fmt (nreverse l))))
15733 (defun org-time-string-to-time (s &optional buffer pos)
15734 (condition-case errdata
15735 (apply 'encode-time (org-parse-time-string s))
15736 (error (error "Bad timestamp `%s'%s\nError was: %s"
15737 s (if (not (and buffer pos))
15739 (format " at %d in buffer `%s'" pos buffer))
15740 (cdr errdata)))))
15742 (defun org-time-string-to-seconds (s)
15743 (org-float-time (org-time-string-to-time s)))
15745 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15746 "Convert a time stamp to an absolute day number.
15747 If there is a specifier for a cyclic time stamp, get the closest date to
15748 DAYNR.
15749 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15750 The variable date is bound by the calendar when this is called."
15751 (cond
15752 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15753 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15754 daynr
15755 (+ daynr 1000)))
15756 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15757 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15758 (time-to-days (current-time))) (match-string 0 s)
15759 prefer show-all))
15760 (t (time-to-days
15761 (condition-case errdata
15762 (apply 'encode-time (org-parse-time-string s))
15763 (error (error "Bad timestamp `%s'%s\nError was: %s"
15764 s (if (not (and buffer pos))
15766 (format " at %d in buffer `%s'" pos buffer))
15767 (cdr errdata))))))))
15769 (defun org-days-to-iso-week (days)
15770 "Return the iso week number."
15771 (require 'cal-iso)
15772 (car (calendar-iso-from-absolute days)))
15774 (defun org-small-year-to-year (year)
15775 "Convert 2-digit years into 4-digit years.
15776 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15777 The year 2000 cannot be abbreviated. Any year larger than 99
15778 is returned unchanged."
15779 (if (< year 38)
15780 (setq year (+ 2000 year))
15781 (if (< year 100)
15782 (setq year (+ 1900 year))))
15783 year)
15785 (defun org-time-from-absolute (d)
15786 "Return the time corresponding to date D.
15787 D may be an absolute day number, or a calendar-type list (month day year)."
15788 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15789 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15791 (defun org-calendar-holiday ()
15792 "List of holidays, for Diary display in Org-mode."
15793 (require 'holidays)
15794 (let ((hl (funcall
15795 (if (fboundp 'calendar-check-holidays)
15796 'calendar-check-holidays 'check-calendar-holidays) date)))
15797 (if hl (mapconcat 'identity hl "; "))))
15799 (defun org-diary-sexp-entry (sexp entry date)
15800 "Process a SEXP diary ENTRY for DATE."
15801 (require 'diary-lib)
15802 (let ((result (if calendar-debug-sexp
15803 (let ((stack-trace-on-error t))
15804 (eval (car (read-from-string sexp))))
15805 (condition-case nil
15806 (eval (car (read-from-string sexp)))
15807 (error
15808 (beep)
15809 (message "Bad sexp at line %d in %s: %s"
15810 (org-current-line)
15811 (buffer-file-name) sexp)
15812 (sleep-for 2))))))
15813 (cond ((stringp result) (split-string result "; "))
15814 ((and (consp result)
15815 (not (consp (cdr result)))
15816 (stringp (cdr result))) (cdr result))
15817 ((and (consp result)
15818 (stringp (car result))) result)
15819 (result entry)
15820 (t nil))))
15822 (defun org-diary-to-ical-string (frombuf)
15823 "Get iCalendar entries from diary entries in buffer FROMBUF.
15824 This uses the icalendar.el library."
15825 (let* ((tmpdir (if (featurep 'xemacs)
15826 (temp-directory)
15827 temporary-file-directory))
15828 (tmpfile (make-temp-name
15829 (expand-file-name "orgics" tmpdir)))
15830 buf rtn b e)
15831 (with-current-buffer frombuf
15832 (icalendar-export-region (point-min) (point-max) tmpfile)
15833 (setq buf (find-buffer-visiting tmpfile))
15834 (set-buffer buf)
15835 (goto-char (point-min))
15836 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15837 (setq b (match-beginning 0)))
15838 (goto-char (point-max))
15839 (if (re-search-backward "^END:VEVENT" nil t)
15840 (setq e (match-end 0)))
15841 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15842 (kill-buffer buf)
15843 (delete-file tmpfile)
15844 rtn))
15846 (defun org-closest-date (start current change prefer show-all)
15847 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15848 When PREFER is `past', return a date that is either CURRENT or past.
15849 When PREFER is `future', return a date that is either CURRENT or future.
15850 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15851 ;; Make the proper lists from the dates
15852 (catch 'exit
15853 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15854 dn dw sday cday n1 n2 n0
15855 d m y y1 y2 date1 date2 nmonths nm ny m2)
15857 (setq start (org-date-to-gregorian start)
15858 current (org-date-to-gregorian
15859 (if show-all
15860 current
15861 (time-to-days (current-time))))
15862 sday (calendar-absolute-from-gregorian start)
15863 cday (calendar-absolute-from-gregorian current))
15865 (if (<= cday sday) (throw 'exit sday))
15867 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15868 (setq dn (string-to-number (match-string 1 change))
15869 dw (cdr (assoc (match-string 2 change) a1)))
15870 (error "Invalid change specifier: %s" change))
15871 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15872 (cond
15873 ((eq dw 'day)
15874 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15875 n2 (+ n1 dn)))
15876 ((eq dw 'year)
15877 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15878 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15879 (setq date1 (list m d y1)
15880 n1 (calendar-absolute-from-gregorian date1)
15881 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15882 n2 (calendar-absolute-from-gregorian date2)))
15883 ((eq dw 'month)
15884 ;; approx number of month between the two dates
15885 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15886 ;; How often does dn fit in there?
15887 (setq d (nth 1 start) m (car start) y (nth 2 start)
15888 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15889 m (+ m nm)
15890 ny (floor (/ m 12))
15891 y (+ y ny)
15892 m (- m (* ny 12)))
15893 (while (> m 12) (setq m (- m 12) y (1+ y)))
15894 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15895 (setq m2 (+ m dn) y2 y)
15896 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15897 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15898 (while (<= n2 cday)
15899 (setq n1 n2 m m2 y y2)
15900 (setq m2 (+ m dn) y2 y)
15901 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15902 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15903 ;; Make sure n1 is the earlier date
15904 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15905 (if show-all
15906 (cond
15907 ((eq prefer 'past) (if (= cday n2) n2 n1))
15908 ((eq prefer 'future) (if (= cday n1) n1 n2))
15909 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15910 (cond
15911 ((eq prefer 'past) (if (= cday n2) n2 n1))
15912 ((eq prefer 'future) (if (= cday n1) n1 n2))
15913 (t (if (= cday n1) n1 n2)))))))
15915 (defun org-date-to-gregorian (date)
15916 "Turn any specification of DATE into a Gregorian date for the calendar."
15917 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15918 ((and (listp date) (= (length date) 3)) date)
15919 ((stringp date)
15920 (setq date (org-parse-time-string date))
15921 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15922 ((listp date)
15923 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15925 (defun org-parse-time-string (s &optional nodefault)
15926 "Parse the standard Org-mode time string.
15927 This should be a lot faster than the normal `parse-time-string'.
15928 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15929 hour and minute fields will be nil if not given."
15930 (if (string-match org-ts-regexp0 s)
15931 (list 0
15932 (if (or (match-beginning 8) (not nodefault))
15933 (string-to-number (or (match-string 8 s) "0")))
15934 (if (or (match-beginning 7) (not nodefault))
15935 (string-to-number (or (match-string 7 s) "0")))
15936 (string-to-number (match-string 4 s))
15937 (string-to-number (match-string 3 s))
15938 (string-to-number (match-string 2 s))
15939 nil nil nil)
15940 (error "Not a standard Org-mode time string: %s" s)))
15942 (defun org-timestamp-up (&optional arg)
15943 "Increase the date item at the cursor by one.
15944 If the cursor is on the year, change the year. If it is on the month,
15945 the day or the time, change that.
15946 With prefix ARG, change by that many units."
15947 (interactive "p")
15948 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15950 (defun org-timestamp-down (&optional arg)
15951 "Decrease the date item at the cursor by one.
15952 If the cursor is on the year, change the year. If it is on the month,
15953 the day or the time, change that.
15954 With prefix ARG, change by that many units."
15955 (interactive "p")
15956 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15958 (defun org-timestamp-up-day (&optional arg)
15959 "Increase the date in the time stamp by one day.
15960 With prefix ARG, change that many days."
15961 (interactive "p")
15962 (if (and (not (org-at-timestamp-p t))
15963 (org-at-heading-p))
15964 (org-todo 'up)
15965 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15967 (defun org-timestamp-down-day (&optional arg)
15968 "Decrease the date in the time stamp by one day.
15969 With prefix ARG, change that many days."
15970 (interactive "p")
15971 (if (and (not (org-at-timestamp-p t))
15972 (org-at-heading-p))
15973 (org-todo 'down)
15974 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15976 (defun org-at-timestamp-p (&optional inactive-ok)
15977 "Determine if the cursor is in or at a timestamp."
15978 (interactive)
15979 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15980 (pos (point))
15981 (ans (or (looking-at tsr)
15982 (save-excursion
15983 (skip-chars-backward "^[<\n\r\t")
15984 (if (> (point) (point-min)) (backward-char 1))
15985 (and (looking-at tsr)
15986 (> (- (match-end 0) pos) -1))))))
15987 (and ans
15988 (boundp 'org-ts-what)
15989 (setq org-ts-what
15990 (cond
15991 ((= pos (match-beginning 0)) 'bracket)
15992 ;; Point is considered to be "on the bracket" whether
15993 ;; it's really on it or right after it.
15994 ((or (= pos (1- (match-end 0)))
15995 (= pos (match-end 0))) 'bracket)
15996 ((org-pos-in-match-range pos 2) 'year)
15997 ((org-pos-in-match-range pos 3) 'month)
15998 ((org-pos-in-match-range pos 7) 'hour)
15999 ((org-pos-in-match-range pos 8) 'minute)
16000 ((or (org-pos-in-match-range pos 4)
16001 (org-pos-in-match-range pos 5)) 'day)
16002 ((and (> pos (or (match-end 8) (match-end 5)))
16003 (< pos (match-end 0)))
16004 (- pos (or (match-end 8) (match-end 5))))
16005 (t 'day))))
16006 ans))
16008 (defun org-toggle-timestamp-type ()
16009 "Toggle the type (<active> or [inactive]) of a time stamp."
16010 (interactive)
16011 (when (org-at-timestamp-p t)
16012 (let ((beg (match-beginning 0)) (end (match-end 0))
16013 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16014 (save-excursion
16015 (goto-char beg)
16016 (while (re-search-forward "[][<>]" end t)
16017 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16018 t t)))
16019 (message "Timestamp is now %sactive"
16020 (if (equal (char-after beg) ?<) "" "in")))))
16022 (defun org-timestamp-change (n &optional what updown)
16023 "Change the date in the time stamp at point.
16024 The date will be changed by N times WHAT. WHAT can be `day', `month',
16025 `year', `minute', `second'. If WHAT is not given, the cursor position
16026 in the timestamp determines what will be changed."
16027 (let ((origin (point)) origin-cat
16028 with-hm inactive
16029 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16030 org-ts-what
16031 extra rem
16032 ts time time0)
16033 (if (not (org-at-timestamp-p t))
16034 (error "Not at a timestamp"))
16035 (if (and (not what) (eq org-ts-what 'bracket))
16036 (org-toggle-timestamp-type)
16037 ;; Point isn't on brackets. Remember the part of the time-stamp
16038 ;; the point was in. Indeed, size of time-stamps may change,
16039 ;; but point must be kept in the same category nonetheless.
16040 (setq origin-cat org-ts-what)
16041 (if (and (not what) (not (eq org-ts-what 'day))
16042 org-display-custom-times
16043 (get-text-property (point) 'display)
16044 (not (get-text-property (1- (point)) 'display)))
16045 (setq org-ts-what 'day))
16046 (setq org-ts-what (or what org-ts-what)
16047 inactive (= (char-after (match-beginning 0)) ?\[)
16048 ts (match-string 0))
16049 (replace-match "")
16050 (if (string-match
16051 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16053 (setq extra (match-string 1 ts)))
16054 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16055 (setq with-hm t))
16056 (setq time0 (org-parse-time-string ts))
16057 (when (and updown
16058 (eq org-ts-what 'minute)
16059 (not current-prefix-arg))
16060 ;; This looks like s-up and s-down. Change by one rounding step.
16061 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16062 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16063 (setcar (cdr time0) (+ (nth 1 time0)
16064 (if (> n 0) (- rem) (- dm rem))))))
16065 (setq time
16066 (encode-time (or (car time0) 0)
16067 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16068 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16069 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16070 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16071 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16072 (nthcdr 6 time0)))
16073 (when (and (member org-ts-what '(hour minute))
16074 extra
16075 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16076 (setq extra (org-modify-ts-extra
16077 extra
16078 (if (eq org-ts-what 'hour) 2 5)
16079 n dm)))
16080 (when (integerp org-ts-what)
16081 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16082 (if (eq what 'calendar)
16083 (let ((cal-date (org-get-date-from-calendar)))
16084 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16085 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16086 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16087 (setcar time0 (or (car time0) 0))
16088 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16089 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16090 (setq time (apply 'encode-time time0))))
16091 ;; Insert the new time-stamp, and ensure point stays in the same
16092 ;; category as before (i.e. not after the last position in that
16093 ;; category).
16094 (let ((pos (point)))
16095 ;; Stay before inserted string. `save-excursion' is of no use.
16096 (setq org-last-changed-timestamp
16097 (org-insert-time-stamp time with-hm inactive nil nil extra))
16098 (goto-char pos))
16099 (save-match-data
16100 (looking-at org-ts-regexp3)
16101 (goto-char (cond
16102 ;; `day' category ends before `hour' if any, or at
16103 ;; the end of the day name.
16104 ((eq origin-cat 'day)
16105 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16106 ((eq origin-cat 'hour) (min (match-end 7) origin))
16107 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16108 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16109 ;; `year' and `month' have both fixed size: point
16110 ;; couldn't have moved into another part.
16111 (t origin))))
16112 ;; Update clock if on a CLOCK line.
16113 (org-clock-update-time-maybe)
16114 ;; Try to recenter the calendar window, if any.
16115 (if (and org-calendar-follow-timestamp-change
16116 (get-buffer-window "*Calendar*" t)
16117 (memq org-ts-what '(day month year)))
16118 (org-recenter-calendar (time-to-days time))))))
16120 (defun org-modify-ts-extra (s pos n dm)
16121 "Change the different parts of the lead-time and repeat fields in timestamp."
16122 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16123 ng h m new rem)
16124 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16125 (cond
16126 ((or (org-pos-in-match-range pos 2)
16127 (org-pos-in-match-range pos 3))
16128 (setq m (string-to-number (match-string 3 s))
16129 h (string-to-number (match-string 2 s)))
16130 (if (org-pos-in-match-range pos 2)
16131 (setq h (+ h n))
16132 (setq n (* dm (org-no-warnings (signum n))))
16133 (when (not (= 0 (setq rem (% m dm))))
16134 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16135 (setq m (+ m n)))
16136 (if (< m 0) (setq m (+ m 60) h (1- h)))
16137 (if (> m 59) (setq m (- m 60) h (1+ h)))
16138 (setq h (min 24 (max 0 h)))
16139 (setq ng 1 new (format "-%02d:%02d" h m)))
16140 ((org-pos-in-match-range pos 6)
16141 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16142 ((org-pos-in-match-range pos 5)
16143 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16145 ((org-pos-in-match-range pos 9)
16146 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16147 ((org-pos-in-match-range pos 8)
16148 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16150 (when ng
16151 (setq s (concat
16152 (substring s 0 (match-beginning ng))
16154 (substring s (match-end ng))))))
16157 (defun org-recenter-calendar (date)
16158 "If the calendar is visible, recenter it to DATE."
16159 (let ((cwin (get-buffer-window "*Calendar*" t)))
16160 (when cwin
16161 (let ((calendar-move-hook nil))
16162 (with-selected-window cwin
16163 (calendar-goto-date (if (listp date) date
16164 (calendar-gregorian-from-absolute date))))))))
16166 (defun org-goto-calendar (&optional arg)
16167 "Go to the Emacs calendar at the current date.
16168 If there is a time stamp in the current line, go to that date.
16169 A prefix ARG can be used to force the current date."
16170 (interactive "P")
16171 (let ((tsr org-ts-regexp) diff
16172 (calendar-move-hook nil)
16173 (calendar-view-holidays-initially-flag nil)
16174 (calendar-view-diary-initially-flag nil))
16175 (if (or (org-at-timestamp-p)
16176 (save-excursion
16177 (beginning-of-line 1)
16178 (looking-at (concat ".*" tsr))))
16179 (let ((d1 (time-to-days (current-time)))
16180 (d2 (time-to-days
16181 (org-time-string-to-time (match-string 1)))))
16182 (setq diff (- d2 d1))))
16183 (calendar)
16184 (calendar-goto-today)
16185 (if (and diff (not arg)) (calendar-forward-day diff))))
16187 (defun org-get-date-from-calendar ()
16188 "Return a list (month day year) of date at point in calendar."
16189 (with-current-buffer "*Calendar*"
16190 (save-match-data
16191 (calendar-cursor-to-date))))
16193 (defun org-date-from-calendar ()
16194 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16195 If there is already a time stamp at the cursor position, update it."
16196 (interactive)
16197 (if (org-at-timestamp-p t)
16198 (org-timestamp-change 0 'calendar)
16199 (let ((cal-date (org-get-date-from-calendar)))
16200 (org-insert-time-stamp
16201 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16203 (defun org-minutes-to-hh:mm-string (m)
16204 "Compute H:MM from a number of minutes."
16205 (let ((h (/ m 60)))
16206 (setq m (- m (* 60 h)))
16207 (format org-time-clocksum-format h m)))
16209 (defun org-hh:mm-string-to-minutes (s)
16210 "Convert a string H:MM to a number of minutes.
16211 If the string is just a number, interpret it as minutes.
16212 In fact, the first hh:mm or number in the string will be taken,
16213 there can be extra stuff in the string.
16214 If no number is found, the return value is 0."
16215 (cond
16216 ((integerp s) s)
16217 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16218 (+ (* (string-to-number (match-string 1 s)) 60)
16219 (string-to-number (match-string 2 s))))
16220 ((string-match "\\([0-9]+\\)" s)
16221 (string-to-number (match-string 1 s)))
16222 (t 0)))
16224 (defcustom org-effort-durations
16225 `(("h" . 60)
16226 ("d" . ,(* 60 8))
16227 ("w" . ,(* 60 8 5))
16228 ("m" . ,(* 60 8 5 4))
16229 ("y" . ,(* 60 8 5 40)))
16230 "Conversion factor to minutes for an effort modifier.
16232 Each entry has the form (MODIFIER . MINUTES).
16234 In an effort string, a number followed by MODIFIER is multiplied
16235 by the specified number of MINUTES to obtain an effort in
16236 minutes.
16238 For example, if the value of this variable is ((\"hours\" . 60)), then an
16239 effort string \"2hours\" is equivalent to 120 minutes."
16240 :group 'org-agenda
16241 :version "24.1"
16242 :type '(alist :key-type (string :tag "Modifier")
16243 :value-type (number :tag "Minutes")))
16245 (defun org-duration-string-to-minutes (s)
16246 "Convert a duration string S to minutes.
16248 A bare number is interpreted as minutes, modifiers can be set by
16249 customizing `org-effort-durations' (which see).
16251 Entries containing a colon are interpreted as H:MM by
16252 `org-hh:mm-string-to-minutes'."
16253 (let ((result 0)
16254 (re (concat "\\([0-9]+\\) *\\("
16255 (regexp-opt (mapcar 'car org-effort-durations))
16256 "\\)")))
16257 (while (string-match re s)
16258 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16259 (string-to-number (match-string 1 s))))
16260 (setq s (replace-match "" nil t s)))
16261 (incf result (org-hh:mm-string-to-minutes s))
16262 result))
16264 ;;;; Files
16266 (defun org-save-all-org-buffers ()
16267 "Save all Org-mode buffers without user confirmation."
16268 (interactive)
16269 (message "Saving all Org-mode buffers...")
16270 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16271 (when (featurep 'org-id) (org-id-locations-save))
16272 (message "Saving all Org-mode buffers... done"))
16274 (defun org-revert-all-org-buffers ()
16275 "Revert all Org-mode buffers.
16276 Prompt for confirmation when there are unsaved changes.
16277 Be sure you know what you are doing before letting this function
16278 overwrite your changes.
16280 This function is useful in a setup where one tracks org files
16281 with a version control system, to revert on one machine after pulling
16282 changes from another. I believe the procedure must be like this:
16284 1. M-x org-save-all-org-buffers
16285 2. Pull changes from the other machine, resolve conflicts
16286 3. M-x org-revert-all-org-buffers"
16287 (interactive)
16288 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16289 (error "Abort"))
16290 (save-excursion
16291 (save-window-excursion
16292 (mapc
16293 (lambda (b)
16294 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16295 (with-current-buffer b buffer-file-name))
16296 (org-pop-to-buffer-same-window b)
16297 (revert-buffer t 'no-confirm)))
16298 (buffer-list))
16299 (when (and (featurep 'org-id) org-id-track-globally)
16300 (org-id-locations-load)))))
16302 ;;;; Agenda files
16304 ;;;###autoload
16305 (defun org-switchb (&optional arg)
16306 "Switch between Org buffers.
16307 With one prefix argument, restrict available buffers to files.
16308 With two prefix arguments, restrict available buffers to agenda files.
16310 Defaults to `iswitchb' for buffer name completion.
16311 Set `org-completion-use-ido' to make it use ido instead."
16312 (interactive "P")
16313 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16314 ((equal arg '(16)) (org-buffer-list 'agenda))
16315 (t (org-buffer-list))))
16316 (org-completion-use-iswitchb org-completion-use-iswitchb)
16317 (org-completion-use-ido org-completion-use-ido))
16318 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16319 (setq org-completion-use-iswitchb t))
16320 (org-pop-to-buffer-same-window
16321 (org-icompleting-read "Org buffer: "
16322 (mapcar 'list (mapcar 'buffer-name blist))
16323 nil t))))
16325 ;;; Define some older names previously used for this functionality
16326 ;;;###autoload
16327 (defalias 'org-ido-switchb 'org-switchb)
16328 ;;;###autoload
16329 (defalias 'org-iswitchb 'org-switchb)
16331 (defun org-buffer-list (&optional predicate exclude-tmp)
16332 "Return a list of Org buffers.
16333 PREDICATE can be `export', `files' or `agenda'.
16335 export restrict the list to Export buffers.
16336 files restrict the list to buffers visiting Org files.
16337 agenda restrict the list to buffers visiting agenda files.
16339 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16340 (let* ((bfn nil)
16341 (agenda-files (and (eq predicate 'agenda)
16342 (mapcar 'file-truename (org-agenda-files t))))
16343 (filter
16344 (cond
16345 ((eq predicate 'files)
16346 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16347 ((eq predicate 'export)
16348 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16349 ((eq predicate 'agenda)
16350 (lambda (b)
16351 (with-current-buffer b
16352 (and (eq major-mode 'org-mode)
16353 (setq bfn (buffer-file-name b))
16354 (member (file-truename bfn) agenda-files)))))
16355 (t (lambda (b) (with-current-buffer b
16356 (or (eq major-mode 'org-mode)
16357 (string-match "\*Org .*Export"
16358 (buffer-name b)))))))))
16359 (delq nil
16360 (mapcar
16361 (lambda(b)
16362 (if (and (funcall filter b)
16363 (or (not exclude-tmp)
16364 (not (string-match "tmp" (buffer-name b)))))
16366 nil))
16367 (buffer-list)))))
16369 (defun org-agenda-files (&optional unrestricted archives)
16370 "Get the list of agenda files.
16371 Optional UNRESTRICTED means return the full list even if a restriction
16372 is currently in place.
16373 When ARCHIVES is t, include all archive files that are really being
16374 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16375 `org-agenda-archives-mode' is t."
16376 (let ((files
16377 (cond
16378 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16379 ((stringp org-agenda-files) (org-read-agenda-file-list))
16380 ((listp org-agenda-files) org-agenda-files)
16381 (t (error "Invalid value of `org-agenda-files'")))))
16382 (setq files (apply 'append
16383 (mapcar (lambda (f)
16384 (if (file-directory-p f)
16385 (directory-files
16386 f t org-agenda-file-regexp)
16387 (list f)))
16388 files)))
16389 (when org-agenda-skip-unavailable-files
16390 (setq files (delq nil
16391 (mapcar (function
16392 (lambda (file)
16393 (and (file-readable-p file) file)))
16394 files))))
16395 (when (or (eq archives t)
16396 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16397 (setq files (org-add-archive-files files)))
16398 files))
16400 (defun org-agenda-file-p (&optional file)
16401 "Return non-nil, if FILE is an agenda file.
16402 If FILE is omitted, use the file associated with the current
16403 buffer."
16404 (member (or file (buffer-file-name))
16405 (org-agenda-files t)))
16407 (defun org-edit-agenda-file-list ()
16408 "Edit the list of agenda files.
16409 Depending on setup, this either uses customize to edit the variable
16410 `org-agenda-files', or it visits the file that is holding the list. In the
16411 latter case, the buffer is set up in a way that saving it automatically kills
16412 the buffer and restores the previous window configuration."
16413 (interactive)
16414 (if (stringp org-agenda-files)
16415 (let ((cw (current-window-configuration)))
16416 (find-file org-agenda-files)
16417 (org-set-local 'org-window-configuration cw)
16418 (org-add-hook 'after-save-hook
16419 (lambda ()
16420 (set-window-configuration
16421 (prog1 org-window-configuration
16422 (kill-buffer (current-buffer))))
16423 (org-install-agenda-files-menu)
16424 (message "New agenda file list installed"))
16425 nil 'local)
16426 (message "%s" (substitute-command-keys
16427 "Edit list and finish with \\[save-buffer]")))
16428 (customize-variable 'org-agenda-files)))
16430 (defun org-store-new-agenda-file-list (list)
16431 "Set new value for the agenda file list and save it correctly."
16432 (if (stringp org-agenda-files)
16433 (let ((fe (org-read-agenda-file-list t)) b u)
16434 (while (setq b (find-buffer-visiting org-agenda-files))
16435 (kill-buffer b))
16436 (with-temp-file org-agenda-files
16437 (insert
16438 (mapconcat
16439 (lambda (f) ;; Keep un-expanded entries.
16440 (if (setq u (assoc f fe))
16441 (cdr u)
16443 list "\n")
16444 "\n")))
16445 (let ((org-mode-hook nil) (org-inhibit-startup t)
16446 (org-insert-mode-line-in-empty-file nil))
16447 (setq org-agenda-files list)
16448 (customize-save-variable 'org-agenda-files org-agenda-files))))
16450 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16451 "Read the list of agenda files from a file.
16452 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16453 filenames, used by `org-store-new-agenda-file-list' to write back
16454 un-expanded file names."
16455 (when (file-directory-p org-agenda-files)
16456 (error "`org-agenda-files' cannot be a single directory"))
16457 (when (stringp org-agenda-files)
16458 (with-temp-buffer
16459 (insert-file-contents org-agenda-files)
16460 (mapcar
16461 (lambda (f)
16462 (let ((e (expand-file-name (substitute-in-file-name f)
16463 org-directory)))
16464 (if pair-with-expansion
16465 (cons e f)
16466 e)))
16467 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16469 ;;;###autoload
16470 (defun org-cycle-agenda-files ()
16471 "Cycle through the files in `org-agenda-files'.
16472 If the current buffer visits an agenda file, find the next one in the list.
16473 If the current buffer does not, find the first agenda file."
16474 (interactive)
16475 (let* ((fs (org-agenda-files t))
16476 (files (append fs (list (car fs))))
16477 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16478 file)
16479 (unless files (error "No agenda files"))
16480 (catch 'exit
16481 (while (setq file (pop files))
16482 (if (equal (file-truename file) tcf)
16483 (when (car files)
16484 (find-file (car files))
16485 (throw 'exit t))))
16486 (find-file (car fs)))
16487 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16489 (defun org-agenda-file-to-front (&optional to-end)
16490 "Move/add the current file to the top of the agenda file list.
16491 If the file is not present in the list, it is added to the front. If it is
16492 present, it is moved there. With optional argument TO-END, add/move to the
16493 end of the list."
16494 (interactive "P")
16495 (let ((org-agenda-skip-unavailable-files nil)
16496 (file-alist (mapcar (lambda (x)
16497 (cons (file-truename x) x))
16498 (org-agenda-files t)))
16499 (ctf (file-truename buffer-file-name))
16500 x had)
16501 (setq x (assoc ctf file-alist) had x)
16503 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16504 (if to-end
16505 (setq file-alist (append (delq x file-alist) (list x)))
16506 (setq file-alist (cons x (delq x file-alist))))
16507 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16508 (org-install-agenda-files-menu)
16509 (message "File %s to %s of agenda file list"
16510 (if had "moved" "added") (if to-end "end" "front"))))
16512 (defun org-remove-file (&optional file)
16513 "Remove current file from the list of files in variable `org-agenda-files'.
16514 These are the files which are being checked for agenda entries.
16515 Optional argument FILE means use this file instead of the current."
16516 (interactive)
16517 (let* ((org-agenda-skip-unavailable-files nil)
16518 (file (or file buffer-file-name))
16519 (true-file (file-truename file))
16520 (afile (abbreviate-file-name file))
16521 (files (delq nil (mapcar
16522 (lambda (x)
16523 (if (equal true-file
16524 (file-truename x))
16525 nil x))
16526 (org-agenda-files t)))))
16527 (if (not (= (length files) (length (org-agenda-files t))))
16528 (progn
16529 (org-store-new-agenda-file-list files)
16530 (org-install-agenda-files-menu)
16531 (message "Removed file: %s" afile))
16532 (message "File was not in list: %s (not removed)" afile))))
16534 (defun org-file-menu-entry (file)
16535 (vector file (list 'find-file file) t))
16537 (defun org-check-agenda-file (file)
16538 "Make sure FILE exists. If not, ask user what to do."
16539 (when (not (file-exists-p file))
16540 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16541 (abbreviate-file-name file))
16542 (let ((r (downcase (read-char-exclusive))))
16543 (cond
16544 ((equal r ?r)
16545 (org-remove-file file)
16546 (throw 'nextfile t))
16547 (t (error "Abort"))))))
16549 (defun org-get-agenda-file-buffer (file)
16550 "Get a buffer visiting FILE. If the buffer needs to be created, add
16551 it to the list of buffers which might be released later."
16552 (let ((buf (org-find-base-buffer-visiting file)))
16553 (if buf
16554 buf ; just return it
16555 ;; Make a new buffer and remember it
16556 (setq buf (find-file-noselect file))
16557 (if buf (push buf org-agenda-new-buffers))
16558 buf)))
16560 (defun org-release-buffers (blist)
16561 "Release all buffers in list, asking the user for confirmation when needed.
16562 When a buffer is unmodified, it is just killed. When modified, it is saved
16563 \(if the user agrees) and then killed."
16564 (let (buf file)
16565 (while (setq buf (pop blist))
16566 (setq file (buffer-file-name buf))
16567 (when (and (buffer-modified-p buf)
16568 file
16569 (y-or-n-p (format "Save file %s? " file)))
16570 (with-current-buffer buf (save-buffer)))
16571 (kill-buffer buf))))
16573 (defun org-prepare-agenda-buffers (files)
16574 "Create buffers for all agenda files, protect archived trees and comments."
16575 (interactive)
16576 (let ((pa '(:org-archived t))
16577 (pc '(:org-comment t))
16578 (pall '(:org-archived t :org-comment t))
16579 (inhibit-read-only t)
16580 (rea (concat ":" org-archive-tag ":"))
16581 bmp file re)
16582 (save-excursion
16583 (save-restriction
16584 (while (setq file (pop files))
16585 (catch 'nextfile
16586 (if (bufferp file)
16587 (set-buffer file)
16588 (org-check-agenda-file file)
16589 (set-buffer (org-get-agenda-file-buffer file)))
16590 (widen)
16591 (setq bmp (buffer-modified-p))
16592 (org-refresh-category-properties)
16593 (setq org-todo-keywords-for-agenda
16594 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16595 (setq org-done-keywords-for-agenda
16596 (append org-done-keywords-for-agenda org-done-keywords))
16597 (setq org-todo-keyword-alist-for-agenda
16598 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16599 (setq org-drawers-for-agenda
16600 (append org-drawers-for-agenda org-drawers))
16601 (setq org-tag-alist-for-agenda
16602 (append org-tag-alist-for-agenda org-tag-alist))
16604 (save-excursion
16605 (remove-text-properties (point-min) (point-max) pall)
16606 (when org-agenda-skip-archived-trees
16607 (goto-char (point-min))
16608 (while (re-search-forward rea nil t)
16609 (if (org-at-heading-p t)
16610 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16611 (goto-char (point-min))
16612 (setq re (format org-heading-keyword-regexp-format
16613 org-comment-string))
16614 (while (re-search-forward re nil t)
16615 (add-text-properties
16616 (match-beginning 0) (org-end-of-subtree t) pc)))
16617 (set-buffer-modified-p bmp)))))
16618 (setq org-todo-keywords-for-agenda
16619 (org-uniquify org-todo-keywords-for-agenda))
16620 (setq org-todo-keyword-alist-for-agenda
16621 (org-uniquify org-todo-keyword-alist-for-agenda)
16622 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16624 ;;;; Embedded LaTeX
16626 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16627 "Keymap for the minor `org-cdlatex-mode'.")
16629 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16630 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16631 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16632 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16633 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16635 (defvar org-cdlatex-texmathp-advice-is-done nil
16636 "Flag remembering if we have applied the advice to texmathp already.")
16638 (define-minor-mode org-cdlatex-mode
16639 "Toggle the minor `org-cdlatex-mode'.
16640 This mode supports entering LaTeX environment and math in LaTeX fragments
16641 in Org-mode.
16642 \\{org-cdlatex-mode-map}"
16643 nil " OCDL" nil
16644 (when org-cdlatex-mode
16645 (require 'cdlatex)
16646 (run-hooks 'cdlatex-mode-hook)
16647 (cdlatex-compute-tables))
16648 (unless org-cdlatex-texmathp-advice-is-done
16649 (setq org-cdlatex-texmathp-advice-is-done t)
16650 (defadvice texmathp (around org-math-always-on activate)
16651 "Always return t in org-mode buffers.
16652 This is because we want to insert math symbols without dollars even outside
16653 the LaTeX math segments. If Orgmode thinks that point is actually inside
16654 an embedded LaTeX fragment, let texmathp do its job.
16655 \\[org-cdlatex-mode-map]"
16656 (interactive)
16657 (let (p)
16658 (cond
16659 ((not (eq major-mode 'org-mode)) ad-do-it)
16660 ((eq this-command 'cdlatex-math-symbol)
16661 (setq ad-return-value t
16662 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16664 (let ((p (org-inside-LaTeX-fragment-p)))
16665 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16666 (setq ad-return-value t
16667 texmathp-why '("Org-mode embedded math" . 0))
16668 (if p ad-do-it)))))))))
16670 (defun turn-on-org-cdlatex ()
16671 "Unconditionally turn on `org-cdlatex-mode'."
16672 (org-cdlatex-mode 1))
16674 (defun org-inside-LaTeX-fragment-p ()
16675 "Test if point is inside a LaTeX fragment.
16676 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16677 sequence appearing also before point.
16678 Even though the matchers for math are configurable, this function assumes
16679 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16680 delimiters are skipped when they have been removed by customization.
16681 The return value is nil, or a cons cell with the delimiter and the
16682 position of this delimiter.
16684 This function does a reasonably good job, but can locally be fooled by
16685 for example currency specifications. For example it will assume being in
16686 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16687 fragments that are properly closed, but during editing, we have to live
16688 with the uncertainty caused by missing closing delimiters. This function
16689 looks only before point, not after."
16690 (catch 'exit
16691 (let ((pos (point))
16692 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16693 (lim (progn
16694 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16695 (point)))
16696 dd-on str (start 0) m re)
16697 (goto-char pos)
16698 (when dodollar
16699 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16700 re (nth 1 (assoc "$" org-latex-regexps)))
16701 (while (string-match re str start)
16702 (cond
16703 ((= (match-end 0) (length str))
16704 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16705 ((= (match-end 0) (- (length str) 5))
16706 (throw 'exit nil))
16707 (t (setq start (match-end 0))))))
16708 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16709 (goto-char pos)
16710 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16711 (and (match-beginning 2) (throw 'exit nil))
16712 ;; count $$
16713 (while (re-search-backward "\\$\\$" lim t)
16714 (setq dd-on (not dd-on)))
16715 (goto-char pos)
16716 (if dd-on (cons "$$" m))))))
16718 (defun org-inside-latex-macro-p ()
16719 "Is point inside a LaTeX macro or its arguments?"
16720 (save-match-data
16721 (org-in-regexp
16722 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16724 (defun org-try-cdlatex-tab ()
16725 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16726 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16727 - inside a LaTeX fragment, or
16728 - after the first word in a line, where an abbreviation expansion could
16729 insert a LaTeX environment."
16730 (when org-cdlatex-mode
16731 (cond
16732 ;; Before any word on the line: No expansion possible.
16733 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16734 ;; Just after first word on the line: Expand it. Make sure it
16735 ;; cannot happen on headlines, though.
16736 ((save-excursion
16737 (skip-chars-backward "a-zA-Z0-9*")
16738 (skip-chars-backward " \t")
16739 (and (bolp) (not (org-at-heading-p))))
16740 (cdlatex-tab) t)
16741 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16743 (defun org-cdlatex-underscore-caret (&optional arg)
16744 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16745 Revert to the normal definition outside of these fragments."
16746 (interactive "P")
16747 (if (org-inside-LaTeX-fragment-p)
16748 (call-interactively 'cdlatex-sub-superscript)
16749 (let (org-cdlatex-mode)
16750 (call-interactively (key-binding (vector last-input-event))))))
16752 (defun org-cdlatex-math-modify (&optional arg)
16753 "Execute `cdlatex-math-modify' in LaTeX fragments.
16754 Revert to the normal definition outside of these fragments."
16755 (interactive "P")
16756 (if (org-inside-LaTeX-fragment-p)
16757 (call-interactively 'cdlatex-math-modify)
16758 (let (org-cdlatex-mode)
16759 (call-interactively (key-binding (vector last-input-event))))))
16761 (defvar org-latex-fragment-image-overlays nil
16762 "List of overlays carrying the images of latex fragments.")
16763 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16765 (defun org-remove-latex-fragment-image-overlays ()
16766 "Remove all overlays with LaTeX fragment images in current buffer."
16767 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16768 (setq org-latex-fragment-image-overlays nil))
16770 (defun org-preview-latex-fragment (&optional subtree)
16771 "Preview the LaTeX fragment at point, or all locally or globally.
16772 If the cursor is in a LaTeX fragment, create the image and overlay
16773 it over the source code. If there is no fragment at point, display
16774 all fragments in the current text, from one headline to the next. With
16775 prefix SUBTREE, display all fragments in the current subtree. With a
16776 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16777 the cursor is before the first headline,
16778 display all fragments in the buffer.
16779 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16780 (interactive "P")
16781 (unless buffer-file-name
16782 (error "Can't preview LaTeX fragment in a non-file buffer"))
16783 (org-remove-latex-fragment-image-overlays)
16784 (save-excursion
16785 (save-restriction
16786 (let (beg end at msg)
16787 (cond
16788 ((or (equal subtree '(16))
16789 (not (save-excursion
16790 (re-search-backward org-outline-regexp-bol nil t))))
16791 (setq beg (point-min) end (point-max)
16792 msg "Creating images for buffer...%s"))
16793 ((equal subtree '(4))
16794 (org-back-to-heading)
16795 (setq beg (point) end (org-end-of-subtree t)
16796 msg "Creating images for subtree...%s"))
16798 (if (setq at (org-inside-LaTeX-fragment-p))
16799 (goto-char (max (point-min) (- (cdr at) 2)))
16800 (org-back-to-heading))
16801 (setq beg (point) end (progn (outline-next-heading) (point))
16802 msg (if at "Creating image...%s"
16803 "Creating images for entry...%s"))))
16804 (message msg "")
16805 (narrow-to-region beg end)
16806 (goto-char beg)
16807 (org-format-latex
16808 (concat "ltxpng/" (file-name-sans-extension
16809 (file-name-nondirectory
16810 buffer-file-name)))
16811 default-directory 'overlays msg at 'forbuffer 'dvipng)
16812 (message msg "done. Use `C-c C-c' to remove images.")))))
16814 (defvar org-latex-regexps
16815 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16816 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16817 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16818 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16819 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16820 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16821 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16822 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16823 "Regular expressions for matching embedded LaTeX.")
16825 (defvar org-export-have-math nil) ;; dynamic scoping
16826 (defun org-format-latex (prefix &optional dir overlays msg at
16827 forbuffer processing-type)
16828 "Replace LaTeX fragments with links to an image, and produce images.
16829 Some of the options can be changed using the variable
16830 `org-format-latex-options'."
16831 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16832 (let* ((prefixnodir (file-name-nondirectory prefix))
16833 (absprefix (expand-file-name prefix dir))
16834 (todir (file-name-directory absprefix))
16835 (opt org-format-latex-options)
16836 (matchers (plist-get opt :matchers))
16837 (re-list org-latex-regexps)
16838 (org-format-latex-header-extra
16839 (plist-get (org-infile-export-plist) :latex-header-extra))
16840 (cnt 0) txt hash link beg end re e checkdir
16841 executables-checked string
16842 m n block-type block linkfile movefile ov)
16843 ;; Check the different regular expressions
16844 (while (setq e (pop re-list))
16845 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16846 block (if block-type "\n\n" ""))
16847 (when (member m matchers)
16848 (goto-char (point-min))
16849 (while (re-search-forward re nil t)
16850 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16851 (not (get-text-property (match-beginning n)
16852 'org-protected))
16853 (or (not overlays)
16854 (not (eq (get-char-property (match-beginning n)
16855 'org-overlay-type)
16856 'org-latex-overlay))))
16857 (setq org-export-have-math t)
16858 (cond
16859 ((eq processing-type 'verbatim)
16860 ;; Leave the text verbatim, just protect it
16861 (add-text-properties (match-beginning n) (match-end n)
16862 '(org-protected t)))
16863 ((eq processing-type 'mathjax)
16864 ;; Prepare for MathJax processing
16865 (setq string (match-string n))
16866 (if (member m '("$" "$1"))
16867 (save-excursion
16868 (delete-region (match-beginning n) (match-end n))
16869 (goto-char (match-beginning n))
16870 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16871 "\\)")
16872 '(org-protected t))))
16873 (add-text-properties (match-beginning n) (match-end n)
16874 '(org-protected t))))
16875 ((eq processing-type 'dvipng)
16876 ;; Process to an image
16877 (setq txt (match-string n)
16878 beg (match-beginning n) end (match-end n)
16879 cnt (1+ cnt))
16880 (let (print-length print-level) ; make sure full list is printed
16881 (setq hash (sha1 (prin1-to-string
16882 (list org-format-latex-header
16883 org-format-latex-header-extra
16884 org-export-latex-default-packages-alist
16885 org-export-latex-packages-alist
16886 org-format-latex-options
16887 forbuffer txt)))
16888 linkfile (format "%s_%s.png" prefix hash)
16889 movefile (format "%s_%s.png" absprefix hash)))
16890 (setq link (concat block "[[file:" linkfile "]]" block))
16891 (if msg (message msg cnt))
16892 (goto-char beg)
16893 (unless checkdir ; make sure the directory exists
16894 (setq checkdir t)
16895 (or (file-directory-p todir) (make-directory todir t)))
16897 (unless executables-checked
16898 (org-check-external-command
16899 "latex" "needed to convert LaTeX fragments to images")
16900 (org-check-external-command
16901 "dvipng" "needed to convert LaTeX fragments to images")
16902 (setq executables-checked t))
16904 (unless (file-exists-p movefile)
16905 (org-create-formula-image
16906 txt movefile opt forbuffer))
16907 (if overlays
16908 (progn
16909 (mapc (lambda (o)
16910 (if (eq (overlay-get o 'org-overlay-type)
16911 'org-latex-overlay)
16912 (delete-overlay o)))
16913 (overlays-in beg end))
16914 (setq ov (make-overlay beg end))
16915 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16916 (if (featurep 'xemacs)
16917 (progn
16918 (overlay-put ov 'invisible t)
16919 (overlay-put
16920 ov 'end-glyph
16921 (make-glyph (vector 'png :file movefile))))
16922 (overlay-put
16923 ov 'display
16924 (list 'image :type 'png :file movefile :ascent 'center)))
16925 (push ov org-latex-fragment-image-overlays)
16926 (goto-char end))
16927 (delete-region beg end)
16928 (insert (org-add-props link
16929 (list 'org-latex-src
16930 (replace-regexp-in-string
16931 "\"" "" txt)
16932 'org-latex-src-embed-type
16933 (if block-type 'paragraph 'character))))))
16934 ((eq processing-type 'mathml)
16935 ;; Process to MathML
16936 (unless executables-checked
16937 (unless (save-match-data (org-format-latex-mathml-available-p))
16938 (error "LaTeX to MathML converter not configured"))
16939 (setq executables-checked t))
16940 (setq txt (match-string n)
16941 beg (match-beginning n) end (match-end n)
16942 cnt (1+ cnt))
16943 (if msg (message msg cnt))
16944 (goto-char beg)
16945 (delete-region beg end)
16946 (insert (org-format-latex-as-mathml
16947 txt block-type prefix dir)))
16949 (error "Unknown conversion type %s for latex fragments"
16950 processing-type)))))))))
16952 (defun org-create-math-formula (latex-frag &optional mathml-file)
16953 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16954 Use `org-latex-to-mathml-convert-command'. If the conversion is
16955 sucessful, return the portion between \"<math...> </math>\"
16956 elements otherwise return nil. When MATHML-FILE is specified,
16957 write the results in to that file. When invoked as an
16958 interactive command, prompt for LATEX-FRAG, with initial value
16959 set to the current active region and echo the results for user
16960 inspection."
16961 (interactive (list (let ((frag (when (region-active-p)
16962 (buffer-substring-no-properties
16963 (region-beginning) (region-end)))))
16964 (read-string "LaTeX Fragment: " frag nil frag))))
16965 (unless latex-frag (error "Invalid latex-frag"))
16966 (let* ((tmp-in-file (file-relative-name
16967 (make-temp-name (expand-file-name "ltxmathml-in"))))
16968 (ignore (write-region latex-frag nil tmp-in-file))
16969 (tmp-out-file (file-relative-name
16970 (make-temp-name (expand-file-name "ltxmathml-out"))))
16971 (cmd (format-spec
16972 org-latex-to-mathml-convert-command
16973 `((?j . ,(shell-quote-argument
16974 (expand-file-name org-latex-to-mathml-jar-file)))
16975 (?I . ,(shell-quote-argument tmp-in-file))
16976 (?o . ,(shell-quote-argument tmp-out-file)))))
16977 mathml shell-command-output)
16978 (when (org-called-interactively-p 'any)
16979 (unless (org-format-latex-mathml-available-p)
16980 (error "LaTeX to MathML converter not configured")))
16981 (message "Running %s" cmd)
16982 (setq shell-command-output (shell-command-to-string cmd))
16983 (setq mathml
16984 (when (file-readable-p tmp-out-file)
16985 (with-current-buffer (find-file-noselect tmp-out-file t)
16986 (goto-char (point-min))
16987 (when (re-search-forward
16988 (concat
16989 (regexp-quote
16990 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16991 "\\(.\\|\n\\)*"
16992 (regexp-quote "</math>")) nil t)
16993 (prog1 (match-string 0) (kill-buffer))))))
16994 (cond
16995 (mathml
16996 (setq mathml
16997 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16998 (when mathml-file
16999 (write-region mathml nil mathml-file))
17000 (when (org-called-interactively-p 'any)
17001 (message mathml)))
17002 ((message "LaTeX to MathML conversion failed")
17003 (message shell-command-output)))
17004 (delete-file tmp-in-file)
17005 (when (file-exists-p tmp-out-file)
17006 (delete-file tmp-out-file))
17007 mathml))
17009 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17010 prefix &optional dir)
17011 "Use `org-create-math-formula' but check local cache first."
17012 (let* ((absprefix (expand-file-name prefix dir))
17013 (print-length nil) (print-level nil)
17014 (formula-id (concat
17015 "formula-"
17016 (sha1
17017 (prin1-to-string
17018 (list latex-frag
17019 org-latex-to-mathml-convert-command)))))
17020 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17021 (formula-cache-dir (file-name-directory formula-cache)))
17023 (unless (file-directory-p formula-cache-dir)
17024 (make-directory formula-cache-dir t))
17026 (unless (file-exists-p formula-cache)
17027 (org-create-math-formula latex-frag formula-cache))
17029 (if (file-exists-p formula-cache)
17030 ;; Successful conversion. Return the link to MathML file.
17031 (org-add-props
17032 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17033 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17034 'org-latex-src-embed-type (if latex-frag-type
17035 'paragraph 'character)))
17036 ;; Failed conversion. Return the LaTeX fragment verbatim
17037 (add-text-properties
17038 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17039 latex-frag)))
17041 ;; This function borrows from Ganesh Swami's latex2png.el
17042 (defun org-create-formula-image (string tofile options buffer)
17043 "This calls dvipng."
17044 (require 'org-latex)
17045 (let* ((tmpdir (if (featurep 'xemacs)
17046 (temp-directory)
17047 temporary-file-directory))
17048 (texfilebase (make-temp-name
17049 (expand-file-name "orgtex" tmpdir)))
17050 (texfile (concat texfilebase ".tex"))
17051 (dvifile (concat texfilebase ".dvi"))
17052 (pngfile (concat texfilebase ".png"))
17053 (fnh (if (featurep 'xemacs)
17054 (font-height (face-font 'default))
17055 (face-attribute 'default :height nil)))
17056 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17057 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17058 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17059 "Black"))
17060 (bg (or (plist-get options (if buffer :background :html-background))
17061 "Transparent")))
17062 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17063 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17064 (with-temp-file texfile
17065 (insert (org-splice-latex-header
17066 org-format-latex-header
17067 org-export-latex-default-packages-alist
17068 org-export-latex-packages-alist t
17069 org-format-latex-header-extra))
17070 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17071 (require 'org-latex)
17072 (org-export-latex-fix-inputenc))
17073 (let ((dir default-directory))
17074 (condition-case nil
17075 (progn
17076 (cd tmpdir)
17077 (call-process "latex" nil nil nil texfile))
17078 (error nil))
17079 (cd dir))
17080 (if (not (file-exists-p dvifile))
17081 (progn (message "Failed to create dvi file from %s" texfile) nil)
17082 (condition-case nil
17083 (if (featurep 'xemacs)
17084 (call-process "dvipng" nil nil nil
17085 "-fg" fg "-bg" bg
17086 "-T" "tight"
17087 "-o" pngfile
17088 dvifile)
17089 (call-process "dvipng" nil nil nil
17090 "-fg" fg "-bg" bg
17091 "-D" dpi
17092 ;;"-x" scale "-y" scale
17093 "-T" "tight"
17094 "-o" pngfile
17095 dvifile))
17096 (error nil))
17097 (if (not (file-exists-p pngfile))
17098 (if org-format-latex-signal-error
17099 (error "Failed to create png file from %s" texfile)
17100 (message "Failed to create png file from %s" texfile)
17101 nil)
17102 ;; Use the requested file name and clean up
17103 (copy-file pngfile tofile 'replace)
17104 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17105 (delete-file (concat texfilebase e)))
17106 pngfile))))
17108 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17109 "Fill a LaTeX header template TPL.
17110 In the template, the following place holders will be recognized:
17112 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17113 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17114 [PACKAGES] \\usepackage statements for PKG
17115 [NO-PACKAGES] do not include PKG
17116 [EXTRA] the string EXTRA
17117 [NO-EXTRA] do not include EXTRA
17119 For backward compatibility, if both the positive and the negative place
17120 holder is missing, the positive one (without the \"NO-\") will be
17121 assumed to be present at the end of the template.
17122 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17123 EXTRA is a string.
17124 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17125 (let (rpl (end ""))
17126 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17127 (setq rpl (if (or (match-end 1) (not def-pkg))
17128 "" (org-latex-packages-to-string def-pkg snippets-p t))
17129 tpl (replace-match rpl t t tpl))
17130 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17132 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17133 (setq rpl (if (or (match-end 1) (not pkg))
17134 "" (org-latex-packages-to-string pkg snippets-p t))
17135 tpl (replace-match rpl t t tpl))
17136 (if pkg (setq end
17137 (concat end "\n"
17138 (org-latex-packages-to-string pkg snippets-p)))))
17140 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17141 (setq rpl (if (or (match-end 1) (not extra))
17142 "" (concat extra "\n"))
17143 tpl (replace-match rpl t t tpl))
17144 (if (and extra (string-match "\\S-" extra))
17145 (setq end (concat end "\n" extra))))
17147 (if (string-match "\\S-" end)
17148 (concat tpl "\n" end)
17149 tpl)))
17151 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17152 "Turn an alist of packages into a string with the \\usepackage macros."
17153 (setq pkg (mapconcat (lambda(p)
17154 (cond
17155 ((stringp p) p)
17156 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17157 (format "%% Package %s omitted" (cadr p)))
17158 ((equal "" (car p))
17159 (format "\\usepackage{%s}" (cadr p)))
17161 (format "\\usepackage[%s]{%s}"
17162 (car p) (cadr p)))))
17164 "\n"))
17165 (if newline (concat pkg "\n") pkg))
17167 (defun org-dvipng-color (attr)
17168 "Return an rgb color specification for dvipng."
17169 (apply 'format "rgb %s %s %s"
17170 (mapcar 'org-normalize-color
17171 (if (featurep 'xemacs)
17172 (color-rgb-components
17173 (face-property 'default
17174 (cond ((eq attr :foreground) 'foreground)
17175 ((eq attr :background) 'background))))
17176 (color-values (face-attribute 'default attr nil))))))
17178 (defun org-normalize-color (value)
17179 "Return string to be used as color value for an RGB component."
17180 (format "%g" (/ value 65535.0)))
17182 ;; Image display
17185 (defvar org-inline-image-overlays nil)
17186 (make-variable-buffer-local 'org-inline-image-overlays)
17188 (defun org-toggle-inline-images (&optional include-linked)
17189 "Toggle the display of inline images.
17190 INCLUDE-LINKED is passed to `org-display-inline-images'."
17191 (interactive "P")
17192 (if org-inline-image-overlays
17193 (progn
17194 (org-remove-inline-images)
17195 (message "Inline image display turned off"))
17196 (org-display-inline-images include-linked)
17197 (if org-inline-image-overlays
17198 (message "%d images displayed inline"
17199 (length org-inline-image-overlays))
17200 (message "No images to display inline"))))
17202 (defun org-display-inline-images (&optional include-linked refresh beg end)
17203 "Display inline images.
17204 Normally only links without a description part are inlined, because this
17205 is how it will work for export. When INCLUDE-LINKED is set, also links
17206 with a description part will be inlined. This can be nice for a quick
17207 look at those images, but it does not reflect what exported files will look
17208 like.
17209 When REFRESH is set, refresh existing images between BEG and END.
17210 This will create new image displays only if necessary.
17211 BEG and END default to the buffer boundaries."
17212 (interactive "P")
17213 (unless refresh
17214 (org-remove-inline-images)
17215 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17216 (save-excursion
17217 (save-restriction
17218 (widen)
17219 (setq beg (or beg (point-min)) end (or end (point-max)))
17220 (goto-char beg)
17221 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17222 (substring (org-image-file-name-regexp) 0 -2)
17223 "\\)\\]" (if include-linked "" "\\]")))
17224 old file ov img)
17225 (while (re-search-forward re end t)
17226 (setq old (get-char-property-and-overlay (match-beginning 1)
17227 'org-image-overlay))
17228 (setq file (expand-file-name
17229 (concat (or (match-string 3) "") (match-string 4))))
17230 (when (file-exists-p file)
17231 (if (and (car-safe old) refresh)
17232 (image-refresh (overlay-get (cdr old) 'display))
17233 (setq img (save-match-data (create-image file)))
17234 (when img
17235 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17236 (overlay-put ov 'display img)
17237 (overlay-put ov 'face 'default)
17238 (overlay-put ov 'org-image-overlay t)
17239 (overlay-put ov 'modification-hooks
17240 (list 'org-display-inline-modification-hook))
17241 (push ov org-inline-image-overlays)))))))))
17243 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17244 "Remove inline-display overlay if a corresponding region is modified."
17245 (let ((inhibit-modification-hooks t))
17246 (when (and ov after)
17247 (delete ov org-inline-image-overlays)
17248 (delete-overlay ov))))
17250 (defun org-remove-inline-images ()
17251 "Remove inline display of images."
17252 (interactive)
17253 (mapc 'delete-overlay org-inline-image-overlays)
17254 (setq org-inline-image-overlays nil))
17256 ;;;; Key bindings
17258 ;; Outline functions from `outline-mode-prefix-map'
17259 ;; that can be remapped in Org:
17260 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17261 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17262 (define-key org-mode-map [remap outline-forward-same-level]
17263 'org-forward-same-level)
17264 (define-key org-mode-map [remap outline-backward-same-level]
17265 'org-backward-same-level)
17266 (define-key org-mode-map [remap show-branches]
17267 'org-kill-note-or-show-branches)
17268 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17269 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17270 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17272 ;; Outline functions from `outline-mode-prefix-map'
17273 ;; that can not be remapped in Org:
17274 ;; - the column "key binding" shows whether the Outline function is still
17275 ;; available in Org mode on the same key that it has been bound to in
17276 ;; Outline mode:
17277 ;; - "overridden": key used for a different functionality in Org mode
17278 ;; - else: key still bound to the same Outline function in Org mode
17279 ;; | Outline function | key binding | Org replacement |
17280 ;; |------------------------------------+-------------+-----------------------|
17281 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17282 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17283 ;; | `show-children' | `C-c C-i' | visibility cycling |
17284 ;; | `hide-subtree' | overridden | visibility cycling |
17285 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17286 ;; | `hide-body' | overridden | no replacement |
17287 ;; | `show-all' | overridden | no replacement |
17288 ;; | `hide-entry' | overridden | visibility cycling |
17289 ;; | `show-entry' | overridden | no replacement |
17290 ;; | `hide-leaves' | overridden | no replacement |
17291 ;; | `hide-sublevels' | overridden | no replacement |
17292 ;; | `hide-other' | overridden | no replacement |
17293 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17294 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17296 ;; Make `C-c C-x' a prefix key
17297 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17299 ;; TAB key with modifiers
17300 (org-defkey org-mode-map "\C-i" 'org-cycle)
17301 (org-defkey org-mode-map [(tab)] 'org-cycle)
17302 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17303 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17304 ;; The following line is necessary under Suse GNU/Linux
17305 (unless (featurep 'xemacs)
17306 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17307 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17308 (define-key org-mode-map [backtab] 'org-shifttab)
17310 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17311 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17312 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17314 ;; Cursor keys with modifiers
17315 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17316 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17317 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17318 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17320 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17321 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17322 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17323 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17325 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17326 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17327 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17328 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17330 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17331 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17332 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17333 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17335 ;; Babel keys
17336 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17337 (mapc (lambda (pair)
17338 (define-key org-babel-map (car pair) (cdr pair)))
17339 org-babel-key-bindings)
17341 ;;; Extra keys for tty access.
17342 ;; We only set them when really needed because otherwise the
17343 ;; menus don't show the simple keys
17345 (when (or org-use-extra-keys
17346 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17347 (not window-system))
17348 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17349 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17350 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17351 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17352 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17353 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17354 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17355 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17356 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17357 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17358 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17359 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17360 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17361 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17362 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17363 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17364 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17365 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17366 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17367 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17368 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17369 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17370 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17371 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17372 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17373 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17374 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17375 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17377 ;; All the other keys
17379 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17380 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17381 (if (boundp 'narrow-map)
17382 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17383 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17384 (if (boundp 'narrow-map)
17385 (org-defkey narrow-map "b" 'org-narrow-to-block)
17386 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17387 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17388 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17389 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17390 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17391 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17392 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17393 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17394 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17395 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17396 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17397 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17398 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17399 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17400 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17401 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17402 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17403 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17404 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17405 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17406 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17407 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17408 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17409 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17410 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17411 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17412 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17413 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17414 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17415 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17416 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17417 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17418 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17419 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17420 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17421 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17422 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17423 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17424 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17425 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17426 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17427 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17428 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17429 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17430 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17431 (org-defkey org-mode-map "\C-c^" 'org-sort)
17432 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17433 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17434 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17435 (org-defkey org-mode-map "\C-m" 'org-return)
17436 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17437 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17438 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17439 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17440 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17441 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17442 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17443 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17444 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17445 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17446 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17447 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17448 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17449 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17450 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17451 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17452 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17453 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17454 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17455 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17456 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17457 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17459 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17460 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17461 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17462 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17464 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17465 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17466 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17467 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17468 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17469 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17470 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17471 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17472 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17473 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17474 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17475 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17476 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17477 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17478 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17479 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17480 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17481 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17483 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17484 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17485 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17486 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17487 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17489 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17491 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17493 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17494 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17496 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17499 (when (featurep 'xemacs)
17500 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17503 (defconst org-speed-commands-default
17505 ("Outline Navigation")
17506 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17507 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17508 ("f" . (org-speed-move-safe 'org-forward-same-level))
17509 ("b" . (org-speed-move-safe 'org-backward-same-level))
17510 ("u" . (org-speed-move-safe 'outline-up-heading))
17511 ("j" . org-goto)
17512 ("g" . (org-refile t))
17513 ("Outline Visibility")
17514 ("c" . org-cycle)
17515 ("C" . org-shifttab)
17516 (" " . org-display-outline-path)
17517 ("Outline Structure Editing")
17518 ("U" . org-shiftmetaup)
17519 ("D" . org-shiftmetadown)
17520 ("r" . org-metaright)
17521 ("l" . org-metaleft)
17522 ("R" . org-shiftmetaright)
17523 ("L" . org-shiftmetaleft)
17524 ("i" . (progn (forward-char 1) (call-interactively
17525 'org-insert-heading-respect-content)))
17526 ("^" . org-sort)
17527 ("w" . org-refile)
17528 ("a" . org-archive-subtree-default-with-confirmation)
17529 ("." . org-mark-subtree)
17530 ("Clock Commands")
17531 ("I" . org-clock-in)
17532 ("O" . org-clock-out)
17533 ("Meta Data Editing")
17534 ("t" . org-todo)
17535 ("0" . (org-priority ?\ ))
17536 ("1" . (org-priority ?A))
17537 ("2" . (org-priority ?B))
17538 ("3" . (org-priority ?C))
17539 (";" . org-set-tags-command)
17540 ("e" . org-set-effort)
17541 ("Agenda Views etc")
17542 ("v" . org-agenda)
17543 ("/" . org-sparse-tree)
17544 ("Misc")
17545 ("o" . org-open-at-point)
17546 ("?" . org-speed-command-help)
17547 ("<" . (org-agenda-set-restriction-lock 'subtree))
17548 (">" . (org-agenda-remove-restriction-lock))
17550 "The default speed commands.")
17552 (defun org-print-speed-command (e)
17553 (if (> (length (car e)) 1)
17554 (progn
17555 (princ "\n")
17556 (princ (car e))
17557 (princ "\n")
17558 (princ (make-string (length (car e)) ?-))
17559 (princ "\n"))
17560 (princ (car e))
17561 (princ " ")
17562 (if (symbolp (cdr e))
17563 (princ (symbol-name (cdr e)))
17564 (prin1 (cdr e)))
17565 (princ "\n")))
17567 (defun org-speed-command-help ()
17568 "Show the available speed commands."
17569 (interactive)
17570 (if (not org-use-speed-commands)
17571 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17572 (with-output-to-temp-buffer "*Help*"
17573 (princ "User-defined Speed commands\n===========================\n")
17574 (mapc 'org-print-speed-command org-speed-commands-user)
17575 (princ "\n")
17576 (princ "Built-in Speed commands\n=======================\n")
17577 (mapc 'org-print-speed-command org-speed-commands-default))
17578 (with-current-buffer "*Help*"
17579 (setq truncate-lines t))))
17581 (defun org-speed-move-safe (cmd)
17582 "Execute CMD, but make sure that the cursor always ends up in a headline.
17583 If not, return to the original position and throw an error."
17584 (interactive)
17585 (let ((pos (point)))
17586 (call-interactively cmd)
17587 (unless (and (bolp) (org-at-heading-p))
17588 (goto-char pos)
17589 (error "Boundary reached while executing %s" cmd))))
17591 (defvar org-self-insert-command-undo-counter 0)
17593 (defvar org-table-auto-blank-field) ; defined in org-table.el
17594 (defvar org-speed-command nil)
17596 (defun org-speed-command-default-hook (keys)
17597 "Hook for activating single-letter speed commands.
17598 `org-speed-commands-default' specifies a minimal command set.
17599 Use `org-speed-commands-user' for further customization."
17600 (when (or (and (bolp) (looking-at org-outline-regexp))
17601 (and (functionp org-use-speed-commands)
17602 (funcall org-use-speed-commands)))
17603 (cdr (assoc keys (append org-speed-commands-user
17604 org-speed-commands-default)))))
17606 (defun org-babel-speed-command-hook (keys)
17607 "Hook for activating single-letter code block commands."
17608 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17609 (cdr (assoc keys org-babel-key-bindings))))
17611 (defcustom org-speed-command-hook
17612 '(org-speed-command-default-hook org-babel-speed-command-hook)
17613 "Hook for activating speed commands at strategic locations.
17614 Hook functions are called in sequence until a valid handler is
17615 found.
17617 Each hook takes a single argument, a user-pressed command key
17618 which is also a `self-insert-command' from the global map.
17620 Within the hook, examine the cursor position and the command key
17621 and return nil or a valid handler as appropriate. Handler could
17622 be one of an interactive command, a function, or a form.
17624 Set `org-use-speed-commands' to non-nil value to enable this
17625 hook. The default setting is `org-speed-command-default-hook'."
17626 :group 'org-structure
17627 :type 'hook)
17629 (defun org-self-insert-command (N)
17630 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17631 If the cursor is in a table looking at whitespace, the whitespace is
17632 overwritten, and the table is not marked as requiring realignment."
17633 (interactive "p")
17634 (org-check-before-invisible-edit 'insert)
17635 (cond
17636 ((and org-use-speed-commands
17637 (setq org-speed-command
17638 (run-hook-with-args-until-success
17639 'org-speed-command-hook (this-command-keys))))
17640 (cond
17641 ((commandp org-speed-command)
17642 (setq this-command org-speed-command)
17643 (call-interactively org-speed-command))
17644 ((functionp org-speed-command)
17645 (funcall org-speed-command))
17646 ((and org-speed-command (listp org-speed-command))
17647 (eval org-speed-command))
17648 (t (let (org-use-speed-commands)
17649 (call-interactively 'org-self-insert-command)))))
17650 ((and
17651 (org-table-p)
17652 (progn
17653 ;; check if we blank the field, and if that triggers align
17654 (and (featurep 'org-table) org-table-auto-blank-field
17655 (member last-command
17656 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17657 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17658 ;; got extra space, this field does not determine column width
17659 (let (org-table-may-need-update) (org-table-blank-field))
17660 ;; no extra space, this field may determine column width
17661 (org-table-blank-field)))
17663 (eq N 1)
17664 (looking-at "[^|\n]* |"))
17665 (let (org-table-may-need-update)
17666 (goto-char (1- (match-end 0)))
17667 (backward-delete-char 1)
17668 (goto-char (match-beginning 0))
17669 (self-insert-command N)))
17671 (setq org-table-may-need-update t)
17672 (self-insert-command N)
17673 (org-fix-tags-on-the-fly)
17674 (if org-self-insert-cluster-for-undo
17675 (if (not (eq last-command 'org-self-insert-command))
17676 (setq org-self-insert-command-undo-counter 1)
17677 (if (>= org-self-insert-command-undo-counter 20)
17678 (setq org-self-insert-command-undo-counter 1)
17679 (and (> org-self-insert-command-undo-counter 0)
17680 buffer-undo-list (listp buffer-undo-list)
17681 (not (cadr buffer-undo-list)) ; remove nil entry
17682 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17683 (setq org-self-insert-command-undo-counter
17684 (1+ org-self-insert-command-undo-counter))))))))
17686 (defun org-check-before-invisible-edit (kind)
17687 "Check is editing if kind KIND would be dangerous with invisible text around.
17688 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17689 ;; First, try to get out of here as quickly as possible, to reduce overhead
17690 (if (and org-catch-invisible-edits
17691 (or (not (boundp 'visible-mode)) (not visible-mode))
17692 (or (get-char-property (point) 'invisible)
17693 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17694 ;; OK, we need to take a closer look
17695 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17696 (invisible-before-point (if (bobp) nil (get-char-property
17697 (1- (point)) 'invisible)))
17698 (border-and-ok-direction
17700 ;; Check if we are acting predictably before invisible text
17701 (and invisible-at-point (not invisible-before-point)
17702 (memq kind '(insert delete-backward)))
17703 ;; Check if we are acting predictably after invisible text
17704 ;; This works not well, and I have turned it off. It seems
17705 ;; better to always show and stop after invisible text.
17706 ;; (and (not invisible-at-point) invisible-before-point
17707 ;; (memq kind '(insert delete)))
17710 (when (or (memq invisible-at-point '(outline org-hide-block))
17711 (memq invisible-before-point '(outline org-hide-block)))
17712 (if (eq org-catch-invisible-edits 'error)
17713 (error "Editing in invisible areas is prohibited - make visible first"))
17714 ;; Make the area visible
17715 (save-excursion
17716 (if invisible-before-point
17717 (goto-char (previous-single-char-property-change
17718 (point) 'invisible)))
17719 (org-cycle))
17720 (cond
17721 ((eq org-catch-invisible-edits 'show)
17722 ;; That's it, we do the edit after showing
17723 (message
17724 "Unfolding invisible region around point before editing")
17725 (sit-for 1))
17726 ((and (eq org-catch-invisible-edits 'smart)
17727 border-and-ok-direction)
17728 (message "Unfolding invisible region around point before editing"))
17730 ;; Don't do the edit, make the user repeat it in full visibility
17731 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17733 (defun org-fix-tags-on-the-fly ()
17734 (when (and (equal (char-after (point-at-bol)) ?*)
17735 (org-at-heading-p))
17736 (org-align-tags-here org-tags-column)))
17738 (defun org-delete-backward-char (N)
17739 "Like `delete-backward-char', insert whitespace at field end in tables.
17740 When deleting backwards, in tables this function will insert whitespace in
17741 front of the next \"|\" separator, to keep the table aligned. The table will
17742 still be marked for re-alignment if the field did fill the entire column,
17743 because, in this case the deletion might narrow the column."
17744 (interactive "p")
17745 (org-check-before-invisible-edit 'delete-backward)
17746 (if (and (org-table-p)
17747 (eq N 1)
17748 (string-match "|" (buffer-substring (point-at-bol) (point)))
17749 (looking-at ".*?|"))
17750 (let ((pos (point))
17751 (noalign (looking-at "[^|\n\r]* |"))
17752 (c org-table-may-need-update))
17753 (backward-delete-char N)
17754 (if (not overwrite-mode)
17755 (progn
17756 (skip-chars-forward "^|")
17757 (insert " ")
17758 (goto-char (1- pos))))
17759 ;; noalign: if there were two spaces at the end, this field
17760 ;; does not determine the width of the column.
17761 (if noalign (setq org-table-may-need-update c)))
17762 (backward-delete-char N)
17763 (org-fix-tags-on-the-fly)))
17765 (defun org-delete-char (N)
17766 "Like `delete-char', but insert whitespace at field end in tables.
17767 When deleting characters, in tables this function will insert whitespace in
17768 front of the next \"|\" separator, to keep the table aligned. The table will
17769 still be marked for re-alignment if the field did fill the entire column,
17770 because, in this case the deletion might narrow the column."
17771 (interactive "p")
17772 (org-check-before-invisible-edit 'delete)
17773 (if (and (org-table-p)
17774 (not (bolp))
17775 (not (= (char-after) ?|))
17776 (eq N 1))
17777 (if (looking-at ".*?|")
17778 (let ((pos (point))
17779 (noalign (looking-at "[^|\n\r]* |"))
17780 (c org-table-may-need-update))
17781 (replace-match (concat
17782 (substring (match-string 0) 1 -1)
17783 " |"))
17784 (goto-char pos)
17785 ;; noalign: if there were two spaces at the end, this field
17786 ;; does not determine the width of the column.
17787 (if noalign (setq org-table-may-need-update c)))
17788 (delete-char N))
17789 (delete-char N)
17790 (org-fix-tags-on-the-fly)))
17792 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17793 (put 'org-self-insert-command 'delete-selection t)
17794 (put 'orgtbl-self-insert-command 'delete-selection t)
17795 (put 'org-delete-char 'delete-selection 'supersede)
17796 (put 'org-delete-backward-char 'delete-selection 'supersede)
17797 (put 'org-yank 'delete-selection 'yank)
17799 ;; Make `flyspell-mode' delay after some commands
17800 (put 'org-self-insert-command 'flyspell-delayed t)
17801 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17802 (put 'org-delete-char 'flyspell-delayed t)
17803 (put 'org-delete-backward-char 'flyspell-delayed t)
17805 ;; Make pabbrev-mode expand after org-mode commands
17806 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17807 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17809 ;; How to do this: Measure non-white length of current string
17810 ;; If equal to column width, we should realign.
17812 (defun org-remap (map &rest commands)
17813 "In MAP, remap the functions given in COMMANDS.
17814 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17815 (let (new old)
17816 (while commands
17817 (setq old (pop commands) new (pop commands))
17818 (if (fboundp 'command-remapping)
17819 (org-defkey map (vector 'remap old) new)
17820 (substitute-key-definition old new map global-map)))))
17822 (when (eq org-enable-table-editor 'optimized)
17823 ;; If the user wants maximum table support, we need to hijack
17824 ;; some standard editing functions
17825 (org-remap org-mode-map
17826 'self-insert-command 'org-self-insert-command
17827 'delete-char 'org-delete-char
17828 'delete-backward-char 'org-delete-backward-char)
17829 (org-defkey org-mode-map "|" 'org-force-self-insert))
17831 (defvar org-ctrl-c-ctrl-c-hook nil
17832 "Hook for functions attaching themselves to `C-c C-c'.
17834 This can be used to add additional functionality to the C-c C-c
17835 key which executes context-dependent commands. This hook is run
17836 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17837 run after the last test.
17839 Each function will be called with no arguments. The function
17840 must check if the context is appropriate for it to act. If yes,
17841 it should do its thing and then return a non-nil value. If the
17842 context is wrong, just do nothing and return nil.")
17844 (defvar org-ctrl-c-ctrl-c-final-hook nil
17845 "Hook for functions attaching themselves to `C-c C-c'.
17847 This can be used to add additional functionality to the C-c C-c
17848 key which executes context-dependent commands. This hook is run
17849 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17850 before the first test.
17852 Each function will be called with no arguments. The function
17853 must check if the context is appropriate for it to act. If yes,
17854 it should do its thing and then return a non-nil value. If the
17855 context is wrong, just do nothing and return nil.")
17857 (defvar org-tab-first-hook nil
17858 "Hook for functions to attach themselves to TAB.
17859 See `org-ctrl-c-ctrl-c-hook' for more information.
17860 This hook runs as the first action when TAB is pressed, even before
17861 `org-cycle' messes around with the `outline-regexp' to cater for
17862 inline tasks and plain list item folding.
17863 If any function in this hook returns t, any other actions that
17864 would have been caused by TAB (such as table field motion or visibility
17865 cycling) will not occur.")
17867 (defvar org-tab-after-check-for-table-hook nil
17868 "Hook for functions to attach themselves to TAB.
17869 See `org-ctrl-c-ctrl-c-hook' for more information.
17870 This hook runs after it has been established that the cursor is not in a
17871 table, but before checking if the cursor is in a headline or if global cycling
17872 should be done.
17873 If any function in this hook returns t, not other actions like visibility
17874 cycling will be done.")
17876 (defvar org-tab-after-check-for-cycling-hook nil
17877 "Hook for functions to attach themselves to TAB.
17878 See `org-ctrl-c-ctrl-c-hook' for more information.
17879 This hook runs after it has been established that not table field motion and
17880 not visibility should be done because of current context. This is probably
17881 the place where a package like yasnippets can hook in.")
17883 (defvar org-tab-before-tab-emulation-hook nil
17884 "Hook for functions to attach themselves to TAB.
17885 See `org-ctrl-c-ctrl-c-hook' for more information.
17886 This hook runs after every other options for TAB have been exhausted, but
17887 before indentation and \t insertion takes place.")
17889 (defvar org-metaleft-hook nil
17890 "Hook for functions attaching themselves to `M-left'.
17891 See `org-ctrl-c-ctrl-c-hook' for more information.")
17892 (defvar org-metaright-hook nil
17893 "Hook for functions attaching themselves to `M-right'.
17894 See `org-ctrl-c-ctrl-c-hook' for more information.")
17895 (defvar org-metaup-hook nil
17896 "Hook for functions attaching themselves to `M-up'.
17897 See `org-ctrl-c-ctrl-c-hook' for more information.")
17898 (defvar org-metadown-hook nil
17899 "Hook for functions attaching themselves to `M-down'.
17900 See `org-ctrl-c-ctrl-c-hook' for more information.")
17901 (defvar org-shiftmetaleft-hook nil
17902 "Hook for functions attaching themselves to `M-S-left'.
17903 See `org-ctrl-c-ctrl-c-hook' for more information.")
17904 (defvar org-shiftmetaright-hook nil
17905 "Hook for functions attaching themselves to `M-S-right'.
17906 See `org-ctrl-c-ctrl-c-hook' for more information.")
17907 (defvar org-shiftmetaup-hook nil
17908 "Hook for functions attaching themselves to `M-S-up'.
17909 See `org-ctrl-c-ctrl-c-hook' for more information.")
17910 (defvar org-shiftmetadown-hook nil
17911 "Hook for functions attaching themselves to `M-S-down'.
17912 See `org-ctrl-c-ctrl-c-hook' for more information.")
17913 (defvar org-metareturn-hook nil
17914 "Hook for functions attaching themselves to `M-RET'.
17915 See `org-ctrl-c-ctrl-c-hook' for more information.")
17916 (defvar org-shiftup-hook nil
17917 "Hook for functions attaching themselves to `S-up'.
17918 See `org-ctrl-c-ctrl-c-hook' for more information.")
17919 (defvar org-shiftup-final-hook nil
17920 "Hook for functions attaching themselves to `S-up'.
17921 This one runs after all other options except shift-select have been excluded.
17922 See `org-ctrl-c-ctrl-c-hook' for more information.")
17923 (defvar org-shiftdown-hook nil
17924 "Hook for functions attaching themselves to `S-down'.
17925 See `org-ctrl-c-ctrl-c-hook' for more information.")
17926 (defvar org-shiftdown-final-hook nil
17927 "Hook for functions attaching themselves to `S-down'.
17928 This one runs after all other options except shift-select have been excluded.
17929 See `org-ctrl-c-ctrl-c-hook' for more information.")
17930 (defvar org-shiftleft-hook nil
17931 "Hook for functions attaching themselves to `S-left'.
17932 See `org-ctrl-c-ctrl-c-hook' for more information.")
17933 (defvar org-shiftleft-final-hook nil
17934 "Hook for functions attaching themselves to `S-left'.
17935 This one runs after all other options except shift-select have been excluded.
17936 See `org-ctrl-c-ctrl-c-hook' for more information.")
17937 (defvar org-shiftright-hook nil
17938 "Hook for functions attaching themselves to `S-right'.
17939 See `org-ctrl-c-ctrl-c-hook' for more information.")
17940 (defvar org-shiftright-final-hook nil
17941 "Hook for functions attaching themselves to `S-right'.
17942 This one runs after all other options except shift-select have been excluded.
17943 See `org-ctrl-c-ctrl-c-hook' for more information.")
17945 (defun org-modifier-cursor-error ()
17946 "Throw an error, a modified cursor command was applied in wrong context."
17947 (error "This command is active in special context like tables, headlines or items"))
17949 (defun org-shiftselect-error ()
17950 "Throw an error because Shift-Cursor command was applied in wrong context."
17951 (if (and (boundp 'shift-select-mode) shift-select-mode)
17952 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17953 (error "This command works only in special context like headlines or timestamps")))
17955 (defun org-call-for-shift-select (cmd)
17956 (let ((this-command-keys-shift-translated t))
17957 (call-interactively cmd)))
17959 (defun org-shifttab (&optional arg)
17960 "Global visibility cycling or move to previous table field.
17961 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17962 on context.
17963 See the individual commands for more information."
17964 (interactive "P")
17965 (cond
17966 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17967 ((integerp arg)
17968 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17969 (message "Content view to level: %d" arg)
17970 (org-content (prefix-numeric-value arg2))
17971 (setq org-cycle-global-status 'overview)))
17972 (t (call-interactively 'org-global-cycle))))
17974 (defun org-shiftmetaleft ()
17975 "Promote subtree or delete table column.
17976 Calls `org-promote-subtree', `org-outdent-item',
17977 or `org-table-delete-column', depending on context.
17978 See the individual commands for more information."
17979 (interactive)
17980 (cond
17981 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17982 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17983 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17984 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17985 (t (org-modifier-cursor-error))))
17987 (defun org-shiftmetaright ()
17988 "Demote subtree or insert table column.
17989 Calls `org-demote-subtree', `org-indent-item',
17990 or `org-table-insert-column', depending on context.
17991 See the individual commands for more information."
17992 (interactive)
17993 (cond
17994 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17995 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17996 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
17997 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17998 (t (org-modifier-cursor-error))))
18000 (defun org-shiftmetaup (&optional arg)
18001 "Move subtree up or kill table row.
18002 Calls `org-move-subtree-up' or `org-table-kill-row' or
18003 `org-move-item-up' depending on context. See the individual commands
18004 for more information."
18005 (interactive "P")
18006 (cond
18007 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18008 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18009 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18010 ((org-at-item-p) (call-interactively 'org-move-item-up))
18011 (t (org-modifier-cursor-error))))
18013 (defun org-shiftmetadown (&optional arg)
18014 "Move subtree down or insert table row.
18015 Calls `org-move-subtree-down' or `org-table-insert-row' or
18016 `org-move-item-down', depending on context. See the individual
18017 commands for more information."
18018 (interactive "P")
18019 (cond
18020 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18021 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18022 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18023 ((org-at-item-p) (call-interactively 'org-move-item-down))
18024 (t (org-modifier-cursor-error))))
18026 (defsubst org-hidden-tree-error ()
18027 (error
18028 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18030 (defun org-metaleft (&optional arg)
18031 "Promote heading or move table column to left.
18032 Calls `org-do-promote' or `org-table-move-column', depending on context.
18033 With no specific context, calls the Emacs default `backward-word'.
18034 See the individual commands for more information."
18035 (interactive "P")
18036 (cond
18037 ((run-hook-with-args-until-success 'org-metaleft-hook))
18038 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18039 ((org-with-limited-levels
18040 (or (org-at-heading-p)
18041 (and (org-region-active-p)
18042 (save-excursion
18043 (goto-char (region-beginning))
18044 (org-at-heading-p)))))
18045 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18046 (call-interactively 'org-do-promote))
18047 ;; At an inline task.
18048 ((org-at-heading-p)
18049 (call-interactively 'org-inlinetask-promote))
18050 ((or (org-at-item-p)
18051 (and (org-region-active-p)
18052 (save-excursion
18053 (goto-char (region-beginning))
18054 (org-at-item-p))))
18055 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18056 (call-interactively 'org-outdent-item))
18057 (t (call-interactively 'backward-word))))
18059 (defun org-metaright (&optional arg)
18060 "Demote subtree or move table column to right.
18061 Calls `org-do-demote' or `org-table-move-column', depending on context.
18062 With no specific context, calls the Emacs default `forward-word'.
18063 See the individual commands for more information."
18064 (interactive "P")
18065 (cond
18066 ((run-hook-with-args-until-success 'org-metaright-hook))
18067 ((org-at-table-p) (call-interactively 'org-table-move-column))
18068 ((org-with-limited-levels
18069 (or (org-at-heading-p)
18070 (and (org-region-active-p)
18071 (save-excursion
18072 (goto-char (region-beginning))
18073 (org-at-heading-p)))))
18074 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18075 (call-interactively 'org-do-demote))
18076 ;; At an inline task.
18077 ((org-at-heading-p)
18078 (call-interactively 'org-inlinetask-demote))
18079 ((or (org-at-item-p)
18080 (and (org-region-active-p)
18081 (save-excursion
18082 (goto-char (region-beginning))
18083 (org-at-item-p))))
18084 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18085 (call-interactively 'org-indent-item))
18086 (t (call-interactively 'forward-word))))
18088 (defun org-check-for-hidden (what)
18089 "Check if there are hidden headlines/items in the current visual line.
18090 WHAT can be either `headlines' or `items'. If the current line is
18091 an outline or item heading and it has a folded subtree below it,
18092 this function returns t, nil otherwise."
18093 (let ((re (cond
18094 ((eq what 'headlines) org-outline-regexp-bol)
18095 ((eq what 'items) (org-item-beginning-re))
18096 (t (error "This should not happen"))))
18097 beg end)
18098 (save-excursion
18099 (catch 'exit
18100 (unless (org-region-active-p)
18101 (setq beg (point-at-bol))
18102 (beginning-of-line 2)
18103 (while (and (not (eobp)) ;; this is like `next-line'
18104 (get-char-property (1- (point)) 'invisible))
18105 (beginning-of-line 2))
18106 (setq end (point))
18107 (goto-char beg)
18108 (goto-char (point-at-eol))
18109 (setq end (max end (point)))
18110 (while (re-search-forward re end t)
18111 (if (get-char-property (match-beginning 0) 'invisible)
18112 (throw 'exit t))))
18113 nil))))
18115 (defun org-metaup (&optional arg)
18116 "Move subtree up or move table row up.
18117 Calls `org-move-subtree-up' or `org-table-move-row' or
18118 `org-move-item-up', depending on context. See the individual commands
18119 for more information."
18120 (interactive "P")
18121 (cond
18122 ((run-hook-with-args-until-success 'org-metaup-hook))
18123 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18124 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18125 ((org-at-item-p) (call-interactively 'org-move-item-up))
18126 (t (transpose-lines 1) (beginning-of-line -1))))
18128 (defun org-metadown (&optional arg)
18129 "Move subtree down or move table row down.
18130 Calls `org-move-subtree-down' or `org-table-move-row' or
18131 `org-move-item-down', depending on context. See the individual
18132 commands for more information."
18133 (interactive "P")
18134 (cond
18135 ((run-hook-with-args-until-success 'org-metadown-hook))
18136 ((org-at-table-p) (call-interactively 'org-table-move-row))
18137 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18138 ((org-at-item-p) (call-interactively 'org-move-item-down))
18139 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18141 (defun org-shiftup (&optional arg)
18142 "Increase item in timestamp or increase priority of current headline.
18143 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18144 depending on context. See the individual commands for more information."
18145 (interactive "P")
18146 (cond
18147 ((run-hook-with-args-until-success 'org-shiftup-hook))
18148 ((and org-support-shift-select (org-region-active-p))
18149 (org-call-for-shift-select 'previous-line))
18150 ((org-at-timestamp-p t)
18151 (call-interactively (if org-edit-timestamp-down-means-later
18152 'org-timestamp-down 'org-timestamp-up)))
18153 ((and (not (eq org-support-shift-select 'always))
18154 org-enable-priority-commands
18155 (org-at-heading-p))
18156 (call-interactively 'org-priority-up))
18157 ((and (not org-support-shift-select) (org-at-item-p))
18158 (call-interactively 'org-previous-item))
18159 ((org-clocktable-try-shift 'up arg))
18160 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18161 (org-support-shift-select
18162 (org-call-for-shift-select 'previous-line))
18163 (t (org-shiftselect-error))))
18165 (defun org-shiftdown (&optional arg)
18166 "Decrease item in timestamp or decrease priority of current headline.
18167 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18168 depending on context. See the individual commands for more information."
18169 (interactive "P")
18170 (cond
18171 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18172 ((and org-support-shift-select (org-region-active-p))
18173 (org-call-for-shift-select 'next-line))
18174 ((org-at-timestamp-p t)
18175 (call-interactively (if org-edit-timestamp-down-means-later
18176 'org-timestamp-up 'org-timestamp-down)))
18177 ((and (not (eq org-support-shift-select 'always))
18178 org-enable-priority-commands
18179 (org-at-heading-p))
18180 (call-interactively 'org-priority-down))
18181 ((and (not org-support-shift-select) (org-at-item-p))
18182 (call-interactively 'org-next-item))
18183 ((org-clocktable-try-shift 'down arg))
18184 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18185 (org-support-shift-select
18186 (org-call-for-shift-select 'next-line))
18187 (t (org-shiftselect-error))))
18189 (defun org-shiftright (&optional arg)
18190 "Cycle the thing at point or in the current line, depending on context.
18191 Depending on context, this does one of the following:
18193 - switch a timestamp at point one day into the future
18194 - on a headline, switch to the next TODO keyword.
18195 - on an item, switch entire list to the next bullet type
18196 - on a property line, switch to the next allowed value
18197 - on a clocktable definition line, move time block into the future"
18198 (interactive "P")
18199 (cond
18200 ((run-hook-with-args-until-success 'org-shiftright-hook))
18201 ((and org-support-shift-select (org-region-active-p))
18202 (org-call-for-shift-select 'forward-char))
18203 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18204 ((and (not (eq org-support-shift-select 'always))
18205 (org-at-heading-p))
18206 (let ((org-inhibit-logging
18207 (not org-treat-S-cursor-todo-selection-as-state-change))
18208 (org-inhibit-blocking
18209 (not org-treat-S-cursor-todo-selection-as-state-change)))
18210 (org-call-with-arg 'org-todo 'right)))
18211 ((or (and org-support-shift-select
18212 (not (eq org-support-shift-select 'always))
18213 (org-at-item-bullet-p))
18214 (and (not org-support-shift-select) (org-at-item-p)))
18215 (org-call-with-arg 'org-cycle-list-bullet nil))
18216 ((and (not (eq org-support-shift-select 'always))
18217 (org-at-property-p))
18218 (call-interactively 'org-property-next-allowed-value))
18219 ((org-clocktable-try-shift 'right arg))
18220 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18221 (org-support-shift-select
18222 (org-call-for-shift-select 'forward-char))
18223 (t (org-shiftselect-error))))
18225 (defun org-shiftleft (&optional arg)
18226 "Cycle the thing at point or in the current line, depending on context.
18227 Depending on context, this does one of the following:
18229 - switch a timestamp at point one day into the past
18230 - on a headline, switch to the previous TODO keyword.
18231 - on an item, switch entire list to the previous bullet type
18232 - on a property line, switch to the previous allowed value
18233 - on a clocktable definition line, move time block into the past"
18234 (interactive "P")
18235 (cond
18236 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18237 ((and org-support-shift-select (org-region-active-p))
18238 (org-call-for-shift-select 'backward-char))
18239 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18240 ((and (not (eq org-support-shift-select 'always))
18241 (org-at-heading-p))
18242 (let ((org-inhibit-logging
18243 (not org-treat-S-cursor-todo-selection-as-state-change))
18244 (org-inhibit-blocking
18245 (not org-treat-S-cursor-todo-selection-as-state-change)))
18246 (org-call-with-arg 'org-todo 'left)))
18247 ((or (and org-support-shift-select
18248 (not (eq org-support-shift-select 'always))
18249 (org-at-item-bullet-p))
18250 (and (not org-support-shift-select) (org-at-item-p)))
18251 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18252 ((and (not (eq org-support-shift-select 'always))
18253 (org-at-property-p))
18254 (call-interactively 'org-property-previous-allowed-value))
18255 ((org-clocktable-try-shift 'left arg))
18256 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18257 (org-support-shift-select
18258 (org-call-for-shift-select 'backward-char))
18259 (t (org-shiftselect-error))))
18261 (defun org-shiftcontrolright ()
18262 "Switch to next TODO set."
18263 (interactive)
18264 (cond
18265 ((and org-support-shift-select (org-region-active-p))
18266 (org-call-for-shift-select 'forward-word))
18267 ((and (not (eq org-support-shift-select 'always))
18268 (org-at-heading-p))
18269 (org-call-with-arg 'org-todo 'nextset))
18270 (org-support-shift-select
18271 (org-call-for-shift-select 'forward-word))
18272 (t (org-shiftselect-error))))
18274 (defun org-shiftcontrolleft ()
18275 "Switch to previous TODO set."
18276 (interactive)
18277 (cond
18278 ((and org-support-shift-select (org-region-active-p))
18279 (org-call-for-shift-select 'backward-word))
18280 ((and (not (eq org-support-shift-select 'always))
18281 (org-at-heading-p))
18282 (org-call-with-arg 'org-todo 'previousset))
18283 (org-support-shift-select
18284 (org-call-for-shift-select 'backward-word))
18285 (t (org-shiftselect-error))))
18287 (defun org-shiftcontrolup ()
18288 "Change timestamps synchronously up in CLOCK log lines."
18289 (interactive)
18290 (cond ((and (not org-support-shift-select)
18291 (org-at-clock-log-p)
18292 (org-at-timestamp-p t))
18293 (org-clock-timestamps-up))
18294 (t (org-shiftselect-error))))
18296 (defun org-shiftcontroldown ()
18297 "Change timestamps synchronously down in CLOCK log lines."
18298 (interactive)
18299 (cond ((and (not org-support-shift-select)
18300 (org-at-clock-log-p)
18301 (org-at-timestamp-p t))
18302 (org-clock-timestamps-down))
18303 (t (org-shiftselect-error))))
18305 (defun org-ctrl-c-ret ()
18306 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18307 (interactive)
18308 (cond
18309 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18310 (t (call-interactively 'org-insert-heading))))
18312 (defun org-find-visible ()
18313 (let ((s (point)))
18314 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18315 (get-char-property s 'invisible)))
18317 (defun org-find-invisible ()
18318 (let ((s (point)))
18319 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18320 (not (get-char-property s 'invisible))))
18323 (defun org-copy-visible (beg end)
18324 "Copy the visible parts of the region."
18325 (interactive "r")
18326 (let (snippets s)
18327 (save-excursion
18328 (save-restriction
18329 (narrow-to-region beg end)
18330 (setq s (goto-char (point-min)))
18331 (while (not (= (point) (point-max)))
18332 (goto-char (org-find-invisible))
18333 (push (buffer-substring s (point)) snippets)
18334 (setq s (goto-char (org-find-visible))))))
18335 (kill-new (apply 'concat (nreverse snippets)))))
18337 (defun org-copy-special ()
18338 "Copy region in table or copy current subtree.
18339 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18340 See the individual commands for more information."
18341 (interactive)
18342 (call-interactively
18343 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18345 (defun org-cut-special ()
18346 "Cut region in table or cut current subtree.
18347 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18348 See the individual commands for more information."
18349 (interactive)
18350 (call-interactively
18351 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18353 (defun org-paste-special (arg)
18354 "Paste rectangular region into table, or past subtree relative to level.
18355 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18356 See the individual commands for more information."
18357 (interactive "P")
18358 (if (org-at-table-p)
18359 (org-table-paste-rectangle)
18360 (org-paste-subtree arg)))
18362 (defun org-edit-special (&optional arg)
18363 "Call a special editor for the stuff at point.
18364 When at a table, call the formula editor with `org-table-edit-formulas'.
18365 When at the first line of an src example, call `org-edit-src-code'.
18366 When in an #+include line, visit the include file. Otherwise call
18367 `ffap' to visit the file at point."
18368 (interactive)
18369 ;; possibly prep session before editing source
18370 (when arg
18371 (let* ((info (org-babel-get-src-block-info))
18372 (lang (nth 0 info))
18373 (params (nth 2 info))
18374 (session (cdr (assoc :session params))))
18375 (when (and info session) ;; we are in a source-code block with a session
18376 (funcall
18377 (intern (concat "org-babel-prep-session:" lang)) session params))))
18378 (cond ;; proceed with `org-edit-special'
18379 ((save-excursion
18380 (beginning-of-line 1)
18381 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18382 (find-file (org-trim (match-string 1))))
18383 ((org-edit-src-code))
18384 ((org-edit-fixed-width-region))
18385 ((org-at-table.el-p)
18386 (org-edit-src-code))
18387 ((or (org-at-table-p)
18388 (save-excursion
18389 (beginning-of-line 1)
18390 (looking-at "[ \t]*#\\+TBLFM:")))
18391 (call-interactively 'org-table-edit-formulas))
18392 (t (call-interactively 'ffap))))
18394 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18395 (defun org-ctrl-c-ctrl-c (&optional arg)
18396 "Set tags in headline, or update according to changed information at point.
18398 This command does many different things, depending on context:
18400 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18401 this is what we do.
18403 - If the cursor is on a statistics cookie, update it.
18405 - If the cursor is in a headline, prompt for tags and insert them
18406 into the current line, aligned to `org-tags-column'. When called
18407 with prefix arg, realign all tags in the current buffer.
18409 - If the cursor is in one of the special #+KEYWORD lines, this
18410 triggers scanning the buffer for these lines and updating the
18411 information.
18413 - If the cursor is inside a table, realign the table. This command
18414 works even if the automatic table editor has been turned off.
18416 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18417 the entire table.
18419 - If the cursor is at a footnote reference or definition, jump to
18420 the corresponding definition or references, respectively.
18422 - If the cursor is a the beginning of a dynamic block, update it.
18424 - If the current buffer is a capture buffer, close note and file it.
18426 - If the cursor is on a <<<target>>>, update radio targets and
18427 corresponding links in this buffer.
18429 - If the cursor is on a numbered item in a plain list, renumber the
18430 ordered list.
18432 - If the cursor is on a checkbox, toggle it.
18434 - If the cursor is on a code block, evaluate it. The variable
18435 `org-confirm-babel-evaluate' can be used to control prompting
18436 before code block evaluation, by default every code block
18437 evaluation requires confirmation. Code block evaluation can be
18438 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18439 (interactive "P")
18440 (let ((org-enable-table-editor t))
18441 (cond
18442 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18443 org-occur-highlights
18444 org-latex-fragment-image-overlays)
18445 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18446 (org-remove-occur-highlights)
18447 (org-remove-latex-fragment-image-overlays)
18448 (message "Temporary highlights/overlays removed from current buffer"))
18449 ((and (local-variable-p 'org-finish-function (current-buffer))
18450 (fboundp org-finish-function))
18451 (funcall org-finish-function))
18452 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18453 ((org-in-regexp org-ts-regexp-both)
18454 (org-timestamp-change 0 'day))
18455 ((or (looking-at org-property-start-re)
18456 (org-at-property-p))
18457 (call-interactively 'org-property-action))
18458 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18459 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18460 (or (org-at-heading-p) (org-at-item-p)))
18461 (call-interactively 'org-update-statistics-cookies))
18462 ((org-at-heading-p) (call-interactively 'org-set-tags))
18463 ((org-at-table.el-p)
18464 (message "Use C-c ' to edit table.el tables"))
18465 ((org-at-table-p)
18466 (org-table-maybe-eval-formula)
18467 (if arg
18468 (call-interactively 'org-table-recalculate)
18469 (org-table-maybe-recalculate-line))
18470 (call-interactively 'org-table-align)
18471 (orgtbl-send-table 'maybe))
18472 ((or (org-footnote-at-reference-p)
18473 (org-footnote-at-definition-p))
18474 (call-interactively 'org-footnote-action))
18475 ((org-at-item-checkbox-p)
18476 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18477 ;; list only if at top item.
18478 (let* ((cbox (match-string 1))
18479 (struct (org-list-struct))
18480 (old-struct (copy-tree struct))
18481 (parents (org-list-parents-alist struct))
18482 (orderedp (org-entry-get nil "ORDERED"))
18483 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18484 block-item)
18485 ;; Use a light version of `org-toggle-checkbox' to avoid
18486 ;; computing list structure twice.
18487 (let ((new-box (cond
18488 ((equal arg '(16)) "[-]")
18489 ((equal arg '(4)) nil)
18490 ((equal "[X]" cbox) "[ ]")
18491 (t "[X]"))))
18492 (if (and firstp arg)
18493 ;; If at first item of sub-list, remove check-box from
18494 ;; every item at the same level.
18495 (mapc
18496 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18497 (org-list-get-all-items
18498 (point-at-bol) struct (org-list-prevs-alist struct)))
18499 (org-list-set-checkbox (point-at-bol) struct new-box)))
18500 ;; Replicate `org-list-write-struct', while grabbing a return
18501 ;; value from `org-list-struct-fix-box'.
18502 (org-list-struct-fix-ind struct parents 2)
18503 (org-list-struct-fix-item-end struct)
18504 (let ((prevs (org-list-prevs-alist struct)))
18505 (org-list-struct-fix-bul struct prevs)
18506 (org-list-struct-fix-ind struct parents)
18507 (setq block-item
18508 (org-list-struct-fix-box struct parents prevs orderedp)))
18509 (org-list-struct-apply-struct struct old-struct)
18510 (org-update-checkbox-count-maybe)
18511 (when block-item
18512 (message
18513 "Checkboxes were removed due to unchecked box at line %d"
18514 (org-current-line block-item)))
18515 (when firstp (org-list-send-list 'maybe))))
18516 ((org-at-item-p)
18517 ;; Cursor at an item: repair list. Do checkbox related actions
18518 ;; only if function was called with an argument. Send list only
18519 ;; if at top item.
18520 (let* ((struct (org-list-struct))
18521 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18522 old-struct)
18523 (when arg
18524 (setq old-struct (copy-tree struct))
18525 (if firstp
18526 ;; If at first item of sub-list, add check-box to every
18527 ;; item at the same level.
18528 (mapc
18529 (lambda (pos)
18530 (unless (org-list-get-checkbox pos struct)
18531 (org-list-set-checkbox pos struct "[ ]")))
18532 (org-list-get-all-items
18533 (point-at-bol) struct (org-list-prevs-alist struct)))
18534 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18535 (org-list-write-struct
18536 struct (org-list-parents-alist struct) old-struct)
18537 (when arg (org-update-checkbox-count-maybe))
18538 (when firstp (org-list-send-list 'maybe))))
18539 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18540 ;; Dynamic block
18541 (beginning-of-line 1)
18542 (save-excursion (org-update-dblock)))
18543 ((save-excursion
18544 (beginning-of-line 1)
18545 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18546 (cond
18547 ((equal (match-string 1) "TBLFM")
18548 ;; Recalculate the table before this line
18549 (save-excursion
18550 (beginning-of-line 1)
18551 (skip-chars-backward " \r\n\t")
18552 (if (org-at-table-p)
18553 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18555 (let ((org-inhibit-startup-visibility-stuff t)
18556 (org-startup-align-all-tables nil))
18557 (when (boundp 'org-table-coordinate-overlays)
18558 (mapc 'delete-overlay org-table-coordinate-overlays)
18559 (setq org-table-coordinate-overlays nil))
18560 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18561 (message "Local setup has been refreshed"))))
18562 ((org-clock-update-time-maybe))
18564 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18565 (error "C-c C-c can do nothing useful at this location"))))))
18567 (defun org-mode-restart ()
18568 "Restart Org-mode, to scan again for special lines.
18569 Also updates the keyword regular expressions."
18570 (interactive)
18571 (org-mode)
18572 (message "Org-mode restarted"))
18574 (defun org-kill-note-or-show-branches ()
18575 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18576 (interactive)
18577 (if (not org-finish-function)
18578 (progn
18579 (hide-subtree)
18580 (call-interactively 'show-branches))
18581 (let ((org-note-abort t))
18582 (funcall org-finish-function))))
18584 (defun org-return (&optional indent)
18585 "Goto next table row or insert a newline.
18586 Calls `org-table-next-row' or `newline', depending on context.
18587 See the individual commands for more information."
18588 (interactive)
18589 (cond
18590 ((bobp) (if indent (newline-and-indent) (newline)))
18591 ((org-at-table-p)
18592 (org-table-justify-field-maybe)
18593 (call-interactively 'org-table-next-row))
18594 ;; when `newline-and-indent' is called within a list, make sure
18595 ;; text moved stays inside the item.
18596 ((and (org-in-item-p) indent)
18597 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18598 (progn
18599 (save-match-data (newline))
18600 (org-indent-line-to (length (match-string 0))))
18601 (let ((ind (org-get-indentation)))
18602 (newline)
18603 (if (org-looking-back org-list-end-re)
18604 (org-indent-line-function)
18605 (org-indent-line-to ind)))))
18606 ((and org-return-follows-link
18607 (let ((tprop (get-text-property (point) 'face)))
18608 (or (eq tprop 'org-link)
18609 (and (listp tprop) (memq 'org-link tprop)))))
18610 (call-interactively 'org-open-at-point))
18611 ((and (org-at-heading-p)
18612 (looking-at
18613 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18614 (org-show-entry)
18615 (end-of-line 1)
18616 (newline))
18617 (t (if indent (newline-and-indent) (newline)))))
18619 (defun org-return-indent ()
18620 "Goto next table row or insert a newline and indent.
18621 Calls `org-table-next-row' or `newline-and-indent', depending on
18622 context. See the individual commands for more information."
18623 (interactive)
18624 (org-return t))
18626 (defun org-ctrl-c-star ()
18627 "Compute table, or change heading status of lines.
18628 Calls `org-table-recalculate' or `org-toggle-heading',
18629 depending on context."
18630 (interactive)
18631 (cond
18632 ((org-at-table-p)
18633 (call-interactively 'org-table-recalculate))
18635 ;; Convert all lines in region to list items
18636 (call-interactively 'org-toggle-heading))))
18638 (defun org-ctrl-c-minus ()
18639 "Insert separator line in table or modify bullet status of line.
18640 Also turns a plain line or a region of lines into list items.
18641 Calls `org-table-insert-hline', `org-toggle-item', or
18642 `org-cycle-list-bullet', depending on context."
18643 (interactive)
18644 (cond
18645 ((org-at-table-p)
18646 (call-interactively 'org-table-insert-hline))
18647 ((org-region-active-p)
18648 (call-interactively 'org-toggle-item))
18649 ((org-in-item-p)
18650 (call-interactively 'org-cycle-list-bullet))
18652 (call-interactively 'org-toggle-item))))
18654 (defun org-toggle-item (arg)
18655 "Convert headings or normal lines to items, items to normal lines.
18656 If there is no active region, only the current line is considered.
18658 If the first non blank line in the region is an headline, convert
18659 all headlines to items, shifting text accordingly.
18661 If it is an item, convert all items to normal lines.
18663 If it is normal text, change region into an item. With a prefix
18664 argument ARG, change each line in region into an item."
18665 (interactive "P")
18666 (let ((shift-text
18667 (function
18668 ;; Shift text in current section to IND, from point to END.
18669 ;; The function leaves point to END line.
18670 (lambda (ind end)
18671 (let ((min-i 1000) (end (copy-marker end)))
18672 ;; First determine the minimum indentation (MIN-I) of
18673 ;; the text.
18674 (save-excursion
18675 (catch 'exit
18676 (while (< (point) end)
18677 (let ((i (org-get-indentation)))
18678 (cond
18679 ;; Skip blank lines and inline tasks.
18680 ((looking-at "^[ \t]*$"))
18681 ((looking-at org-outline-regexp-bol))
18682 ;; We can't find less than 0 indentation.
18683 ((zerop i) (throw 'exit (setq min-i 0)))
18684 ((< i min-i) (setq min-i i))))
18685 (forward-line))))
18686 ;; Then indent each line so that a line indented to
18687 ;; MIN-I becomes indented to IND. Ignore blank lines
18688 ;; and inline tasks in the process.
18689 (let ((delta (- ind min-i)))
18690 (while (< (point) end)
18691 (unless (or (looking-at "^[ \t]*$")
18692 (looking-at org-outline-regexp-bol))
18693 (org-indent-line-to (+ (org-get-indentation) delta)))
18694 (forward-line)))))))
18695 (skip-blanks
18696 (function
18697 ;; Return beginning of first non-blank line, starting from
18698 ;; line at POS.
18699 (lambda (pos)
18700 (save-excursion
18701 (goto-char pos)
18702 (skip-chars-forward " \r\t\n")
18703 (point-at-bol)))))
18704 beg end)
18705 ;; Determine boundaries of changes.
18706 (if (org-region-active-p)
18707 (setq beg (funcall skip-blanks (region-beginning))
18708 end (copy-marker (region-end)))
18709 (setq beg (funcall skip-blanks (point-at-bol))
18710 end (copy-marker (point-at-eol))))
18711 ;; Depending on the starting line, choose an action on the text
18712 ;; between BEG and END.
18713 (org-with-limited-levels
18714 (save-excursion
18715 (goto-char beg)
18716 (cond
18717 ;; Case 1. Start at an item: de-itemize. Note that it only
18718 ;; happens when a region is active: `org-ctrl-c-minus'
18719 ;; would call `org-cycle-list-bullet' otherwise.
18720 ((org-at-item-p)
18721 (while (< (point) end)
18722 (when (org-at-item-p)
18723 (skip-chars-forward " \t")
18724 (delete-region (point) (match-end 0)))
18725 (forward-line)))
18726 ;; Case 2. Start at an heading: convert to items.
18727 ((org-at-heading-p)
18728 (let* ((bul (org-list-bullet-string "-"))
18729 (bul-len (length bul))
18730 ;; Indentation of the first heading. It should be
18731 ;; relative to the indentation of its parent, if any.
18732 (start-ind (save-excursion
18733 (cond
18734 ((not org-adapt-indentation) 0)
18735 ((not (outline-previous-heading)) 0)
18736 (t (length (match-string 0))))))
18737 ;; Level of first heading. Further headings will be
18738 ;; compared to it to determine hierarchy in the list.
18739 (ref-level (org-reduced-level (org-outline-level))))
18740 (while (< (point) end)
18741 (let* ((level (org-reduced-level (org-outline-level)))
18742 (delta (max 0 (- level ref-level))))
18743 ;; If current headline is less indented than the first
18744 ;; one, set it as reference, in order to preserve
18745 ;; subtrees.
18746 (when (< level ref-level) (setq ref-level level))
18747 (replace-match bul t t)
18748 (org-indent-line-to (+ start-ind (* delta bul-len)))
18749 ;; Ensure all text down to END (or SECTION-END) belongs
18750 ;; to the newly created item.
18751 (let ((section-end (save-excursion
18752 (or (outline-next-heading) (point)))))
18753 (forward-line)
18754 (funcall shift-text
18755 (+ start-ind (* (1+ delta) bul-len))
18756 (min end section-end)))))))
18757 ;; Case 3. Normal line with ARG: turn each non-item line into
18758 ;; an item.
18759 (arg
18760 (while (< (point) end)
18761 (unless (or (org-at-heading-p) (org-at-item-p))
18762 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18763 (replace-match
18764 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18765 (forward-line)))
18766 ;; Case 4. Normal line without ARG: make the first line of
18767 ;; region an item, and shift indentation of others
18768 ;; lines to set them as item's body.
18769 (t (let* ((bul (org-list-bullet-string "-"))
18770 (bul-len (length bul))
18771 (ref-ind (org-get-indentation)))
18772 (skip-chars-forward " \t")
18773 (insert bul)
18774 (forward-line)
18775 (while (< (point) end)
18776 ;; Ensure that lines less indented than first one
18777 ;; still get included in item body.
18778 (funcall shift-text
18779 (+ ref-ind bul-len)
18780 (min end (save-excursion (or (outline-next-heading)
18781 (point)))))
18782 (forward-line)))))))))
18784 (defun org-toggle-heading (&optional nstars)
18785 "Convert headings to normal text, or items or text to headings.
18786 If there is no active region, only the current line is considered.
18788 If the first non blank line is an headline, remove the stars from
18789 all headlines in the region.
18791 If it is a plain list item, turn all plain list items into headings.
18793 If it is a normal line, turn each and every normal line (i.e. not
18794 an heading or an item) in the region into a heading.
18796 When converting a line into a heading, the number of stars is chosen
18797 such that the lines become children of the current entry. However,
18798 when a prefix argument is given, its value determines the number of
18799 stars to add."
18800 (interactive "P")
18801 (let ((skip-blanks
18802 (function
18803 ;; Return beginning of first non-blank line, starting from
18804 ;; line at POS.
18805 (lambda (pos)
18806 (save-excursion
18807 (goto-char pos)
18808 (skip-chars-forward " \r\t\n")
18809 (point-at-bol)))))
18810 beg end)
18811 ;; Determine boundaries of changes. If region ends at a bol, do
18812 ;; not consider the last line to be in the region.
18813 (if (org-region-active-p)
18814 (setq beg (funcall skip-blanks (region-beginning))
18815 end (copy-marker (save-excursion
18816 (goto-char (region-end))
18817 (if (bolp) (point) (point-at-eol)))))
18818 (setq beg (funcall skip-blanks (point-at-bol))
18819 end (copy-marker (point-at-eol))))
18820 ;; Ensure inline tasks don't count as headings.
18821 (org-with-limited-levels
18822 (save-excursion
18823 (goto-char beg)
18824 (cond
18825 ;; Case 1. Started at an heading: de-star headings.
18826 ((org-at-heading-p)
18827 (while (< (point) end)
18828 (when (org-at-heading-p t)
18829 (looking-at org-outline-regexp) (replace-match ""))
18830 (forward-line)))
18831 ;; Case 2. Started at an item: change items into headlines.
18832 ;; One star will be added by `org-list-to-subtree'.
18833 ((org-at-item-p)
18834 (let* ((stars (make-string
18835 (if nstars
18836 ;; subtract the star that will be added again by
18837 ;; `org-list-to-subtree'
18838 (1- (prefix-numeric-value current-prefix-arg))
18839 (or (org-current-level) 0))
18840 ?*))
18841 (add-stars
18842 (cond (nstars "") ; stars from prefix only
18843 ((equal stars "") "") ; before first heading
18844 (org-odd-levels-only "*") ; inside heading, odd
18845 (t "")))) ; inside heading, oddeven
18846 (while (< (point) end)
18847 (when (org-at-item-p)
18848 ;; Pay attention to cases when region ends before list.
18849 (let* ((struct (org-list-struct))
18850 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18851 (save-restriction
18852 (narrow-to-region (point) list-end)
18853 (insert
18854 (org-list-to-subtree
18855 (org-list-parse-list t)
18856 '(:istart (concat stars add-stars (funcall get-stars depth))
18857 :icount (concat stars add-stars (funcall get-stars depth))))))))
18858 (forward-line))))
18859 ;; Case 3. Started at normal text: make every line an heading,
18860 ;; skipping headlines and items.
18861 (t (let* ((stars (make-string
18862 (if nstars
18863 (prefix-numeric-value current-prefix-arg)
18864 (or (org-current-level) 0))
18865 ?*))
18866 (add-stars
18867 (cond (nstars "") ; stars from prefix only
18868 ((equal stars "") "*") ; before first heading
18869 (org-odd-levels-only "**") ; inside heading, odd
18870 (t "*"))) ; inside heading, oddeven
18871 (rpl (concat stars add-stars " ")))
18872 (while (< (point) end)
18873 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18874 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18875 (replace-match (concat rpl (match-string 2))))
18876 (forward-line)))))))))
18878 (defun org-meta-return (&optional arg)
18879 "Insert a new heading or wrap a region in a table.
18880 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18881 See the individual commands for more information."
18882 (interactive "P")
18883 (cond
18884 ((run-hook-with-args-until-success 'org-metareturn-hook))
18885 ((org-at-table-p)
18886 (call-interactively 'org-table-wrap-region))
18887 (t (call-interactively 'org-insert-heading))))
18889 ;;; Menu entries
18891 ;; Define the Org-mode menus
18892 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18893 '("Tbl"
18894 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18895 ["Next Field" org-cycle (org-at-table-p)]
18896 ["Previous Field" org-shifttab (org-at-table-p)]
18897 ["Next Row" org-return (org-at-table-p)]
18898 "--"
18899 ["Blank Field" org-table-blank-field (org-at-table-p)]
18900 ["Edit Field" org-table-edit-field (org-at-table-p)]
18901 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18902 "--"
18903 ("Column"
18904 ["Move Column Left" org-metaleft (org-at-table-p)]
18905 ["Move Column Right" org-metaright (org-at-table-p)]
18906 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18907 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18908 ("Row"
18909 ["Move Row Up" org-metaup (org-at-table-p)]
18910 ["Move Row Down" org-metadown (org-at-table-p)]
18911 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18912 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18913 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18914 "--"
18915 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18916 ("Rectangle"
18917 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18918 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18919 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18920 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18921 "--"
18922 ("Calculate"
18923 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18924 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18925 ["Edit Formulas" org-edit-special (org-at-table-p)]
18926 "--"
18927 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18928 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18929 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18930 "--"
18931 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18932 "--"
18933 ["Sum Column/Rectangle" org-table-sum
18934 (or (org-at-table-p) (org-region-active-p))]
18935 ["Which Column?" org-table-current-column (org-at-table-p)])
18936 ["Debug Formulas"
18937 org-table-toggle-formula-debugger
18938 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18939 ["Show Col/Row Numbers"
18940 org-table-toggle-coordinate-overlays
18941 :style toggle
18942 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18943 "--"
18944 ["Create" org-table-create (and (not (org-at-table-p))
18945 org-enable-table-editor)]
18946 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18947 ["Import from File" org-table-import (not (org-at-table-p))]
18948 ["Export to File" org-table-export (org-at-table-p)]
18949 "--"
18950 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18952 (easy-menu-define org-org-menu org-mode-map "Org menu"
18953 '("Org"
18954 ("Show/Hide"
18955 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18956 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18957 ["Sparse Tree..." org-sparse-tree t]
18958 ["Reveal Context" org-reveal t]
18959 ["Show All" show-all t]
18960 "--"
18961 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18962 "--"
18963 ["New Heading" org-insert-heading t]
18964 ("Navigate Headings"
18965 ["Up" outline-up-heading t]
18966 ["Next" outline-next-visible-heading t]
18967 ["Previous" outline-previous-visible-heading t]
18968 ["Next Same Level" outline-forward-same-level t]
18969 ["Previous Same Level" outline-backward-same-level t]
18970 "--"
18971 ["Jump" org-goto t])
18972 ("Edit Structure"
18973 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18974 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18975 "--"
18976 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18977 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18978 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18979 "--"
18980 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18981 "--"
18982 ["Copy visible text" org-copy-visible t]
18983 "--"
18984 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18985 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18986 ["Demote Heading" org-metaright (not (org-at-table-p))]
18987 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18988 "--"
18989 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18990 "--"
18991 ["Convert to odd levels" org-convert-to-odd-levels t]
18992 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18993 ("Editing"
18994 ["Emphasis..." org-emphasize t]
18995 ["Edit Source Example" org-edit-special t]
18996 "--"
18997 ["Footnote new/jump" org-footnote-action t]
18998 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18999 ("Archive"
19000 ["Archive (default method)" org-archive-subtree-default t]
19001 "--"
19002 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19003 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19004 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19006 "--"
19007 ("Hyperlinks"
19008 ["Store Link (Global)" org-store-link t]
19009 ["Find existing link to here" org-occur-link-in-agenda-files t]
19010 ["Insert Link" org-insert-link t]
19011 ["Follow Link" org-open-at-point t]
19012 "--"
19013 ["Next link" org-next-link t]
19014 ["Previous link" org-previous-link t]
19015 "--"
19016 ["Descriptive Links"
19017 org-toggle-link-display
19018 :style radio
19019 :selected org-descriptive-links
19021 ["Literal Links"
19022 org-toggle-link-display
19023 :style radio
19024 :selected (not org-descriptive-links)])
19025 "--"
19026 ("TODO Lists"
19027 ["TODO/DONE/-" org-todo t]
19028 ("Select keyword"
19029 ["Next keyword" org-shiftright (org-at-heading-p)]
19030 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19031 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19032 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19033 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19034 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19035 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19036 "--"
19037 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19038 :selected org-enforce-todo-dependencies :style toggle :active t]
19039 "Settings for tree at point"
19040 ["Do Children sequentially" org-toggle-ordered-property :style radio
19041 :selected (org-entry-get nil "ORDERED")
19042 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19043 ["Do Children parallel" org-toggle-ordered-property :style radio
19044 :selected (not (org-entry-get nil "ORDERED"))
19045 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19046 "--"
19047 ["Set Priority" org-priority t]
19048 ["Priority Up" org-shiftup t]
19049 ["Priority Down" org-shiftdown t]
19050 "--"
19051 ["Get news from all feeds" org-feed-update-all t]
19052 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19053 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19054 ("TAGS and Properties"
19055 ["Set Tags" org-set-tags-command t]
19056 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19057 "--"
19058 ["Set property" org-set-property t]
19059 ["Column view of properties" org-columns t]
19060 ["Insert Column View DBlock" org-insert-columns-dblock t])
19061 ("Dates and Scheduling"
19062 ["Timestamp" org-time-stamp t]
19063 ["Timestamp (inactive)" org-time-stamp-inactive t]
19064 ("Change Date"
19065 ["1 Day Later" org-shiftright t]
19066 ["1 Day Earlier" org-shiftleft t]
19067 ["1 ... Later" org-shiftup t]
19068 ["1 ... Earlier" org-shiftdown t])
19069 ["Compute Time Range" org-evaluate-time-range t]
19070 ["Schedule Item" org-schedule t]
19071 ["Deadline" org-deadline t]
19072 "--"
19073 ["Custom time format" org-toggle-time-stamp-overlays
19074 :style radio :selected org-display-custom-times]
19075 "--"
19076 ["Goto Calendar" org-goto-calendar t]
19077 ["Date from Calendar" org-date-from-calendar t]
19078 "--"
19079 ["Start/Restart Timer" org-timer-start t]
19080 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19081 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19082 ["Insert Timer String" org-timer t]
19083 ["Insert Timer Item" org-timer-item t])
19084 ("Logging work"
19085 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19086 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19087 ["Clock out" org-clock-out t]
19088 ["Clock cancel" org-clock-cancel t]
19089 "--"
19090 ["Mark as default task" org-clock-mark-default-task t]
19091 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19092 ["Goto running clock" org-clock-goto t]
19093 "--"
19094 ["Display times" org-clock-display t]
19095 ["Create clock table" org-clock-report t]
19096 "--"
19097 ["Record DONE time"
19098 (progn (setq org-log-done (not org-log-done))
19099 (message "Switching to %s will %s record a timestamp"
19100 (car org-done-keywords)
19101 (if org-log-done "automatically" "not")))
19102 :style toggle :selected org-log-done])
19103 "--"
19104 ["Agenda Command..." org-agenda t]
19105 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19106 ("File List for Agenda")
19107 ("Special views current file"
19108 ["TODO Tree" org-show-todo-tree t]
19109 ["Check Deadlines" org-check-deadlines t]
19110 ["Timeline" org-timeline t]
19111 ["Tags/Property tree" org-match-sparse-tree t])
19112 "--"
19113 ["Export/Publish..." org-export t]
19114 ("LaTeX"
19115 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19116 :selected org-cdlatex-mode]
19117 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19118 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19119 ["Modify math symbol" org-cdlatex-math-modify
19120 (org-inside-LaTeX-fragment-p)]
19121 ["Insert citation" org-reftex-citation t]
19122 "--"
19123 ["Template for BEAMER" (progn (require 'org-beamer)
19124 (org-insert-beamer-options-template)) t])
19125 "--"
19126 ("MobileOrg"
19127 ["Push Files and Views" org-mobile-push t]
19128 ["Get Captured and Flagged" org-mobile-pull t]
19129 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19130 "--"
19131 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19132 "--"
19133 ("Documentation"
19134 ["Show Version" org-version t]
19135 ["Info Documentation" org-info t])
19136 ("Customize"
19137 ["Browse Org Group" org-customize t]
19138 "--"
19139 ["Expand This Menu" org-create-customize-menu
19140 (fboundp 'customize-menu-create)])
19141 ["Send bug report" org-submit-bug-report t]
19142 "--"
19143 ("Refresh/Reload"
19144 ["Refresh setup current buffer" org-mode-restart t]
19145 ["Reload Org (after update)" org-reload t]
19146 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19149 (defun org-info (&optional node)
19150 "Read documentation for Org-mode in the info system.
19151 With optional NODE, go directly to that node."
19152 (interactive)
19153 (info (format "(org)%s" (or node ""))))
19155 ;;;###autoload
19156 (defun org-submit-bug-report ()
19157 "Submit a bug report on Org-mode via mail.
19159 Don't hesitate to report any problems or inaccurate documentation.
19161 If you don't have setup sending mail from (X)Emacs, please copy the
19162 output buffer into your mail program, as it gives us important
19163 information about your Org-mode version and configuration."
19164 (interactive)
19165 (require 'reporter)
19166 (org-load-modules-maybe)
19167 (org-require-autoloaded-modules)
19168 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19169 (reporter-submit-bug-report
19170 "emacs-orgmode@gnu.org"
19171 (org-version)
19172 (let (list)
19173 (save-window-excursion
19174 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19175 (delete-other-windows)
19176 (erase-buffer)
19177 (insert "You are about to submit a bug report to the Org-mode mailing list.
19179 We would like to add your full Org-mode and Outline configuration to the
19180 bug report. This greatly simplifies the work of the maintainer and
19181 other experts on the mailing list.
19183 HOWEVER, some variables you have customized may contain private
19184 information. The names of customers, colleagues, or friends, might
19185 appear in the form of file names, tags, todo states, or search strings.
19186 If you answer yes to the prompt, you might want to check and remove
19187 such private information before sending the email.")
19188 (add-text-properties (point-min) (point-max) '(face org-warning))
19189 (when (yes-or-no-p "Include your Org-mode configuration ")
19190 (mapatoms
19191 (lambda (v)
19192 (and (boundp v)
19193 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19194 (or (and (symbol-value v)
19195 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19196 (and
19197 (get v 'custom-type) (get v 'standard-value)
19198 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19199 (push v list)))))
19200 (kill-buffer (get-buffer "*Warn about privacy*"))
19201 list))
19202 nil nil
19203 "Remember to cover the basics, that is, what you expected to happen and
19204 what in fact did happen. You don't know how to make a good report? See
19206 http://orgmode.org/manual/Feedback.html#Feedback
19208 Your bug report will be posted to the Org-mode mailing list.
19209 ------------------------------------------------------------------------")
19210 (save-excursion
19211 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19212 (replace-match "\\1Bug: \\3 [\\2]")))))
19215 (defun org-install-agenda-files-menu ()
19216 (let ((bl (buffer-list)))
19217 (save-excursion
19218 (while bl
19219 (set-buffer (pop bl))
19220 (if (eq major-mode 'org-mode) (setq bl nil)))
19221 (when (eq major-mode 'org-mode)
19222 (easy-menu-change
19223 '("Org") "File List for Agenda"
19224 (append
19225 (list
19226 ["Edit File List" (org-edit-agenda-file-list) t]
19227 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19228 ["Remove Current File from List" org-remove-file t]
19229 ["Cycle through agenda files" org-cycle-agenda-files t]
19230 ["Occur in all agenda files" org-occur-in-agenda-files t]
19231 "--")
19232 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19234 ;;;; Documentation
19236 ;;;###autoload
19237 (defun org-require-autoloaded-modules ()
19238 (interactive)
19239 (mapc 'require
19240 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19241 org-docbook org-exp org-html org-icalendar
19242 org-id org-latex
19243 org-publish org-remember org-table
19244 org-timer org-xoxo)))
19246 ;;;###autoload
19247 (defun org-reload (&optional uncompiled)
19248 "Reload all org lisp files.
19249 With prefix arg UNCOMPILED, load the uncompiled versions."
19250 (interactive "P")
19251 (require 'find-func)
19252 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19253 (dir-org (file-name-directory (org-find-library-name "org")))
19254 (dir-org-contrib (ignore-errors
19255 (file-name-directory
19256 (org-find-library-name "org-contribdir"))))
19257 (babel-files
19258 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19259 (append (list nil "comint" "eval" "exp" "keys"
19260 "lob" "ref" "table" "tangle")
19261 (delq nil
19262 (mapcar
19263 (lambda (lang)
19264 (when (cdr lang) (symbol-name (car lang))))
19265 org-babel-load-languages)))))
19266 (files
19267 (append (directory-files dir-org t file-re)
19268 babel-files
19269 (and dir-org-contrib
19270 (directory-files dir-org-contrib t file-re))))
19271 (remove-re (concat (if (featurep 'xemacs)
19272 "org-colview" "org-colview-xemacs")
19273 "\\'")))
19274 (setq files (mapcar 'file-name-sans-extension files))
19275 (setq files (mapcar
19276 (lambda (x) (if (string-match remove-re x) nil x))
19277 files))
19278 (setq files (delq nil files))
19279 (mapc
19280 (lambda (f)
19281 (when (featurep (intern (file-name-nondirectory f)))
19282 (if (and (not uncompiled)
19283 (file-exists-p (concat f ".elc")))
19284 (load (concat f ".elc") nil nil t)
19285 (load (concat f ".el") nil nil t))))
19286 files))
19287 (org-version))
19289 ;;;###autoload
19290 (defun org-customize ()
19291 "Call the customize function with org as argument."
19292 (interactive)
19293 (org-load-modules-maybe)
19294 (org-require-autoloaded-modules)
19295 (customize-browse 'org))
19297 (defun org-create-customize-menu ()
19298 "Create a full customization menu for Org-mode, insert it into the menu."
19299 (interactive)
19300 (org-load-modules-maybe)
19301 (org-require-autoloaded-modules)
19302 (if (fboundp 'customize-menu-create)
19303 (progn
19304 (easy-menu-change
19305 '("Org") "Customize"
19306 `(["Browse Org group" org-customize t]
19307 "--"
19308 ,(customize-menu-create 'org)
19309 ["Set" Custom-set t]
19310 ["Save" Custom-save t]
19311 ["Reset to Current" Custom-reset-current t]
19312 ["Reset to Saved" Custom-reset-saved t]
19313 ["Reset to Standard Settings" Custom-reset-standard t]))
19314 (message "\"Org\"-menu now contains full customization menu"))
19315 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19317 ;;;; Miscellaneous stuff
19319 ;;; Generally useful functions
19321 (defun org-get-at-bol (property)
19322 "Get text property PROPERTY at beginning of line."
19323 (get-text-property (point-at-bol) property))
19325 (defun org-find-text-property-in-string (prop s)
19326 "Return the first non-nil value of property PROP in string S."
19327 (or (get-text-property 0 prop s)
19328 (get-text-property (or (next-single-property-change 0 prop s) 0)
19329 prop s)))
19331 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19332 "Display the given MESSAGE as a warning."
19333 (if (fboundp 'display-warning)
19334 (display-warning 'org message
19335 (if (featurep 'xemacs) 'warning :warning))
19336 (let ((buf (get-buffer-create "*Org warnings*")))
19337 (with-current-buffer buf
19338 (goto-char (point-max))
19339 (insert "Warning (Org): " message)
19340 (unless (bolp)
19341 (newline)))
19342 (display-buffer buf)
19343 (sit-for 0))))
19345 (defun org-eval (form)
19346 "Eval FORM and return result."
19347 (condition-case error
19348 (eval form)
19349 (error (format "%%![Error: %s]" error))))
19351 (defun org-in-clocktable-p ()
19352 "Check if the cursor is in a clocktable."
19353 (let ((pos (point)) start)
19354 (save-excursion
19355 (end-of-line 1)
19356 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19357 (setq start (match-beginning 0))
19358 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19359 (>= (match-end 0) pos)
19360 start))))
19362 (defun org-in-commented-line ()
19363 "Is point in a line starting with `#'?"
19364 (equal (char-after (point-at-bol)) ?#))
19366 (defun org-in-indented-comment-line ()
19367 "Is point in a line starting with `#' after some white space?"
19368 (save-excursion
19369 (save-match-data
19370 (goto-char (point-at-bol))
19371 (looking-at "[ \t]*#"))))
19373 (defun org-in-verbatim-emphasis ()
19374 (save-match-data
19375 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19377 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19378 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19379 (if (and marker (marker-buffer marker)
19380 (buffer-live-p (marker-buffer marker)))
19381 (progn
19382 (org-pop-to-buffer-same-window (marker-buffer marker))
19383 (if (or (> marker (point-max)) (< marker (point-min)))
19384 (widen))
19385 (goto-char marker)
19386 (org-show-context 'org-goto))
19387 (if bookmark
19388 (bookmark-jump bookmark)
19389 (error "Cannot find location"))))
19391 (defun org-quote-csv-field (s)
19392 "Quote field for inclusion in CSV material."
19393 (if (string-match "[\",]" s)
19394 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19397 (defun org-force-self-insert (N)
19398 "Needed to enforce self-insert under remapping."
19399 (interactive "p")
19400 (self-insert-command N))
19402 (defun org-string-width (s)
19403 "Compute width of string, ignoring invisible characters.
19404 This ignores character with invisibility property `org-link', and also
19405 characters with property `org-cwidth', because these will become invisible
19406 upon the next fontification round."
19407 (let (b l)
19408 (when (or (eq t buffer-invisibility-spec)
19409 (assq 'org-link buffer-invisibility-spec))
19410 (while (setq b (text-property-any 0 (length s)
19411 'invisible 'org-link s))
19412 (setq s (concat (substring s 0 b)
19413 (substring s (or (next-single-property-change
19414 b 'invisible s) (length s)))))))
19415 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19416 (setq s (concat (substring s 0 b)
19417 (substring s (or (next-single-property-change
19418 b 'org-cwidth s) (length s))))))
19419 (setq l (string-width s) b -1)
19420 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19421 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19424 (defun org-shorten-string (s maxlength)
19425 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19426 If the string is shorter or has length MAXLENGTH, just return the
19427 original string. If it is longer, the functions finds a space in the
19428 string, breaks this string off at that locations and adds three dots
19429 as ellipsis. Including the ellipsis, the string will not be longer
19430 than MAXLENGTH. If finding a good breaking point in the string does
19431 not work, the string is just chopped off in the middle of a word
19432 if necessary."
19433 (if (<= (length s) maxlength)
19435 (let* ((n (max (- maxlength 4) 1))
19436 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19437 (if (string-match re s)
19438 (concat (match-string 1 s) "...")
19439 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19441 (defun org-get-indentation (&optional line)
19442 "Get the indentation of the current line, interpreting tabs.
19443 When LINE is given, assume it represents a line and compute its indentation."
19444 (if line
19445 (if (string-match "^ *" (org-remove-tabs line))
19446 (match-end 0))
19447 (save-excursion
19448 (beginning-of-line 1)
19449 (skip-chars-forward " \t")
19450 (current-column))))
19452 (defun org-get-string-indentation (s)
19453 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19454 (let ((n -1) (i 0) (w tab-width) c)
19455 (catch 'exit
19456 (while (< (setq n (1+ n)) (length s))
19457 (setq c (aref s n))
19458 (cond ((= c ?\ ) (setq i (1+ i)))
19459 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19460 (t (throw 'exit t)))))
19463 (defun org-remove-tabs (s &optional width)
19464 "Replace tabulators in S with spaces.
19465 Assumes that s is a single line, starting in column 0."
19466 (setq width (or width tab-width))
19467 (while (string-match "\t" s)
19468 (setq s (replace-match
19469 (make-string
19470 (- (* width (/ (+ (match-beginning 0) width) width))
19471 (match-beginning 0)) ?\ )
19472 t t s)))
19475 (defun org-fix-indentation (line ind)
19476 "Fix indentation in LINE.
19477 IND is a cons cell with target and minimum indentation.
19478 If the current indentation in LINE is smaller than the minimum,
19479 leave it alone. If it is larger than ind, set it to the target."
19480 (let* ((l (org-remove-tabs line))
19481 (i (org-get-indentation l))
19482 (i1 (car ind)) (i2 (cdr ind)))
19483 (if (>= i i2) (setq l (substring line i2)))
19484 (if (> i1 0)
19485 (concat (make-string i1 ?\ ) l)
19486 l)))
19488 (defun org-remove-indentation (code &optional n)
19489 "Remove the maximum common indentation from the lines in CODE.
19490 N may optionally be the number of spaces to remove."
19491 (with-temp-buffer
19492 (insert code)
19493 (org-do-remove-indentation n)
19494 (buffer-string)))
19496 (defun org-do-remove-indentation (&optional n)
19497 "Remove the maximum common indentation from the buffer."
19498 (untabify (point-min) (point-max))
19499 (let ((min 10000) re)
19500 (if n
19501 (setq min n)
19502 (goto-char (point-min))
19503 (while (re-search-forward "^ *[^ \n]" nil t)
19504 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19505 (unless (or (= min 0) (= min 10000))
19506 (setq re (format "^ \\{%d\\}" min))
19507 (goto-char (point-min))
19508 (while (re-search-forward re nil t)
19509 (replace-match "")
19510 (end-of-line 1))
19511 min)))
19513 (defun org-fill-template (template alist)
19514 "Find each %key of ALIST in TEMPLATE and replace it."
19515 (let ((case-fold-search nil)
19516 entry key value)
19517 (setq alist (sort (copy-sequence alist)
19518 (lambda (a b) (< (length (car a)) (length (car b))))))
19519 (while (setq entry (pop alist))
19520 (setq template
19521 (replace-regexp-in-string
19522 (concat "%" (regexp-quote (car entry)))
19523 (cdr entry) template t t)))
19524 template))
19526 (defun org-base-buffer (buffer)
19527 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19528 (if (not buffer)
19529 buffer
19530 (or (buffer-base-buffer buffer)
19531 buffer)))
19533 (defun org-trim (s)
19534 "Remove whitespace at beginning and end of string."
19535 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19536 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19539 (defun org-wrap (string &optional width lines)
19540 "Wrap string to either a number of lines, or a width in characters.
19541 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19542 that costs. If there is a word longer than WIDTH, the text is actually
19543 wrapped to the length of that word.
19544 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19545 many lines, whatever width that takes.
19546 The return value is a list of lines, without newlines at the end."
19547 (let* ((words (org-split-string string "[ \t\n]+"))
19548 (maxword (apply 'max (mapcar 'org-string-width words)))
19549 w ll)
19550 (cond (width
19551 (org-do-wrap words (max maxword width)))
19552 (lines
19553 (setq w maxword)
19554 (setq ll (org-do-wrap words maxword))
19555 (if (<= (length ll) lines)
19557 (setq ll words)
19558 (while (> (length ll) lines)
19559 (setq w (1+ w))
19560 (setq ll (org-do-wrap words w)))
19561 ll))
19562 (t (error "Cannot wrap this")))))
19564 (defun org-do-wrap (words width)
19565 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19566 (let (lines line)
19567 (while words
19568 (setq line (pop words))
19569 (while (and words (< (+ (length line) (length (car words))) width))
19570 (setq line (concat line " " (pop words))))
19571 (setq lines (push line lines)))
19572 (nreverse lines)))
19574 (defun org-split-string (string &optional separators)
19575 "Splits STRING into substrings at SEPARATORS.
19576 No empty strings are returned if there are matches at the beginning
19577 and end of string."
19578 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19579 (start 0)
19580 notfirst
19581 (list nil))
19582 (while (and (string-match rexp string
19583 (if (and notfirst
19584 (= start (match-beginning 0))
19585 (< start (length string)))
19586 (1+ start) start))
19587 (< (match-beginning 0) (length string)))
19588 (setq notfirst t)
19589 (or (eq (match-beginning 0) 0)
19590 (and (eq (match-beginning 0) (match-end 0))
19591 (eq (match-beginning 0) start))
19592 (setq list
19593 (cons (substring string start (match-beginning 0))
19594 list)))
19595 (setq start (match-end 0)))
19596 (or (eq start (length string))
19597 (setq list
19598 (cons (substring string start)
19599 list)))
19600 (nreverse list)))
19602 (defun org-quote-vert (s)
19603 "Replace \"|\" with \"\\vert\"."
19604 (while (string-match "|" s)
19605 (setq s (replace-match "\\vert" t t s)))
19608 (defun org-uuidgen-p (s)
19609 "Is S an ID created by UUIDGEN?"
19610 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19612 (defun org-context ()
19613 "Return a list of contexts of the current cursor position.
19614 If several contexts apply, all are returned.
19615 Each context entry is a list with a symbol naming the context, and
19616 two positions indicating start and end of the context. Possible
19617 contexts are:
19619 :headline anywhere in a headline
19620 :headline-stars on the leading stars in a headline
19621 :todo-keyword on a TODO keyword (including DONE) in a headline
19622 :tags on the TAGS in a headline
19623 :priority on the priority cookie in a headline
19624 :item on the first line of a plain list item
19625 :item-bullet on the bullet/number of a plain list item
19626 :checkbox on the checkbox in a plain list item
19627 :table in an org-mode table
19628 :table-special on a special filed in a table
19629 :table-table in a table.el table
19630 :link on a hyperlink
19631 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19632 :target on a <<target>>
19633 :radio-target on a <<<radio-target>>>
19634 :latex-fragment on a LaTeX fragment
19635 :latex-preview on a LaTeX fragment with overlaid preview image
19637 This function expects the position to be visible because it uses font-lock
19638 faces as a help to recognize the following contexts: :table-special, :link,
19639 and :keyword."
19640 (let* ((f (get-text-property (point) 'face))
19641 (faces (if (listp f) f (list f)))
19642 (p (point)) clist o)
19643 ;; First the large context
19644 (cond
19645 ((org-at-heading-p t)
19646 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19647 (when (progn
19648 (beginning-of-line 1)
19649 (looking-at org-todo-line-tags-regexp))
19650 (push (org-point-in-group p 1 :headline-stars) clist)
19651 (push (org-point-in-group p 2 :todo-keyword) clist)
19652 (push (org-point-in-group p 4 :tags) clist))
19653 (goto-char p)
19654 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19655 (if (looking-at "\\[#[A-Z0-9]\\]")
19656 (push (org-point-in-group p 0 :priority) clist)))
19658 ((org-at-item-p)
19659 (push (org-point-in-group p 2 :item-bullet) clist)
19660 (push (list :item (point-at-bol)
19661 (save-excursion (org-end-of-item) (point)))
19662 clist)
19663 (and (org-at-item-checkbox-p)
19664 (push (org-point-in-group p 0 :checkbox) clist)))
19666 ((org-at-table-p)
19667 (push (list :table (org-table-begin) (org-table-end)) clist)
19668 (if (memq 'org-formula faces)
19669 (push (list :table-special
19670 (previous-single-property-change p 'face)
19671 (next-single-property-change p 'face)) clist)))
19672 ((org-at-table-p 'any)
19673 (push (list :table-table) clist)))
19674 (goto-char p)
19676 ;; Now the small context
19677 (cond
19678 ((org-at-timestamp-p)
19679 (push (org-point-in-group p 0 :timestamp) clist))
19680 ((memq 'org-link faces)
19681 (push (list :link
19682 (previous-single-property-change p 'face)
19683 (next-single-property-change p 'face)) clist))
19684 ((memq 'org-special-keyword faces)
19685 (push (list :keyword
19686 (previous-single-property-change p 'face)
19687 (next-single-property-change p 'face)) clist))
19688 ((org-at-target-p)
19689 (push (org-point-in-group p 0 :target) clist)
19690 (goto-char (1- (match-beginning 0)))
19691 (if (looking-at org-radio-target-regexp)
19692 (push (org-point-in-group p 0 :radio-target) clist))
19693 (goto-char p))
19694 ((setq o (car (delq nil
19695 (mapcar
19696 (lambda (x)
19697 (if (memq x org-latex-fragment-image-overlays) x))
19698 (overlays-at (point))))))
19699 (push (list :latex-fragment
19700 (overlay-start o) (overlay-end o)) clist)
19701 (push (list :latex-preview
19702 (overlay-start o) (overlay-end o)) clist))
19703 ((org-inside-LaTeX-fragment-p)
19704 ;; FIXME: positions wrong.
19705 (push (list :latex-fragment (point) (point)) clist)))
19707 (setq clist (nreverse (delq nil clist)))
19708 clist))
19710 ;; FIXME: Compare with at-regexp-p Do we need both?
19711 (defun org-in-regexp (re &optional nlines visually)
19712 "Check if point is inside a match of regexp.
19713 Normally only the current line is checked, but you can include NLINES extra
19714 lines both before and after point into the search.
19715 If VISUALLY is set, require that the cursor is not after the match but
19716 really on, so that the block visually is on the match."
19717 (catch 'exit
19718 (let ((pos (point))
19719 (eol (point-at-eol (+ 1 (or nlines 0))))
19720 (inc (if visually 1 0)))
19721 (save-excursion
19722 (beginning-of-line (- 1 (or nlines 0)))
19723 (while (re-search-forward re eol t)
19724 (if (and (<= (match-beginning 0) pos)
19725 (>= (+ inc (match-end 0)) pos))
19726 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19728 (defun org-at-regexp-p (regexp)
19729 "Is point inside a match of REGEXP in the current line?"
19730 (catch 'exit
19731 (save-excursion
19732 (let ((pos (point)) (end (point-at-eol)))
19733 (beginning-of-line 1)
19734 (while (re-search-forward regexp end t)
19735 (if (and (<= (match-beginning 0) pos)
19736 (>= (match-end 0) pos))
19737 (throw 'exit t)))
19738 nil))))
19740 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19741 "Non-nil when point is between matches of START-RE and END-RE.
19743 Also return a non-nil value when point is on one of the matches.
19745 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19746 buffer positions. Default values are the positions of headlines
19747 surrounding the point.
19749 The functions returns a cons cell whose car (resp. cdr) is the
19750 position before START-RE (resp. after END-RE)."
19751 (save-match-data
19752 (let ((pos (point))
19753 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19754 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19755 beg end)
19756 (save-excursion
19757 ;; Point is on a block when on START-RE or if START-RE can be
19758 ;; found before it...
19759 (and (or (org-at-regexp-p start-re)
19760 (re-search-backward start-re limit-up t))
19761 (setq beg (match-beginning 0))
19762 ;; ... and END-RE after it...
19763 (goto-char (match-end 0))
19764 (re-search-forward end-re limit-down t)
19765 (> (setq end (match-end 0)) pos)
19766 ;; ... without another START-RE in-between.
19767 (goto-char (match-beginning 0))
19768 (not (re-search-backward start-re (1+ beg) t))
19769 ;; Return value.
19770 (cons beg end))))))
19772 (defun org-in-block-p (names)
19773 "Non-nil when point belongs to a block whose name belongs to NAMES.
19775 NAMES is a list of strings containing names of blocks.
19777 Return first block name matched, or nil. Beware that in case of
19778 nested blocks, the returned name may not belong to the closest
19779 block from point."
19780 (save-match-data
19781 (catch 'exit
19782 (let ((case-fold-search t)
19783 (lim-up (save-excursion (outline-previous-heading)))
19784 (lim-down (save-excursion (outline-next-heading))))
19785 (mapc (lambda (name)
19786 (let ((n (regexp-quote name)))
19787 (when (org-between-regexps-p
19788 (concat "^[ \t]*#\\+begin_" n)
19789 (concat "^[ \t]*#\\+end_" n)
19790 lim-up lim-down)
19791 (throw 'exit n))))
19792 names))
19793 nil)))
19795 (defun org-occur-in-agenda-files (regexp &optional nlines)
19796 "Call `multi-occur' with buffers for all agenda files."
19797 (interactive "sOrg-files matching: \np")
19798 (let* ((files (org-agenda-files))
19799 (tnames (mapcar 'file-truename files))
19800 (extra org-agenda-text-search-extra-files)
19802 (when (eq (car extra) 'agenda-archives)
19803 (setq extra (cdr extra))
19804 (setq files (org-add-archive-files files)))
19805 (while (setq f (pop extra))
19806 (unless (member (file-truename f) tnames)
19807 (add-to-list 'files f 'append)
19808 (add-to-list 'tnames (file-truename f) 'append)))
19809 (multi-occur
19810 (mapcar (lambda (x)
19811 (with-current-buffer
19812 (or (get-file-buffer x) (find-file-noselect x))
19813 (widen)
19814 (current-buffer)))
19815 files)
19816 regexp)))
19818 (if (boundp 'occur-mode-find-occurrence-hook)
19819 ;; Emacs 23
19820 (add-hook 'occur-mode-find-occurrence-hook
19821 (lambda ()
19822 (when (eq major-mode 'org-mode)
19823 (org-reveal))))
19824 ;; Emacs 22
19825 (defadvice occur-mode-goto-occurrence
19826 (after org-occur-reveal activate)
19827 (and (eq major-mode 'org-mode) (org-reveal)))
19828 (defadvice occur-mode-goto-occurrence-other-window
19829 (after org-occur-reveal activate)
19830 (and (eq major-mode 'org-mode) (org-reveal)))
19831 (defadvice occur-mode-display-occurrence
19832 (after org-occur-reveal activate)
19833 (when (eq major-mode 'org-mode)
19834 (let ((pos (occur-mode-find-occurrence)))
19835 (with-current-buffer (marker-buffer pos)
19836 (save-excursion
19837 (goto-char pos)
19838 (org-reveal)))))))
19840 (defun org-occur-link-in-agenda-files ()
19841 "Create a link and search for it in the agendas.
19842 The link is not stored in `org-stored-links', it is just created
19843 for the search purpose."
19844 (interactive)
19845 (let ((link (condition-case nil
19846 (org-store-link nil)
19847 (error "Unable to create a link to here"))))
19848 (org-occur-in-agenda-files (regexp-quote link))))
19850 (defun org-uniquify (list)
19851 "Remove duplicate elements from LIST."
19852 (let (res)
19853 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19854 res))
19856 (defun org-delete-all (elts list)
19857 "Remove all elements in ELTS from LIST."
19858 (while elts
19859 (setq list (delete (pop elts) list)))
19860 list)
19862 (defun org-count (cl-item cl-seq)
19863 "Count the number of occurrences of ITEM in SEQ.
19864 Taken from `count' in cl-seq.el with all keyword arguments removed."
19865 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19866 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19867 (while (< cl-start cl-end)
19868 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19869 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19870 (setq cl-start (1+ cl-start)))
19871 cl-count))
19873 (defun org-remove-if (predicate seq)
19874 "Remove everything from SEQ that fulfills PREDICATE."
19875 (let (res e)
19876 (while seq
19877 (setq e (pop seq))
19878 (if (not (funcall predicate e)) (push e res)))
19879 (nreverse res)))
19881 (defun org-remove-if-not (predicate seq)
19882 "Remove everything from SEQ that does not fulfill PREDICATE."
19883 (let (res e)
19884 (while seq
19885 (setq e (pop seq))
19886 (if (funcall predicate e) (push e res)))
19887 (nreverse res)))
19889 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19890 "Reduce two-argument FUNCTION across SEQ.
19891 Taken from `reduce' in cl-seq.el with all keyword arguments but
19892 \":initial-value\" removed."
19893 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19894 (cadr (memq :initial-value cl-keys)))
19895 (cl-seq (pop cl-seq))
19896 (t (funcall cl-func)))))
19897 (while cl-seq
19898 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19899 cl-accum))
19901 (defun org-back-over-empty-lines ()
19902 "Move backwards over whitespace, to the beginning of the first empty line.
19903 Returns the number of empty lines passed."
19904 (let ((pos (point)))
19905 (if (cdr (assoc 'heading org-blank-before-new-entry))
19906 (skip-chars-backward " \t\n\r")
19907 (unless (eobp)
19908 (forward-line -1)))
19909 (beginning-of-line 2)
19910 (goto-char (min (point) pos))
19911 (count-lines (point) pos)))
19913 (defun org-skip-whitespace ()
19914 (skip-chars-forward " \t\n\r"))
19916 (defun org-point-in-group (point group &optional context)
19917 "Check if POINT is in match-group GROUP.
19918 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19919 match. If the match group does not exist or point is not inside it,
19920 return nil."
19921 (and (match-beginning group)
19922 (>= point (match-beginning group))
19923 (<= point (match-end group))
19924 (if context
19925 (list context (match-beginning group) (match-end group))
19926 t)))
19928 (defun org-switch-to-buffer-other-window (&rest args)
19929 "Switch to buffer in a second window on the current frame.
19930 In particular, do not allow pop-up frames.
19931 Returns the newly created buffer."
19932 (let (pop-up-frames special-display-buffer-names special-display-regexps
19933 special-display-function)
19934 (apply 'switch-to-buffer-other-window args)))
19936 (defun org-combine-plists (&rest plists)
19937 "Create a single property list from all plists in PLISTS.
19938 The process starts by copying the first list, and then setting properties
19939 from the other lists. Settings in the last list are the most significant
19940 ones and overrule settings in the other lists."
19941 (let ((rtn (copy-sequence (pop plists)))
19942 p v ls)
19943 (while plists
19944 (setq ls (pop plists))
19945 (while ls
19946 (setq p (pop ls) v (pop ls))
19947 (setq rtn (plist-put rtn p v))))
19948 rtn))
19950 (defun org-move-line-down (arg)
19951 "Move the current line down. With prefix argument, move it past ARG lines."
19952 (interactive "p")
19953 (let ((col (current-column))
19954 beg end pos)
19955 (beginning-of-line 1) (setq beg (point))
19956 (beginning-of-line 2) (setq end (point))
19957 (beginning-of-line (+ 1 arg))
19958 (setq pos (move-marker (make-marker) (point)))
19959 (insert (delete-and-extract-region beg end))
19960 (goto-char pos)
19961 (org-move-to-column col)))
19963 (defun org-move-line-up (arg)
19964 "Move the current line up. With prefix argument, move it past ARG lines."
19965 (interactive "p")
19966 (let ((col (current-column))
19967 beg end pos)
19968 (beginning-of-line 1) (setq beg (point))
19969 (beginning-of-line 2) (setq end (point))
19970 (beginning-of-line (- arg))
19971 (setq pos (move-marker (make-marker) (point)))
19972 (insert (delete-and-extract-region beg end))
19973 (goto-char pos)
19974 (org-move-to-column col)))
19976 (defun org-replace-escapes (string table)
19977 "Replace %-escapes in STRING with values in TABLE.
19978 TABLE is an association list with keys like \"%a\" and string values.
19979 The sequences in STRING may contain normal field width and padding information,
19980 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19981 so values can contain further %-escapes if they are define later in TABLE."
19982 (let ((tbl (copy-alist table))
19983 (case-fold-search nil)
19984 (pchg 0)
19985 e re rpl)
19986 (while (setq e (pop tbl))
19987 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19988 (when (and (cdr e) (string-match re (cdr e)))
19989 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19990 (safe "SREF"))
19991 (add-text-properties 0 3 (list 'sref sref) safe)
19992 (setcdr e (replace-match safe t t (cdr e)))))
19993 (while (string-match re string)
19994 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19995 (cdr e)))
19996 (setq string (replace-match rpl t t string))))
19997 (while (setq pchg (next-property-change pchg string))
19998 (let ((sref (get-text-property pchg 'sref string)))
19999 (when (and sref (string-match "SREF" string pchg))
20000 (setq string (replace-match sref t t string)))))
20001 string))
20003 (defun org-sublist (list start end)
20004 "Return a section of LIST, from START to END.
20005 Counting starts at 1."
20006 (let (rtn (c start))
20007 (setq list (nthcdr (1- start) list))
20008 (while (and list (<= c end))
20009 (push (pop list) rtn)
20010 (setq c (1+ c)))
20011 (nreverse rtn)))
20013 (defun org-find-base-buffer-visiting (file)
20014 "Like `find-buffer-visiting' but always return the base buffer and
20015 not an indirect buffer."
20016 (let ((buf (or (get-file-buffer file)
20017 (find-buffer-visiting file))))
20018 (if buf
20019 (or (buffer-base-buffer buf) buf)
20020 nil)))
20022 (defun org-image-file-name-regexp (&optional extensions)
20023 "Return regexp matching the file names of images.
20024 If EXTENSIONS is given, only match these."
20025 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20026 (image-file-name-regexp)
20027 (let ((image-file-name-extensions
20028 (or extensions
20029 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20030 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20031 (concat "\\."
20032 (regexp-opt (nconc (mapcar 'upcase
20033 image-file-name-extensions)
20034 image-file-name-extensions)
20036 "\\'"))))
20038 (defun org-file-image-p (file &optional extensions)
20039 "Return non-nil if FILE is an image."
20040 (save-match-data
20041 (string-match (org-image-file-name-regexp extensions) file)))
20043 (defun org-get-cursor-date ()
20044 "Return the date at cursor in as a time.
20045 This works in the calendar and in the agenda, anywhere else it just
20046 returns the current time."
20047 (let (date day defd)
20048 (cond
20049 ((eq major-mode 'calendar-mode)
20050 (setq date (calendar-cursor-to-date)
20051 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20052 ((eq major-mode 'org-agenda-mode)
20053 (setq day (get-text-property (point) 'day))
20054 (if day
20055 (setq date (calendar-gregorian-from-absolute day)
20056 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20057 (nth 2 date))))))
20058 (or defd (current-time))))
20060 (defvar org-agenda-action-marker (make-marker)
20061 "Marker pointing to the entry for the next agenda action.")
20063 (defun org-mark-entry-for-agenda-action ()
20064 "Mark the current entry as target of an agenda action.
20065 Agenda actions are actions executed from the agenda with the key `k',
20066 which make use of the date at the cursor."
20067 (interactive)
20068 (move-marker org-agenda-action-marker
20069 (save-excursion (org-back-to-heading t) (point))
20070 (current-buffer))
20071 (message
20072 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20074 (defun org-mark-subtree ()
20075 "Mark the current subtree.
20076 This puts point at the start of the current subtree, and mark at the end.
20078 If point is in an inline task, mark that task instead."
20079 (interactive)
20080 (let ((inline-task-p
20081 (and (featurep 'org-inlinetask)
20082 (org-inlinetask-in-task-p)))
20083 (beg))
20084 ;; Get beginning of subtree
20085 (cond
20086 (inline-task-p (org-inlinetask-goto-beginning))
20087 ((org-at-heading-p) (beginning-of-line))
20088 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20089 (setq beg (point))
20090 ;; Get end of it
20091 (if inline-task-p
20092 (org-inlinetask-goto-end)
20093 (org-end-of-subtree))
20094 ;; Mark zone
20095 (push-mark (point) nil t)
20096 (goto-char beg)))
20098 ;;; Paragraph filling stuff.
20099 ;; We want this to be just right, so use the full arsenal.
20101 (defun org-indent-line-function ()
20102 "Indent line depending on context."
20103 (interactive)
20104 (let* ((pos (point))
20105 (itemp (org-at-item-p))
20106 (case-fold-search t)
20107 (org-drawer-regexp (or org-drawer-regexp "\000"))
20108 (inline-task-p (and (featurep 'org-inlinetask)
20109 (org-inlinetask-in-task-p)))
20110 (inline-re (and inline-task-p
20111 (org-inlinetask-outline-regexp)))
20112 column)
20113 (beginning-of-line 1)
20114 (cond
20115 ;; Comments
20116 ((looking-at "# ") (setq column 0))
20117 ;; Headings
20118 ((looking-at org-outline-regexp) (setq column 0))
20119 ;; Included files
20120 ((looking-at "#\\+include:") (setq column 0))
20121 ;; Footnote definition
20122 ((looking-at org-footnote-definition-re) (setq column 0))
20123 ;; Literal examples
20124 ((looking-at "[ \t]*:\\( \\|$\\)")
20125 (setq column (org-get-indentation))) ; do nothing
20126 ;; Lists
20127 ((ignore-errors (goto-char (org-in-item-p)))
20128 (setq column (if itemp
20129 (org-get-indentation)
20130 (org-list-item-body-column (point))))
20131 (goto-char pos))
20132 ;; Drawers
20133 ((and (looking-at "[ \t]*:END:")
20134 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20135 (save-excursion
20136 (goto-char (1- (match-beginning 1)))
20137 (setq column (current-column))))
20138 ;; Special blocks
20139 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20140 (save-excursion
20141 (re-search-backward
20142 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20143 (setq column (org-get-indentation (match-string 0))))
20144 ((and (not (looking-at "[ \t]*#\\+begin_"))
20145 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20146 (save-excursion
20147 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20148 (setq column
20149 (cond ((equal (downcase (match-string 1)) "src")
20150 ;; src blocks: let `org-edit-src-exit' handle them
20151 (org-get-indentation))
20152 ((equal (downcase (match-string 1)) "example")
20153 (max (org-get-indentation)
20154 (org-get-indentation (match-string 0))))
20156 (org-get-indentation (match-string 0))))))
20157 ;; This line has nothing special, look at the previous relevant
20158 ;; line to compute indentation
20160 (beginning-of-line 0)
20161 (while (and (not (bobp))
20162 (not (looking-at org-drawer-regexp))
20163 ;; When point started in an inline task, do not move
20164 ;; above task starting line.
20165 (not (and inline-task-p (looking-at inline-re)))
20166 ;; Skip drawers, blocks, empty lines, verbatim,
20167 ;; comments, tables, footnotes definitions, lists,
20168 ;; inline tasks.
20169 (or (and (looking-at "[ \t]*:END:")
20170 (re-search-backward org-drawer-regexp nil t))
20171 (and (looking-at "[ \t]*#\\+end_")
20172 (re-search-backward "[ \t]*#\\+begin_"nil t))
20173 (looking-at "[ \t]*[\n:#|]")
20174 (looking-at org-footnote-definition-re)
20175 (and (ignore-errors (goto-char (org-in-item-p)))
20176 (goto-char
20177 (org-list-get-top-point (org-list-struct))))
20178 (and (not inline-task-p)
20179 (featurep 'org-inlinetask)
20180 (org-inlinetask-in-task-p)
20181 (or (org-inlinetask-goto-beginning) t))))
20182 (beginning-of-line 0))
20183 (cond
20184 ;; There was an heading above.
20185 ((looking-at "\\*+[ \t]+")
20186 (if (not org-adapt-indentation)
20187 (setq column 0)
20188 (goto-char (match-end 0))
20189 (setq column (current-column))))
20190 ;; A drawer had started and is unfinished
20191 ((looking-at org-drawer-regexp)
20192 (goto-char (1- (match-beginning 1)))
20193 (setq column (current-column)))
20194 ;; Else, nothing noticeable found: get indentation and go on.
20195 (t (setq column (org-get-indentation))))))
20196 ;; Now apply indentation and move cursor accordingly
20197 (goto-char pos)
20198 (if (<= (current-column) (current-indentation))
20199 (org-indent-line-to column)
20200 (save-excursion (org-indent-line-to column)))
20201 ;; Special polishing for properties, see `org-property-format'
20202 (setq column (current-column))
20203 (beginning-of-line 1)
20204 (if (looking-at
20205 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20206 (replace-match (concat (match-string 1)
20207 (format org-property-format
20208 (match-string 2) (match-string 3)))
20209 t t))
20210 (org-move-to-column column)))
20212 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20213 "Variable to store copy of `adaptive-fill-regexp'.
20214 Since `adaptive-fill-regexp' is set to never match, we need to
20215 store a backup of its value before entering `org-mode' so that
20216 the functionality can be provided as a fall-back.")
20218 (defun org-set-autofill-regexps ()
20219 (interactive)
20220 ;; In the paragraph separator we include headlines, because filling
20221 ;; text in a line directly attached to a headline would otherwise
20222 ;; fill the headline as well.
20223 (org-set-local 'comment-start-skip "^#+[ \t]*")
20224 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20225 ;; The paragraph starter includes hand-formatted lists.
20226 (org-set-local
20227 'paragraph-start
20228 (concat
20229 "\f" "\\|"
20230 "[ ]*$" "\\|"
20231 org-outline-regexp "\\|"
20232 "[ \t]*#" "\\|"
20233 (org-item-re) "\\|"
20234 "[ \t]*[:|]" "\\|"
20235 "\\$\\$" "\\|"
20236 "\\\\\\(begin\\|end\\|[][]\\)"))
20237 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20238 ;; But only if the user has not turned off tables or fixed-width regions
20239 (org-set-local
20240 'auto-fill-inhibit-regexp
20241 (concat org-outline-regexp
20242 "\\|#\\+"
20243 "\\|[ \t]*" org-keyword-time-regexp
20244 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20245 (concat
20246 "\\|[ \t]*["
20247 (if org-enable-table-editor "|" "")
20248 (if org-enable-fixed-width-editor ":" "")
20249 "]"))))
20250 ;; We use our own fill-paragraph function, to make sure that tables
20251 ;; and fixed-width regions are not wrapped. That function will pass
20252 ;; through to `fill-paragraph' when appropriate.
20253 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20254 ;; Prevent auto-fill from inserting unwanted new items.
20255 (if (boundp 'fill-nobreak-predicate)
20256 (org-set-local 'fill-nobreak-predicate
20257 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20258 fill-nobreak-predicate
20259 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20260 ;; Adaptive filling: To get full control, first make sure that
20261 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20262 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20263 (org-set-local 'org-adaptive-fill-regexp-backup
20264 adaptive-fill-regexp))
20265 (org-set-local 'adaptive-fill-regexp "\000")
20266 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20267 (org-set-local 'adaptive-fill-function
20268 'org-adaptive-fill-function)
20269 (org-set-local
20270 'align-mode-rules-list
20271 '((org-in-buffer-settings
20272 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20273 (modes . '(org-mode))))))
20275 (defun org-fill-item-nobreak-p ()
20276 "Non-nil when a line break at point would insert a new item."
20277 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20279 (defun org-fill-paragraph (&optional justify)
20280 "Re-align a table, pass through to fill-paragraph if no table."
20281 (let ((table-p (org-at-table-p))
20282 (table.el-p (org-at-table.el-p))
20283 (itemp (org-in-item-p)))
20284 (cond ((and (equal (char-after (point-at-bol)) ?*)
20285 (save-excursion (goto-char (point-at-bol))
20286 (looking-at org-outline-regexp)))
20287 t) ; skip headlines
20288 (table.el-p t) ; skip table.el tables
20289 (table-p (org-table-align) t) ; align Org tables
20290 (itemp ; align text in items
20291 (let* ((struct (save-excursion (goto-char itemp)
20292 (org-list-struct)))
20293 (parents (org-list-parents-alist struct))
20294 (children (org-list-get-children itemp struct parents))
20295 beg end prev next prefix)
20296 ;; Determine in which part of item point is: before
20297 ;; first child, after last child, between two
20298 ;; sub-lists, or simply in item if there's no child.
20299 (cond
20300 ((not children)
20301 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20302 beg itemp
20303 end (org-list-get-item-end itemp struct)))
20304 ((< (point) (setq next (car children)))
20305 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20306 beg itemp
20307 end next))
20308 ((> (point) (setq prev (car (last children))))
20309 (setq beg (org-list-get-item-end prev struct)
20310 end (org-list-get-item-end itemp struct)
20311 prefix (save-excursion
20312 (goto-char beg)
20313 (skip-chars-forward " \t")
20314 (make-string (current-column) ?\ ))))
20315 (t (catch 'exit
20316 (while (setq next (pop children))
20317 (if (> (point) next)
20318 (setq prev next)
20319 (setq beg (org-list-get-item-end prev struct)
20320 end next
20321 prefix (save-excursion
20322 (goto-char beg)
20323 (skip-chars-forward " \t")
20324 (make-string (current-column) ?\ )))
20325 (throw 'exit nil))))))
20326 ;; Use `fill-paragraph' with buffer narrowed to item
20327 ;; without any child, and with our computed PREFIX.
20328 (flet ((fill-context-prefix (from to &optional flr) prefix))
20329 (save-restriction
20330 (narrow-to-region beg end)
20331 (save-excursion (fill-paragraph justify)))) t))
20332 ;; Special case where point is not in a list but is on
20333 ;; a paragraph adjacent to a list: make sure this paragraph
20334 ;; doesn't get merged with the end of the list by narrowing
20335 ;; buffer first.
20336 ((save-excursion (forward-paragraph -1)
20337 (setq itemp (org-in-item-p)))
20338 (let ((struct (save-excursion (goto-char itemp)
20339 (org-list-struct))))
20340 (save-restriction
20341 (narrow-to-region (org-list-get-bottom-point struct)
20342 (save-excursion (forward-paragraph 1)
20343 (point)))
20344 (fill-paragraph justify) t)))
20345 ;; Else simply call `fill-paragraph'.
20346 (t nil))))
20348 ;; For reference, this is the default value of adaptive-fill-regexp
20349 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20351 (defun org-adaptive-fill-function ()
20352 "Return a fill prefix for org-mode files."
20353 (let (itemp)
20354 (save-excursion
20355 (cond
20356 ;; Comment line
20357 ((looking-at "#[ \t]+")
20358 (match-string-no-properties 0))
20359 ;; Plain list item
20360 ((org-at-item-p)
20361 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20362 ;; Point is in a list after `backward-paragraph': original
20363 ;; point wasn't in the list, or filling would have been taken
20364 ;; care of by `org-auto-fill-function', but the list and the
20365 ;; real paragraph are not separated by a blank line. Thus, move
20366 ;; point after the list to go back to real paragraph and
20367 ;; determine fill-prefix.
20368 ((setq itemp (org-in-item-p))
20369 (goto-char itemp)
20370 (let* ((struct (org-list-struct))
20371 (bottom (org-list-get-bottom-point struct)))
20372 (goto-char bottom)
20373 (make-string (org-get-indentation) ?\ )))
20374 ;; Other text
20375 ((looking-at org-adaptive-fill-regexp-backup)
20376 (match-string-no-properties 0))))))
20378 (defun org-auto-fill-function ()
20379 "Auto-fill function."
20380 (let (itemp prefix)
20381 ;; When in a list, compute an appropriate fill-prefix and make
20382 ;; sure it will be used by `do-auto-fill'.
20383 (if (setq itemp (org-in-item-p))
20384 (progn
20385 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20386 (flet ((fill-context-prefix (from to &optional flr) prefix))
20387 (do-auto-fill)))
20388 ;; Else just use `do-auto-fill'.
20389 (do-auto-fill))))
20391 ;;; Other stuff.
20393 (defun org-toggle-fixed-width-section (arg)
20394 "Toggle the fixed-width export.
20395 If there is no active region, the QUOTE keyword at the current headline is
20396 inserted or removed. When present, it causes the text between this headline
20397 and the next to be exported as fixed-width text, and unmodified.
20398 If there is an active region, this command adds or removes a colon as the
20399 first character of this line. If the first character of a line is a colon,
20400 this line is also exported in fixed-width font."
20401 (interactive "P")
20402 (let* ((cc 0)
20403 (regionp (org-region-active-p))
20404 (beg (if regionp (region-beginning) (point)))
20405 (end (if regionp (region-end)))
20406 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20407 (case-fold-search nil)
20408 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20409 off)
20410 (if regionp
20411 (save-excursion
20412 (goto-char beg)
20413 (setq cc (current-column))
20414 (beginning-of-line 1)
20415 (setq off (looking-at re))
20416 (while (> nlines 0)
20417 (setq nlines (1- nlines))
20418 (beginning-of-line 1)
20419 (cond
20420 (arg
20421 (org-move-to-column cc t)
20422 (insert ": \n")
20423 (forward-line -1))
20424 ((and off (looking-at re))
20425 (replace-match "" t t nil 1))
20426 ((not off) (org-move-to-column cc t) (insert ": ")))
20427 (forward-line 1)))
20428 (save-excursion
20429 (org-back-to-heading)
20430 (cond
20431 ((looking-at (format org-heading-keyword-regexp-format
20432 org-quote-string))
20433 (goto-char (match-end 1))
20434 (looking-at (concat " +" org-quote-string))
20435 (replace-match "" t t)
20436 (when (eolp) (insert " ")))
20437 ((looking-at org-outline-regexp)
20438 (goto-char (match-end 0))
20439 (insert org-quote-string " ")))))))
20441 (defun org-reftex-citation ()
20442 "Use reftex-citation to insert a citation into the buffer.
20443 This looks for a line like
20445 #+BIBLIOGRAPHY: foo plain option:-d
20447 and derives from it that foo.bib is the bibliography file relevant
20448 for this document. It then installs the necessary environment for RefTeX
20449 to work in this buffer and calls `reftex-citation' to insert a citation
20450 into the buffer.
20452 Export of such citations to both LaTeX and HTML is handled by the contributed
20453 package org-exp-bibtex by Taru Karttunen."
20454 (interactive)
20455 (let ((reftex-docstruct-symbol 'rds)
20456 (reftex-cite-format "\\cite{%l}")
20457 rds bib)
20458 (save-excursion
20459 (save-restriction
20460 (widen)
20461 (let ((case-fold-search t)
20462 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20463 (if (not (save-excursion
20464 (or (re-search-forward re nil t)
20465 (re-search-backward re nil t))))
20466 (error "No bibliography defined in file")
20467 (setq bib (concat (match-string 1) ".bib")
20468 rds (list (list 'bib bib)))))))
20469 (call-interactively 'reftex-citation)))
20471 ;;;; Functions extending outline functionality
20473 (defun org-beginning-of-line (&optional arg)
20474 "Go to the beginning of the current line. If that is invisible, continue
20475 to a visible line beginning. This makes the function of C-a more intuitive.
20476 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20477 first attempt, and only move to after the tags when the cursor is already
20478 beyond the end of the headline."
20479 (interactive "P")
20480 (let ((pos (point))
20481 (special (if (consp org-special-ctrl-a/e)
20482 (car org-special-ctrl-a/e)
20483 org-special-ctrl-a/e))
20484 refpos)
20485 (if (org-bound-and-true-p line-move-visual)
20486 (beginning-of-visual-line 1)
20487 (beginning-of-line 1))
20488 (if (and arg (fboundp 'move-beginning-of-line))
20489 (call-interactively 'move-beginning-of-line)
20490 (if (bobp)
20492 (backward-char 1)
20493 (if (org-truely-invisible-p)
20494 (while (and (not (bobp)) (org-truely-invisible-p))
20495 (backward-char 1)
20496 (beginning-of-line 1))
20497 (forward-char 1))))
20498 (when special
20499 (cond
20500 ((and (looking-at org-complex-heading-regexp)
20501 (= (char-after (match-end 1)) ?\ ))
20502 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20503 (point-at-eol)))
20504 (goto-char
20505 (if (eq special t)
20506 (cond ((> pos refpos) refpos)
20507 ((= pos (point)) refpos)
20508 (t (point)))
20509 (cond ((> pos (point)) (point))
20510 ((not (eq last-command this-command)) (point))
20511 (t refpos)))))
20512 ((org-at-item-p)
20513 ;; Being at an item and not looking at an the item means point
20514 ;; was previously moved to beginning of a visual line, which
20515 ;; doesn't contain the item. Therefore, do nothing special,
20516 ;; just stay here.
20517 (when (looking-at org-list-full-item-re)
20518 ;; Set special position at first white space character after
20519 ;; bullet, and check-box, if any.
20520 (let ((after-bullet
20521 (let ((box (match-end 3)))
20522 (if (not box) (match-end 1)
20523 (let ((after (char-after box)))
20524 (if (and after (= after ? )) (1+ box) box))))))
20525 ;; Special case: Move point to special position when
20526 ;; currently after it or at beginning of line.
20527 (if (eq special t)
20528 (when (or (> pos after-bullet) (= (point) pos))
20529 (goto-char after-bullet))
20530 ;; Reversed case: Move point to special position when
20531 ;; point was already at beginning of line and command is
20532 ;; repeated.
20533 (when (and (= (point) pos) (eq last-command this-command))
20534 (goto-char after-bullet))))))))
20535 (org-no-warnings
20536 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20538 (defun org-end-of-line (&optional arg)
20539 "Go to the end of the line.
20540 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20541 first attempt, and only move to after the tags when the cursor is already
20542 beyond the end of the headline."
20543 (interactive "P")
20544 (let ((special (if (consp org-special-ctrl-a/e)
20545 (cdr org-special-ctrl-a/e)
20546 org-special-ctrl-a/e)))
20547 (cond
20548 ((or (not special) arg
20549 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20550 (call-interactively
20551 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20552 ((fboundp 'move-end-of-line) 'move-end-of-line)
20553 (t 'end-of-line))))
20554 ((org-at-heading-p)
20555 (let ((pos (point)))
20556 (beginning-of-line 1)
20557 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20558 (if (eq special t)
20559 (if (or (< pos (match-beginning 1))
20560 (= pos (match-end 0)))
20561 (goto-char (match-beginning 1))
20562 (goto-char (match-end 0)))
20563 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20564 (goto-char (match-end 0))
20565 (goto-char (match-beginning 1))))
20566 (call-interactively (if (fboundp 'move-end-of-line)
20567 'move-end-of-line
20568 'end-of-line)))))
20569 ((org-at-drawer-p)
20570 (move-end-of-line 1)
20571 (when (overlays-at (1- (point))) (backward-char 1)))
20572 ;; At an item: Move before any hidden text.
20573 (t (call-interactively
20574 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20575 ((fboundp 'move-end-of-line) 'move-end-of-line)
20576 (t 'end-of-line)))))
20577 (org-no-warnings
20578 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20580 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20581 (define-key org-mode-map "\C-e" 'org-end-of-line)
20583 (defun org-backward-sentence (&optional arg)
20584 "Go to beginning of sentence, or beginning of table field.
20585 This will call `backward-sentence' or `org-table-beginning-of-field',
20586 depending on context."
20587 (interactive "P")
20588 (cond
20589 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20590 (t (call-interactively 'backward-sentence))))
20592 (defun org-forward-sentence (&optional arg)
20593 "Go to end of sentence, or end of table field.
20594 This will call `forward-sentence' or `org-table-end-of-field',
20595 depending on context."
20596 (interactive "P")
20597 (cond
20598 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20599 (t (call-interactively 'forward-sentence))))
20601 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20602 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20604 (defun org-kill-line (&optional arg)
20605 "Kill line, to tags or end of line."
20606 (interactive "P")
20607 (cond
20608 ((or (not org-special-ctrl-k)
20609 (bolp)
20610 (not (org-at-heading-p)))
20611 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20612 org-ctrl-k-protect-subtree)
20613 (if (or (eq org-ctrl-k-protect-subtree 'error)
20614 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20615 (error "C-k aborted - would kill hidden subtree")))
20616 (call-interactively 'kill-line))
20617 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20618 (kill-region (point) (match-beginning 1))
20619 (org-set-tags nil t))
20620 (t (kill-region (point) (point-at-eol)))))
20622 (define-key org-mode-map "\C-k" 'org-kill-line)
20624 (defun org-yank (&optional arg)
20625 "Yank. If the kill is a subtree, treat it specially.
20626 This command will look at the current kill and check if is a single
20627 subtree, or a series of subtrees[1]. If it passes the test, and if the
20628 cursor is at the beginning of a line or after the stars of a currently
20629 empty headline, then the yank is handled specially. How exactly depends
20630 on the value of the following variables, both set by default.
20632 org-yank-folded-subtrees
20633 When set, the subtree(s) will be folded after insertion, but only
20634 if doing so would now swallow text after the yanked text.
20636 org-yank-adjusted-subtrees
20637 When set, the subtree will be promoted or demoted in order to
20638 fit into the local outline tree structure, which means that the level
20639 will be adjusted so that it becomes the smaller one of the two
20640 *visible* surrounding headings.
20642 Any prefix to this command will cause `yank' to be called directly with
20643 no special treatment. In particular, a simple \\[universal-argument] prefix \
20644 will just
20645 plainly yank the text as it is.
20647 \[1] The test checks if the first non-white line is a heading
20648 and if there are no other headings with fewer stars."
20649 (interactive "P")
20650 (org-yank-generic 'yank arg))
20652 (defun org-yank-generic (command arg)
20653 "Perform some yank-like command.
20655 This function implements the behavior described in the `org-yank'
20656 documentation. However, it has been generalized to work for any
20657 interactive command with similar behavior."
20659 ;; pretend to be command COMMAND
20660 (setq this-command command)
20662 (if arg
20663 (call-interactively command)
20665 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20666 (and (org-kill-is-subtree-p)
20667 (or (bolp)
20668 (and (looking-at "[ \t]*$")
20669 (string-match
20670 "\\`\\*+\\'"
20671 (buffer-substring (point-at-bol) (point)))))))
20672 swallowp)
20673 (cond
20674 ((and subtreep org-yank-folded-subtrees)
20675 (let ((beg (point))
20676 end)
20677 (if (and subtreep org-yank-adjusted-subtrees)
20678 (org-paste-subtree nil nil 'for-yank)
20679 (call-interactively command))
20681 (setq end (point))
20682 (goto-char beg)
20683 (when (and (bolp) subtreep
20684 (not (setq swallowp
20685 (org-yank-folding-would-swallow-text beg end))))
20686 (org-with-limited-levels
20687 (or (looking-at org-outline-regexp)
20688 (re-search-forward org-outline-regexp-bol end t))
20689 (while (and (< (point) end) (looking-at org-outline-regexp))
20690 (hide-subtree)
20691 (org-cycle-show-empty-lines 'folded)
20692 (condition-case nil
20693 (outline-forward-same-level 1)
20694 (error (goto-char end))))))
20695 (when swallowp
20696 (message
20697 "Inserted text not folded because that would swallow text"))
20699 (goto-char end)
20700 (skip-chars-forward " \t\n\r")
20701 (beginning-of-line 1)
20702 (push-mark beg 'nomsg)))
20703 ((and subtreep org-yank-adjusted-subtrees)
20704 (let ((beg (point-at-bol)))
20705 (org-paste-subtree nil nil 'for-yank)
20706 (push-mark beg 'nomsg)))
20708 (call-interactively command))))))
20710 (defun org-yank-folding-would-swallow-text (beg end)
20711 "Would hide-subtree at BEG swallow any text after END?"
20712 (let (level)
20713 (org-with-limited-levels
20714 (save-excursion
20715 (goto-char beg)
20716 (when (or (looking-at org-outline-regexp)
20717 (re-search-forward org-outline-regexp-bol end t))
20718 (setq level (org-outline-level)))
20719 (goto-char end)
20720 (skip-chars-forward " \t\r\n\v\f")
20721 (if (or (eobp)
20722 (and (bolp) (looking-at org-outline-regexp)
20723 (<= (org-outline-level) level)))
20724 nil ; Nothing would be swallowed
20725 t))))) ; something would swallow
20727 (define-key org-mode-map "\C-y" 'org-yank)
20729 (defun org-truely-invisible-p ()
20730 "Check if point is at a character currently not visible.
20731 This version does not only check the character property, but also
20732 `visible-mode'."
20733 ;; Early versions of noutline don't have `outline-invisible-p'.
20734 (if (org-bound-and-true-p visible-mode)
20736 (outline-invisible-p)))
20738 (defun org-invisible-p2 ()
20739 "Check if point is at a character currently not visible."
20740 (save-excursion
20741 (if (and (eolp) (not (bobp))) (backward-char 1))
20742 ;; Early versions of noutline don't have `outline-invisible-p'.
20743 (outline-invisible-p)))
20745 (defun org-back-to-heading (&optional invisible-ok)
20746 "Call `outline-back-to-heading', but provide a better error message."
20747 (condition-case nil
20748 (outline-back-to-heading invisible-ok)
20749 (error (error "Before first headline at position %d in buffer %s"
20750 (point) (current-buffer)))))
20752 (defun org-beginning-of-defun ()
20753 "Go to the beginning of the subtree, i.e. back to the heading."
20754 (org-back-to-heading))
20755 (defun org-end-of-defun ()
20756 "Go to the end of the subtree."
20757 (org-end-of-subtree nil t))
20759 (defun org-before-first-heading-p ()
20760 "Before first heading?"
20761 (save-excursion
20762 (end-of-line)
20763 (null (re-search-backward org-outline-regexp-bol nil t))))
20765 (defun org-at-heading-p (&optional ignored)
20766 (outline-on-heading-p t))
20767 ;; Compatibility alias with Org versions < 7.8.03
20768 (defalias 'org-on-heading-p 'org-at-heading-p)
20770 (defun org-at-drawer-p nil
20771 "Whether point is at a drawer."
20772 (save-excursion
20773 (move-beginning-of-line 1)
20774 (looking-at org-drawer-regexp)))
20776 (defun org-point-at-end-of-empty-headline ()
20777 "If point is at the end of an empty headline, return t, else nil.
20778 If the heading only contains a TODO keyword, it is still still considered
20779 empty."
20780 (and (looking-at "[ \t]*$")
20781 (save-excursion
20782 (beginning-of-line 1)
20783 (let ((case-fold-search nil))
20784 (looking-at org-todo-line-regexp)))
20785 (string= (match-string 3) "")))
20787 (defun org-at-heading-or-item-p ()
20788 (or (org-at-heading-p) (org-at-item-p)))
20790 (defun org-at-target-p ()
20791 (or (org-in-regexp org-radio-target-regexp)
20792 (org-in-regexp org-target-regexp)))
20793 ;; Compatibility alias with Org versions < 7.8.03
20794 (defalias 'org-on-target-p 'org-at-target-p)
20796 (defun org-up-heading-all (arg)
20797 "Move to the heading line of which the present line is a subheading.
20798 This function considers both visible and invisible heading lines.
20799 With argument, move up ARG levels."
20800 (if (fboundp 'outline-up-heading-all)
20801 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20802 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20804 (defun org-up-heading-safe ()
20805 "Move to the heading line of which the present line is a subheading.
20806 This version will not throw an error. It will return the level of the
20807 headline found, or nil if no higher level is found.
20809 Also, this function will be a lot faster than `outline-up-heading',
20810 because it relies on stars being the outline starters. This can really
20811 make a significant difference in outlines with very many siblings."
20812 (let (start-level re)
20813 (org-back-to-heading t)
20814 (setq start-level (funcall outline-level))
20815 (if (equal start-level 1)
20817 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20818 (if (re-search-backward re nil t)
20819 (funcall outline-level)))))
20821 (defun org-first-sibling-p ()
20822 "Is this heading the first child of its parents?"
20823 (interactive)
20824 (let ((re org-outline-regexp-bol)
20825 level l)
20826 (unless (org-at-heading-p t)
20827 (error "Not at a heading"))
20828 (setq level (funcall outline-level))
20829 (save-excursion
20830 (if (not (re-search-backward re nil t))
20832 (setq l (funcall outline-level))
20833 (< l level)))))
20835 (defun org-goto-sibling (&optional previous)
20836 "Goto the next sibling, even if it is invisible.
20837 When PREVIOUS is set, go to the previous sibling instead. Returns t
20838 when a sibling was found. When none is found, return nil and don't
20839 move point."
20840 (let ((fun (if previous 're-search-backward 're-search-forward))
20841 (pos (point))
20842 (re org-outline-regexp-bol)
20843 level l)
20844 (when (condition-case nil (org-back-to-heading t) (error nil))
20845 (setq level (funcall outline-level))
20846 (catch 'exit
20847 (or previous (forward-char 1))
20848 (while (funcall fun re nil t)
20849 (setq l (funcall outline-level))
20850 (when (< l level) (goto-char pos) (throw 'exit nil))
20851 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20852 (goto-char pos)
20853 nil))))
20855 (defun org-show-siblings ()
20856 "Show all siblings of the current headline."
20857 (save-excursion
20858 (while (org-goto-sibling) (org-flag-heading nil)))
20859 (save-excursion
20860 (while (org-goto-sibling 'previous)
20861 (org-flag-heading nil))))
20863 (defun org-goto-first-child ()
20864 "Goto the first child, even if it is invisible.
20865 Return t when a child was found. Otherwise don't move point and
20866 return nil."
20867 (let (level (pos (point)) (re org-outline-regexp-bol))
20868 (when (condition-case nil (org-back-to-heading t) (error nil))
20869 (setq level (outline-level))
20870 (forward-char 1)
20871 (if (and (re-search-forward re nil t) (> (outline-level) level))
20872 (progn (goto-char (match-beginning 0)) t)
20873 (goto-char pos) nil))))
20875 (defun org-show-hidden-entry ()
20876 "Show an entry where even the heading is hidden."
20877 (save-excursion
20878 (org-show-entry)))
20880 (defun org-flag-heading (flag &optional entry)
20881 "Flag the current heading. FLAG non-nil means make invisible.
20882 When ENTRY is non-nil, show the entire entry."
20883 (save-excursion
20884 (org-back-to-heading t)
20885 ;; Check if we should show the entire entry
20886 (if entry
20887 (progn
20888 (org-show-entry)
20889 (save-excursion
20890 (and (outline-next-heading)
20891 (org-flag-heading nil))))
20892 (outline-flag-region (max (point-min) (1- (point)))
20893 (save-excursion (outline-end-of-heading) (point))
20894 flag))))
20896 (defun org-get-next-sibling ()
20897 "Move to next heading of the same level, and return point.
20898 If there is no such heading, return nil.
20899 This is like outline-next-sibling, but invisible headings are ok."
20900 (let ((level (funcall outline-level)))
20901 (outline-next-heading)
20902 (while (and (not (eobp)) (> (funcall outline-level) level))
20903 (outline-next-heading))
20904 (if (or (eobp) (< (funcall outline-level) level))
20906 (point))))
20908 (defun org-get-last-sibling ()
20909 "Move to previous heading of the same level, and return point.
20910 If there is no such heading, return nil."
20911 (let ((opoint (point))
20912 (level (funcall outline-level)))
20913 (outline-previous-heading)
20914 (when (and (/= (point) opoint) (outline-on-heading-p t))
20915 (while (and (> (funcall outline-level) level)
20916 (not (bobp)))
20917 (outline-previous-heading))
20918 (if (< (funcall outline-level) level)
20920 (point)))))
20922 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20923 ;; This contains an exact copy of the original function, but it uses
20924 ;; `org-back-to-heading', to make it work also in invisible
20925 ;; trees. And is uses an invisible-OK argument.
20926 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20927 ;; Furthermore, when used inside Org, finding the end of a large subtree
20928 ;; with many children and grandchildren etc, this can be much faster
20929 ;; than the outline version.
20930 (org-back-to-heading invisible-OK)
20931 (let ((first t)
20932 (level (funcall outline-level)))
20933 (if (and (eq major-mode 'org-mode) (< level 1000))
20934 ;; A true heading (not a plain list item), in Org-mode
20935 ;; This means we can easily find the end by looking
20936 ;; only for the right number of stars. Using a regexp to do
20937 ;; this is so much faster than using a Lisp loop.
20938 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20939 (forward-char 1)
20940 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20941 ;; something else, do it the slow way
20942 (while (and (not (eobp))
20943 (or first (> (funcall outline-level) level)))
20944 (setq first nil)
20945 (outline-next-heading)))
20946 (unless to-heading
20947 (if (memq (preceding-char) '(?\n ?\^M))
20948 (progn
20949 ;; Go to end of line before heading
20950 (forward-char -1)
20951 (if (memq (preceding-char) '(?\n ?\^M))
20952 ;; leave blank line before heading
20953 (forward-char -1))))))
20954 (point))
20956 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20957 "Use Org version in org-mode, for dramatic speed-up."
20958 (if (eq major-mode 'org-mode)
20959 (progn
20960 (org-end-of-subtree nil t)
20961 (unless (eobp) (backward-char 1)))
20962 ad-do-it))
20964 (defun org-end-of-meta-data-and-drawers ()
20965 "Jump to the first text after meta data and drawers in the current entry.
20966 This will move over empty lines, lines with planning time stamps,
20967 clocking lines, and drawers."
20968 (org-back-to-heading t)
20969 (let ((end (save-excursion (outline-next-heading) (point)))
20970 (re (concat "\\(" org-drawer-regexp "\\)"
20971 "\\|" "[ \t]*" org-keyword-time-regexp)))
20972 (forward-line 1)
20973 (while (re-search-forward re end t)
20974 (if (not (match-end 1))
20975 ;; empty or planning line
20976 (forward-line 1)
20977 ;; a drawer, find the end
20978 (re-search-forward "^[ \t]*:END:" end 'move)
20979 (forward-line 1)))
20980 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20981 (point)))
20983 (defun org-forward-same-level (arg &optional invisible-ok)
20984 "Move forward to the arg'th subheading at same level as this one.
20985 Stop at the first and last subheadings of a superior heading.
20986 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20987 it wil also look at invisible ones."
20988 (interactive "p")
20989 (org-back-to-heading invisible-ok)
20990 (org-at-heading-p)
20991 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20992 (re (format "^\\*\\{1,%d\\} " level))
20994 (forward-char 1)
20995 (while (> arg 0)
20996 (while (and (re-search-forward re nil 'move)
20997 (setq l (- (match-end 0) (match-beginning 0) 1))
20998 (= l level)
20999 (not invisible-ok)
21000 (progn (backward-char 1) (outline-invisible-p)))
21001 (if (< l level) (setq arg 1)))
21002 (setq arg (1- arg)))
21003 (beginning-of-line 1)))
21005 (defun org-backward-same-level (arg &optional invisible-ok)
21006 "Move backward to the arg'th subheading at same level as this one.
21007 Stop at the first and last subheadings of a superior heading."
21008 (interactive "p")
21009 (org-back-to-heading)
21010 (org-at-heading-p)
21011 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21012 (re (format "^\\*\\{1,%d\\} " level))
21014 (while (> arg 0)
21015 (while (and (re-search-backward re nil 'move)
21016 (setq l (- (match-end 0) (match-beginning 0) 1))
21017 (= l level)
21018 (not invisible-ok)
21019 (outline-invisible-p))
21020 (if (< l level) (setq arg 1)))
21021 (setq arg (1- arg)))))
21023 (defun org-show-subtree ()
21024 "Show everything after this heading at deeper levels."
21025 (interactive)
21026 (outline-flag-region
21027 (point)
21028 (save-excursion
21029 (org-end-of-subtree t t))
21030 nil))
21032 (defun org-show-entry ()
21033 "Show the body directly following this heading.
21034 Show the heading too, if it is currently invisible."
21035 (interactive)
21036 (save-excursion
21037 (condition-case nil
21038 (progn
21039 (org-back-to-heading t)
21040 (outline-flag-region
21041 (max (point-min) (1- (point)))
21042 (save-excursion
21043 (if (re-search-forward
21044 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21045 (match-beginning 1)
21046 (point-max)))
21047 nil)
21048 (org-cycle-hide-drawers 'children))
21049 (error nil))))
21051 (defun org-make-options-regexp (kwds &optional extra)
21052 "Make a regular expression for keyword lines."
21053 (concat
21055 "#?[ \t]*\\+\\("
21056 (mapconcat 'regexp-quote kwds "\\|")
21057 (if extra (concat "\\|" extra))
21058 "\\):[ \t]*"
21059 "\\(.*\\)"))
21061 ;; Make isearch reveal the necessary context
21062 (defun org-isearch-end ()
21063 "Reveal context after isearch exits."
21064 (when isearch-success ; only if search was successful
21065 (if (featurep 'xemacs)
21066 ;; Under XEmacs, the hook is run in the correct place,
21067 ;; we directly show the context.
21068 (org-show-context 'isearch)
21069 ;; In Emacs the hook runs *before* restoring the overlays.
21070 ;; So we have to use a one-time post-command-hook to do this.
21071 ;; (Emacs 22 has a special variable, see function `org-mode')
21072 (unless (and (boundp 'isearch-mode-end-hook-quit)
21073 isearch-mode-end-hook-quit)
21074 ;; Only when the isearch was not quitted.
21075 (org-add-hook 'post-command-hook 'org-isearch-post-command
21076 'append 'local)))))
21078 (defun org-isearch-post-command ()
21079 "Remove self from hook, and show context."
21080 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21081 (org-show-context 'isearch))
21084 ;;;; Integration with and fixes for other packages
21086 ;;; Imenu support
21088 (defvar org-imenu-markers nil
21089 "All markers currently used by Imenu.")
21090 (make-variable-buffer-local 'org-imenu-markers)
21092 (defun org-imenu-new-marker (&optional pos)
21093 "Return a new marker for use by Imenu, and remember the marker."
21094 (let ((m (make-marker)))
21095 (move-marker m (or pos (point)))
21096 (push m org-imenu-markers)
21099 (defun org-imenu-get-tree ()
21100 "Produce the index for Imenu."
21101 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21102 (setq org-imenu-markers nil)
21103 (let* ((n org-imenu-depth)
21104 (re (concat "^" (org-get-limited-outline-regexp)))
21105 (subs (make-vector (1+ n) nil))
21106 (last-level 0)
21107 m level head)
21108 (save-excursion
21109 (save-restriction
21110 (widen)
21111 (goto-char (point-max))
21112 (while (re-search-backward re nil t)
21113 (setq level (org-reduced-level (funcall outline-level)))
21114 (when (and (<= level n)
21115 (looking-at org-complex-heading-regexp))
21116 (setq head (org-link-display-format
21117 (org-match-string-no-properties 4))
21118 m (org-imenu-new-marker))
21119 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21120 (if (>= level last-level)
21121 (push (cons head m) (aref subs level))
21122 (push (cons head (aref subs (1+ level))) (aref subs level))
21123 (loop for i from (1+ level) to n do (aset subs i nil)))
21124 (setq last-level level)))))
21125 (aref subs 1)))
21127 (eval-after-load "imenu"
21128 '(progn
21129 (add-hook 'imenu-after-jump-hook
21130 (lambda ()
21131 (if (eq major-mode 'org-mode)
21132 (org-show-context 'org-goto))))))
21134 (defun org-link-display-format (link)
21135 "Replace a link with either the description, or the link target
21136 if no description is present"
21137 (save-match-data
21138 (if (string-match org-bracket-link-analytic-regexp link)
21139 (replace-match (if (match-end 5)
21140 (match-string 5 link)
21141 (concat (match-string 1 link)
21142 (match-string 3 link)))
21143 nil t link)
21144 link)))
21146 (defun org-toggle-link-display ()
21147 "Toggle the literal or descriptive display of links."
21148 (interactive)
21149 (if org-descriptive-links
21150 (progn (org-remove-from-invisibility-spec '(org-link))
21151 (org-restart-font-lock)
21152 (setq org-descriptive-links nil))
21153 (progn (add-to-invisibility-spec '(org-link))
21154 (org-restart-font-lock)
21155 (setq org-descriptive-links t))))
21157 ;; Speedbar support
21159 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21160 "Overlay marking the agenda restriction line in speedbar.")
21161 (overlay-put org-speedbar-restriction-lock-overlay
21162 'face 'org-agenda-restriction-lock)
21163 (overlay-put org-speedbar-restriction-lock-overlay
21164 'help-echo "Agendas are currently limited to this item.")
21165 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21167 (defun org-speedbar-set-agenda-restriction ()
21168 "Restrict future agenda commands to the location at point in speedbar.
21169 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21170 (interactive)
21171 (require 'org-agenda)
21172 (let (p m tp np dir txt)
21173 (cond
21174 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21175 'org-imenu t))
21176 (setq m (get-text-property p 'org-imenu-marker))
21177 (with-current-buffer (marker-buffer m)
21178 (goto-char m)
21179 (org-agenda-set-restriction-lock 'subtree)))
21180 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21181 'speedbar-function 'speedbar-find-file))
21182 (setq tp (previous-single-property-change
21183 (1+ p) 'speedbar-function)
21184 np (next-single-property-change
21185 tp 'speedbar-function)
21186 dir (speedbar-line-directory)
21187 txt (buffer-substring-no-properties (or tp (point-min))
21188 (or np (point-max))))
21189 (with-current-buffer (find-file-noselect
21190 (let ((default-directory dir))
21191 (expand-file-name txt)))
21192 (unless (eq major-mode 'org-mode)
21193 (error "Cannot restrict to non-Org-mode file"))
21194 (org-agenda-set-restriction-lock 'file)))
21195 (t (error "Don't know how to restrict Org-mode's agenda")))
21196 (move-overlay org-speedbar-restriction-lock-overlay
21197 (point-at-bol) (point-at-eol))
21198 (setq current-prefix-arg nil)
21199 (org-agenda-maybe-redo)))
21201 (eval-after-load "speedbar"
21202 '(progn
21203 (speedbar-add-supported-extension ".org")
21204 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21205 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21206 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21207 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21208 (add-hook 'speedbar-visiting-tag-hook
21209 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21211 ;;; Fixes and Hacks for problems with other packages
21213 ;; Make flyspell not check words in links, to not mess up our keymap
21214 (defun org-mode-flyspell-verify ()
21215 "Don't let flyspell put overlays at active buttons, or on
21216 {todo,all-time,additional-option-like}-keywords."
21217 (let ((pos (max (1- (point)) (point-min)))
21218 (word (thing-at-point 'word)))
21219 (and (not (get-text-property pos 'keymap))
21220 (not (get-text-property pos 'org-no-flyspell))
21221 (not (member word org-todo-keywords-1))
21222 (not (member word org-all-time-keywords))
21223 (not (member word org-additional-option-like-keywords)))))
21225 (defun org-remove-flyspell-overlays-in (beg end)
21226 "Remove flyspell overlays in region."
21227 (and (org-bound-and-true-p flyspell-mode)
21228 (fboundp 'flyspell-delete-region-overlays)
21229 (flyspell-delete-region-overlays beg end))
21230 (add-text-properties beg end '(org-no-flyspell t)))
21232 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21233 (eval-after-load "bookmark"
21234 '(if (boundp 'bookmark-after-jump-hook)
21235 ;; We can use the hook
21236 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21237 ;; Hook not available, use advice
21238 (defadvice bookmark-jump (after org-make-visible activate)
21239 "Make the position visible."
21240 (org-bookmark-jump-unhide))))
21242 ;; Make sure saveplace shows the location if it was hidden
21243 (eval-after-load "saveplace"
21244 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21245 "Make the position visible."
21246 (org-bookmark-jump-unhide)))
21248 ;; Make sure ecb shows the location if it was hidden
21249 (eval-after-load "ecb"
21250 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21251 "Make hierarchy visible when jumping into location from ECB tree buffer."
21252 (if (eq major-mode 'org-mode)
21253 (org-show-context))))
21255 (defun org-bookmark-jump-unhide ()
21256 "Unhide the current position, to show the bookmark location."
21257 (and (eq major-mode 'org-mode)
21258 (or (outline-invisible-p)
21259 (save-excursion (goto-char (max (point-min) (1- (point))))
21260 (outline-invisible-p)))
21261 (org-show-context 'bookmark-jump)))
21263 ;; Make session.el ignore our circular variable
21264 (eval-after-load "session"
21265 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21267 ;;;; Experimental code
21269 (defun org-closed-in-range ()
21270 "Sparse tree of items closed in a certain time range.
21271 Still experimental, may disappear in the future."
21272 (interactive)
21273 ;; Get the time interval from the user.
21274 (let* ((time1 (org-float-time
21275 (org-read-date nil 'to-time nil "Starting date: ")))
21276 (time2 (org-float-time
21277 (org-read-date nil 'to-time nil "End date:")))
21278 ;; callback function
21279 (callback (lambda ()
21280 (let ((time
21281 (org-float-time
21282 (apply 'encode-time
21283 (org-parse-time-string
21284 (match-string 1))))))
21285 ;; check if time in interval
21286 (and (>= time time1) (<= time time2))))))
21287 ;; make tree, check each match with the callback
21288 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21290 ;;;; Finish up
21292 (provide 'org)
21294 (run-hooks 'org-load-hook)
21296 ;;; org.el ends here