Bump to version 7.8.10.
[org-mode.git] / lisp / org.el
blob4710bd5bd8681bcebedaaa466d672eea87bd0f45
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.10
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.10"
210 "The version number of the file org.el.")
212 ;;;###autoload
213 (defun org-version (&optional here)
214 "Show the org-mode version in the echo area.
215 With prefix arg HERE, insert it at point."
216 (interactive "P")
217 (let* ((origin default-directory)
218 (version org-version)
219 (git-version)
220 (dir (concat (file-name-directory (locate-library "org")) "../" )))
221 (when (and (file-exists-p (expand-file-name ".git" dir))
222 (executable-find "git"))
223 (unwind-protect
224 (progn
225 (cd dir)
226 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
227 (with-current-buffer "*Shell Command Output*"
228 (goto-char (point-min))
229 (setq git-version (buffer-substring (point) (point-at-eol))))
230 (subst-char-in-string ?- ?. git-version t)
231 (when (string-match "\\S-"
232 (shell-command-to-string
233 "git diff-index --name-only HEAD --"))
234 (setq git-version (concat git-version ".dirty")))
235 (setq version (concat version " (" git-version ")"))))
236 (cd origin)))
237 (setq version (format "Org-mode version %s" version))
238 (if here (insert version))
239 (message version)))
241 ;;; Compatibility constants
243 ;;; The custom variables
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
290 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
498 Not all export backends support this, but HTML does.
500 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-comment-string "COMMENT"
677 "Entries starting with this keyword will never be exported.
678 An entry can be toggled between COMMENT and normal with
679 \\[org-toggle-comment].
680 Changes become only effective after restarting Emacs."
681 :group 'org-keywords
682 :type 'string)
684 (defcustom org-quote-string "QUOTE"
685 "Entries starting with this keyword will be exported in fixed-width font.
686 Quoting applies only to the text in the entry following the headline, and does
687 not extend beyond the next headline, even if that is lower level.
688 An entry can be toggled between QUOTE and normal with
689 \\[org-toggle-fixed-width-section]."
690 :group 'org-keywords
691 :type 'string)
693 (defconst org-repeat-re
694 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
695 "Regular expression for specifying repeated events.
696 After a match, group 1 contains the repeat expression.")
698 (defgroup org-structure nil
699 "Options concerning the general structure of Org-mode files."
700 :tag "Org Structure"
701 :group 'org)
703 (defgroup org-reveal-location nil
704 "Options about how to make context of a location visible."
705 :tag "Org Reveal Location"
706 :group 'org-structure)
708 (defconst org-context-choice
709 '(choice
710 (const :tag "Always" t)
711 (const :tag "Never" nil)
712 (repeat :greedy t :tag "Individual contexts"
713 (cons
714 (choice :tag "Context"
715 (const agenda)
716 (const org-goto)
717 (const occur-tree)
718 (const tags-tree)
719 (const link-search)
720 (const mark-goto)
721 (const bookmark-jump)
722 (const isearch)
723 (const default))
724 (boolean))))
725 "Contexts for the reveal options.")
727 (defcustom org-show-hierarchy-above '((default . t))
728 "Non-nil means show full hierarchy when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the hierarchy of headings
731 above the exposed location is shown.
732 Turning this off for example for sparse trees makes them very compact.
733 Instead of t, this can also be an alist specifying this option for different
734 contexts. Valid contexts are
735 agenda when exposing an entry from the agenda
736 org-goto when using the command `org-goto' on key C-c C-j
737 occur-tree when using the command `org-occur' on key C-c /
738 tags-tree when constructing a sparse tree based on tags matches
739 link-search when exposing search matches associated with a link
740 mark-goto when exposing the jump goal of a mark
741 bookmark-jump when exposing a bookmark location
742 isearch when exiting from an incremental search
743 default default for all contexts not set explicitly"
744 :group 'org-reveal-location
745 :type org-context-choice)
747 (defcustom org-show-following-heading '((default . nil))
748 "Non-nil means show following heading when revealing a location.
749 Org-mode often shows locations in an org-mode file which might have
750 been invisible before. When this is set, the heading following the
751 match is shown.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-siblings '((default . nil) (isearch t))
761 "Non-nil means show all sibling heading when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the sibling of the current entry
764 heading are all made visible. If `org-show-hierarchy-above' is t,
765 the same happens on each level of the hierarchy above the current entry.
767 By default this is on for the isearch context, off for all other contexts.
768 Turning this off for example for sparse trees makes them very compact,
769 but makes it harder to edit the location of the match. In such a case,
770 use the command \\[org-reveal] to show more context.
771 Instead of t, this can also be an alist specifying this option for different
772 contexts. See `org-show-hierarchy-above' for valid contexts."
773 :group 'org-reveal-location
774 :type org-context-choice)
776 (defcustom org-show-entry-below '((default . nil))
777 "Non-nil means show the entry below a headline when revealing a location.
778 Org-mode often shows locations in an org-mode file which might have
779 been invisible before. When this is set, the text below the headline that is
780 exposed is also shown.
782 By default this is off for all contexts.
783 Instead of t, this can also be an alist specifying this option for different
784 contexts. See `org-show-hierarchy-above' for valid contexts."
785 :group 'org-reveal-location
786 :type org-context-choice)
788 (defcustom org-indirect-buffer-display 'other-window
789 "How should indirect tree buffers be displayed?
790 This applies to indirect buffers created with the commands
791 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
792 Valid values are:
793 current-window Display in the current window
794 other-window Just display in another window.
795 dedicated-frame Create one new frame, and re-use it each time.
796 new-frame Make a new frame each time. Note that in this case
797 previously-made indirect buffers are kept, and you need to
798 kill these buffers yourself."
799 :group 'org-structure
800 :group 'org-agenda-windows
801 :type '(choice
802 (const :tag "In current window" current-window)
803 (const :tag "In current frame, other window" other-window)
804 (const :tag "Each time a new frame" new-frame)
805 (const :tag "One dedicated frame" dedicated-frame)))
807 (defcustom org-use-speed-commands nil
808 "Non-nil means activate single letter commands at beginning of a headline.
809 This may also be a function to test for appropriate locations where speed
810 commands should be active."
811 :group 'org-structure
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "At beginning of headline stars" t)
815 (function)))
817 (defcustom org-speed-commands-user nil
818 "Alist of additional speed commands.
819 This list will be checked before `org-speed-commands-default'
820 when the variable `org-use-speed-commands' is non-nil
821 and when the cursor is at the beginning of a headline.
822 The car if each entry is a string with a single letter, which must
823 be assigned to `self-insert-command' in the global map.
824 The cdr is either a command to be called interactively, a function
825 to be called, or a form to be evaluated.
826 An entry that is just a list with a single string will be interpreted
827 as a descriptive headline that will be added when listing the speed
828 commands in the Help buffer using the `?' speed command."
829 :group 'org-structure
830 :type '(repeat :value ("k" . ignore)
831 (choice :value ("k" . ignore)
832 (list :tag "Descriptive Headline" (string :tag "Headline"))
833 (cons :tag "Letter and Command"
834 (string :tag "Command letter")
835 (choice
836 (function)
837 (sexp))))))
839 (defgroup org-cycle nil
840 "Options concerning visibility cycling in Org-mode."
841 :tag "Org Cycle"
842 :group 'org-structure)
844 (defcustom org-cycle-skip-children-state-if-no-children t
845 "Non-nil means skip CHILDREN state in entries that don't have any."
846 :group 'org-cycle
847 :type 'boolean)
849 (defcustom org-cycle-max-level nil
850 "Maximum level which should still be subject to visibility cycling.
851 Levels higher than this will, for cycling, be treated as text, not a headline.
852 When `org-odd-levels-only' is set, a value of N in this variable actually
853 means 2N-1 stars as the limiting headline.
854 When nil, cycle all levels.
855 Note that the limiting level of cycling is also influenced by
856 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
857 `org-inlinetask-min-level' is, cycling will be limited to levels one less
858 than its value."
859 :group 'org-cycle
860 :type '(choice
861 (const :tag "No limit" nil)
862 (integer :tag "Maximum level")))
864 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
865 "Names of drawers. Drawers are not opened by cycling on the headline above.
866 Drawers only open with a TAB on the drawer line itself. A drawer looks like
867 this:
868 :DRAWERNAME:
869 .....
870 :END:
871 The drawer \"PROPERTIES\" is special for capturing properties through
872 the property API.
874 Drawers can be defined on the per-file basis with a line like:
876 #+DRAWERS: HIDDEN STATE PROPERTIES"
877 :group 'org-structure
878 :group 'org-cycle
879 :type '(repeat (string :tag "Drawer Name")))
881 (defcustom org-hide-block-startup nil
882 "Non-nil means entering Org-mode will fold all blocks.
883 This can also be set in on a per-file basis with
885 #+STARTUP: hideblocks
886 #+STARTUP: showblocks"
887 :group 'org-startup
888 :group 'org-cycle
889 :type 'boolean)
891 (defcustom org-cycle-global-at-bob nil
892 "Cycle globally if cursor is at beginning of buffer and not at a headline.
893 This makes it possible to do global cycling without having to use S-TAB or
894 \\[universal-argument] TAB. For this special case to work, the first line \
895 of the buffer
896 must not be a headline - it may be empty or some other text. When used in
897 this way, `org-cycle-hook' is disables temporarily, to make sure the
898 cursor stays at the beginning of the buffer.
899 When this option is nil, don't do anything special at the beginning
900 of the buffer."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-level-after-item/entry-creation t
905 "Non-nil means cycle entry level or item indentation in new empty entries.
907 When the cursor is at the end of an empty headline, i.e with only stars
908 and maybe a TODO keyword, TAB will then switch the entry to become a child,
909 and then all possible ancestor states, before returning to the original state.
910 This makes data entry extremely fast: M-RET to create a new headline,
911 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
913 When the cursor is at the end of an empty plain list item, one TAB will
914 make it a subitem, two or more tabs will back up to make this an item
915 higher up in the item hierarchy."
916 :group 'org-cycle
917 :type 'boolean)
919 (defcustom org-cycle-emulate-tab t
920 "Where should `org-cycle' emulate TAB.
921 nil Never
922 white Only in completely white lines
923 whitestart Only at the beginning of lines, before the first non-white char
924 t Everywhere except in headlines
925 exc-hl-bol Everywhere except at the start of a headline
926 If TAB is used in a place where it does not emulate TAB, the current subtree
927 visibility is cycled."
928 :group 'org-cycle
929 :type '(choice (const :tag "Never" nil)
930 (const :tag "Only in completely white lines" white)
931 (const :tag "Before first char in a line" whitestart)
932 (const :tag "Everywhere except in headlines" t)
933 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
936 (defcustom org-cycle-separator-lines 2
937 "Number of empty lines needed to keep an empty line between collapsed trees.
938 If you leave an empty line between the end of a subtree and the following
939 headline, this empty line is hidden when the subtree is folded.
940 Org-mode will leave (exactly) one empty line visible if the number of
941 empty lines is equal or larger to the number given in this variable.
942 So the default 2 means at least 2 empty lines after the end of a subtree
943 are needed to produce free space between a collapsed subtree and the
944 following headline.
946 If the number is negative, and the number of empty lines is at least -N,
947 all empty lines are shown.
949 Special case: when 0, never leave empty lines in collapsed view."
950 :group 'org-cycle
951 :type 'integer)
952 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
954 (defcustom org-pre-cycle-hook nil
955 "Hook that is run before visibility cycling is happening.
956 The function(s) in this hook must accept a single argument which indicates
957 the new state that will be set right after running this hook. The
958 argument is a symbol. Before a global state change, it can have the values
959 `overview', `content', or `all'. Before a local state change, it can have
960 the values `folded', `children', or `subtree'."
961 :group 'org-cycle
962 :type 'hook)
964 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
965 org-cycle-hide-drawers
966 org-cycle-show-empty-lines
967 org-optimize-window-after-visibility-change)
968 "Hook that is run after `org-cycle' has changed the buffer visibility.
969 The function(s) in this hook must accept a single argument which indicates
970 the new state that was set by the most recent `org-cycle' command. The
971 argument is a symbol. After a global state change, it can have the values
972 `overview', `content', or `all'. After a local state change, it can have
973 the values `folded', `children', or `subtree'."
974 :group 'org-cycle
975 :type 'hook)
977 (defgroup org-edit-structure nil
978 "Options concerning structure editing in Org-mode."
979 :tag "Org Edit Structure"
980 :group 'org-structure)
982 (defcustom org-odd-levels-only nil
983 "Non-nil means skip even levels and only use odd levels for the outline.
984 This has the effect that two stars are being added/taken away in
985 promotion/demotion commands. It also influences how levels are
986 handled by the exporters.
987 Changing it requires restart of `font-lock-mode' to become effective
988 for fontification also in regions already fontified.
989 You may also set this on a per-file basis by adding one of the following
990 lines to the buffer:
992 #+STARTUP: odd
993 #+STARTUP: oddeven"
994 :group 'org-edit-structure
995 :group 'org-appearance
996 :type 'boolean)
998 (defcustom org-adapt-indentation t
999 "Non-nil means adapt indentation to outline node level.
1001 When this variable is set, Org assumes that you write outlines by
1002 indenting text in each node to align with the headline (after the stars).
1003 The following issues are influenced by this variable:
1005 - When this is set and the *entire* text in an entry is indented, the
1006 indentation is increased by one space in a demotion command, and
1007 decreased by one in a promotion command. If any line in the entry
1008 body starts with text at column 0, indentation is not changed at all.
1010 - Property drawers and planning information is inserted indented when
1011 this variable s set. When nil, they will not be indented.
1013 - TAB indents a line relative to context. The lines below a headline
1014 will be indented when this variable is set.
1016 Note that this is all about true indentation, by adding and removing
1017 space characters. See also `org-indent.el' which does level-dependent
1018 indentation in a virtual way, i.e. at display time in Emacs."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1022 (defcustom org-special-ctrl-a/e nil
1023 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1025 When t, `C-a' will bring back the cursor to the beginning of the
1026 headline text, i.e. after the stars and after a possible TODO keyword.
1027 In an item, this will be the position after the bullet.
1028 When the cursor is already at that position, another `C-a' will bring
1029 it to the beginning of the line.
1031 `C-e' will jump to the end of the headline, ignoring the presence of tags
1032 in the headline. A second `C-e' will then jump to the true end of the
1033 line, after any tags. This also means that, when this variable is
1034 non-nil, `C-e' also will never jump beyond the end of the heading of a
1035 folded section, i.e. not after the ellipses.
1037 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1038 going to the true line boundary first. Only a directly following, identical
1039 keypress will bring the cursor to the special positions.
1041 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1042 set separately."
1043 :group 'org-edit-structure
1044 :type '(choice
1045 (const :tag "off" nil)
1046 (const :tag "on: after stars/bullet and before tags first" t)
1047 (const :tag "reversed: true line boundary first" reversed)
1048 (cons :tag "Set C-a and C-e separately"
1049 (choice :tag "Special C-a"
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet first" t)
1052 (const :tag "reversed: before stars/bullet first" reversed))
1053 (choice :tag "Special C-e"
1054 (const :tag "off" nil)
1055 (const :tag "on: before tags first" t)
1056 (const :tag "reversed: after tags first" reversed)))))
1057 (if (fboundp 'defvaralias)
1058 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1060 (defcustom org-special-ctrl-k nil
1061 "Non-nil means `C-k' will behave specially in headlines.
1062 When nil, `C-k' will call the default `kill-line' command.
1063 When t, the following will happen while the cursor is in the headline:
1065 - When the cursor is at the beginning of a headline, kill the entire
1066 line and possible the folded subtree below the line.
1067 - When in the middle of the headline text, kill the headline up to the tags.
1068 - When after the headline text, kill the tags."
1069 :group 'org-edit-structure
1070 :type 'boolean)
1072 (defcustom org-ctrl-k-protect-subtree nil
1073 "Non-nil means, do not delete a hidden subtree with C-k.
1074 When set to the symbol `error', simply throw an error when C-k is
1075 used to kill (part-of) a headline that has hidden text behind it.
1076 Any other non-nil value will result in a query to the user, if it is
1077 OK to kill that hidden subtree. When nil, kill without remorse."
1078 :group 'org-edit-structure
1079 :version "24.1"
1080 :type '(choice
1081 (const :tag "Do not protect hidden subtrees" nil)
1082 (const :tag "Protect hidden subtrees with a security query" t)
1083 (const :tag "Never kill a hidden subtree with C-k" error)))
1085 (defcustom org-catch-invisible-edits nil
1086 "Check if in invisible region before inserting or deleting a character.
1087 Valid values are:
1089 nil Do not check, so just do invisible edits.
1090 error Throw an error and do nothing.
1091 show Make point visible, and do the requested edit.
1092 show-and-error Make point visible, then throw an error and abort the edit.
1093 smart Make point visible, and do insertion/deletion if it is
1094 adjacent to visible text and the change feels predictable.
1095 Never delete a previously invisible character or add in the
1096 middle or right after an invisible region. Basically, this
1097 allows insertion and backward-delete right before ellipses.
1098 FIXME: maybe in this case we should not even show?"
1099 :group 'org-edit-structure
1100 :version "24.1"
1101 :type '(choice
1102 (const :tag "Do not check" nil)
1103 (const :tag "Throw error when trying to edit" error)
1104 (const :tag "Unhide, but do not do the edit" show-and-error)
1105 (const :tag "Show invisible part and do the edit" show)
1106 (const :tag "Be smart and do the right thing" smart)))
1108 (defcustom org-yank-folded-subtrees t
1109 "Non-nil means when yanking subtrees, fold them.
1110 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1111 it starts with a heading and all other headings in it are either children
1112 or siblings, then fold all the subtrees. However, do this only if no
1113 text after the yank would be swallowed into a folded tree by this action."
1114 :group 'org-edit-structure
1115 :type 'boolean)
1117 (defcustom org-yank-adjusted-subtrees nil
1118 "Non-nil means when yanking subtrees, adjust the level.
1119 With this setting, `org-paste-subtree' is used to insert the subtree, see
1120 this function for details."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-M-RET-may-split-line '((default . t))
1125 "Non-nil means M-RET will split the line at the cursor position.
1126 When nil, it will go to the end of the line before making a
1127 new line.
1128 You may also set this option in a different way for different
1129 contexts. Valid contexts are:
1131 headline when creating a new headline
1132 item when creating a new item
1133 table in a table field
1134 default the value to be used for all contexts not explicitly
1135 customized"
1136 :group 'org-structure
1137 :group 'org-table
1138 :type '(choice
1139 (const :tag "Always" t)
1140 (const :tag "Never" nil)
1141 (repeat :greedy t :tag "Individual contexts"
1142 (cons
1143 (choice :tag "Context"
1144 (const headline)
1145 (const item)
1146 (const table)
1147 (const default))
1148 (boolean)))))
1151 (defcustom org-insert-heading-respect-content nil
1152 "Non-nil means insert new headings after the current subtree.
1153 When nil, the new heading is created directly after the current line.
1154 The commands \\[org-insert-heading-respect-content] and
1155 \\[org-insert-todo-heading-respect-content] turn this variable on
1156 for the duration of the command."
1157 :group 'org-structure
1158 :type 'boolean)
1160 (defcustom org-blank-before-new-entry '((heading . auto)
1161 (plain-list-item . auto))
1162 "Should `org-insert-heading' leave a blank line before new heading/item?
1163 The value is an alist, with `heading' and `plain-list-item' as CAR,
1164 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1165 which case Org will look at the surrounding headings/items and try to
1166 make an intelligent decision whether to insert a blank line or not.
1168 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1169 set, the setting here is ignored and no empty line is inserted, to avoid
1170 breaking the list structure."
1171 :group 'org-edit-structure
1172 :type '(list
1173 (cons (const heading)
1174 (choice (const :tag "Never" nil)
1175 (const :tag "Always" t)
1176 (const :tag "Auto" auto)))
1177 (cons (const plain-list-item)
1178 (choice (const :tag "Never" nil)
1179 (const :tag "Always" t)
1180 (const :tag "Auto" auto)))))
1182 (defcustom org-insert-heading-hook nil
1183 "Hook being run after inserting a new heading."
1184 :group 'org-edit-structure
1185 :type 'hook)
1187 (defcustom org-enable-fixed-width-editor t
1188 "Non-nil means lines starting with \":\" are treated as fixed-width.
1189 This currently only means they are never auto-wrapped.
1190 When nil, such lines will be treated like ordinary lines.
1191 See also the QUOTE keyword."
1192 :group 'org-edit-structure
1193 :type 'boolean)
1195 (defcustom org-goto-auto-isearch t
1196 "Non-nil means typing characters in `org-goto' starts incremental search."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defgroup org-sparse-trees nil
1201 "Options concerning sparse trees in Org-mode."
1202 :tag "Org Sparse Trees"
1203 :group 'org-structure)
1205 (defcustom org-highlight-sparse-tree-matches t
1206 "Non-nil means highlight all matches that define a sparse tree.
1207 The highlights will automatically disappear the next time the buffer is
1208 changed by an edit command."
1209 :group 'org-sparse-trees
1210 :type 'boolean)
1212 (defcustom org-remove-highlights-with-change t
1213 "Non-nil means any change to the buffer will remove temporary highlights.
1214 Such highlights are created by `org-occur' and `org-clock-display'.
1215 When nil, `C-c C-c needs to be used to get rid of the highlights.
1216 The highlights created by `org-preview-latex-fragment' always need
1217 `C-c C-c' to be removed."
1218 :group 'org-sparse-trees
1219 :group 'org-time
1220 :type 'boolean)
1223 (defcustom org-occur-hook '(org-first-headline-recenter)
1224 "Hook that is run after `org-occur' has constructed a sparse tree.
1225 This can be used to recenter the window to show as much of the structure
1226 as possible."
1227 :group 'org-sparse-trees
1228 :type 'hook)
1230 (defgroup org-imenu-and-speedbar nil
1231 "Options concerning imenu and speedbar in Org-mode."
1232 :tag "Org Imenu and Speedbar"
1233 :group 'org-structure)
1235 (defcustom org-imenu-depth 2
1236 "The maximum level for Imenu access to Org-mode headlines.
1237 This also applied for speedbar access."
1238 :group 'org-imenu-and-speedbar
1239 :type 'integer)
1241 (defgroup org-table nil
1242 "Options concerning tables in Org-mode."
1243 :tag "Org Table"
1244 :group 'org)
1246 (defcustom org-enable-table-editor 'optimized
1247 "Non-nil means lines starting with \"|\" are handled by the table editor.
1248 When nil, such lines will be treated like ordinary lines.
1250 When equal to the symbol `optimized', the table editor will be optimized to
1251 do the following:
1252 - Automatic overwrite mode in front of whitespace in table fields.
1253 This makes the structure of the table stay in tact as long as the edited
1254 field does not exceed the column width.
1255 - Minimize the number of realigns. Normally, the table is aligned each time
1256 TAB or RET are pressed to move to another field. With optimization this
1257 happens only if changes to a field might have changed the column width.
1258 Optimization requires replacing the functions `self-insert-command',
1259 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1260 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1261 very good at guessing when a re-align will be necessary, but you can always
1262 force one with \\[org-ctrl-c-ctrl-c].
1264 If you would like to use the optimized version in Org-mode, but the
1265 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1267 This variable can be used to turn on and off the table editor during a session,
1268 but in order to toggle optimization, a restart is required.
1270 See also the variable `org-table-auto-blank-field'."
1271 :group 'org-table
1272 :type '(choice
1273 (const :tag "off" nil)
1274 (const :tag "on" t)
1275 (const :tag "on, optimized" optimized)))
1277 (defcustom org-self-insert-cluster-for-undo t
1278 "Non-nil means cluster self-insert commands for undo when possible.
1279 If this is set, then, like in the Emacs command loop, 20 consecutive
1280 characters will be undone together.
1281 This is configurable, because there is some impact on typing performance."
1282 :group 'org-table
1283 :type 'boolean)
1285 (defcustom org-table-tab-recognizes-table.el t
1286 "Non-nil means TAB will automatically notice a table.el table.
1287 When it sees such a table, it moves point into it and - if necessary -
1288 calls `table-recognize-table'."
1289 :group 'org-table-editing
1290 :type 'boolean)
1292 (defgroup org-link nil
1293 "Options concerning links in Org-mode."
1294 :tag "Org Link"
1295 :group 'org)
1297 (defvar org-link-abbrev-alist-local nil
1298 "Buffer-local version of `org-link-abbrev-alist', which see.
1299 The value of this is taken from the #+LINK lines.")
1300 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1302 (defcustom org-link-abbrev-alist nil
1303 "Alist of link abbreviations.
1304 The car of each element is a string, to be replaced at the start of a link.
1305 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1306 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1308 [[linkkey:tag][description]]
1310 The 'linkkey' must be a word word, starting with a letter, followed
1311 by letters, numbers, '-' or '_'.
1313 If REPLACE is a string, the tag will simply be appended to create the link.
1314 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1315 the placeholder \"%h\" will cause a url-encoded version of the tag to
1316 be inserted at that point (see the function `url-hexify-string').
1318 REPLACE may also be a function that will be called with the tag as the
1319 only argument to create the link, which should be returned as a string.
1321 See the manual for examples."
1322 :group 'org-link
1323 :type '(repeat
1324 (cons
1325 (string :tag "Protocol")
1326 (choice
1327 (string :tag "Format")
1328 (function)))))
1330 (defcustom org-descriptive-links t
1331 "Non-nil means Org will display descriptive links.
1332 E.g. [[http://orgmode.org][Org website]] will be displayed as
1333 \"Org Website\", hiding the link itself and just displaying its
1334 description. When set to `nil', Org will display the full links
1335 literally.
1337 You can interactively set the value of this variable by calling
1338 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1339 :group 'org-link
1340 :type 'boolean)
1342 (defcustom org-link-file-path-type 'adaptive
1343 "How the path name in file links should be stored.
1344 Valid values are:
1346 relative Relative to the current directory, i.e. the directory of the file
1347 into which the link is being inserted.
1348 absolute Absolute path, if possible with ~ for home directory.
1349 noabbrev Absolute path, no abbreviation of home directory.
1350 adaptive Use relative path for files in the current directory and sub-
1351 directories of it. For other files, use an absolute path."
1352 :group 'org-link
1353 :type '(choice
1354 (const relative)
1355 (const absolute)
1356 (const noabbrev)
1357 (const adaptive)))
1359 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1360 "Types of links that should be activated in Org-mode files.
1361 This is a list of symbols, each leading to the activation of a certain link
1362 type. In principle, it does not hurt to turn on most link types - there may
1363 be a small gain when turning off unused link types. The types are:
1365 bracket The recommended [[link][description]] or [[link]] links with hiding.
1366 angle Links in angular brackets that may contain whitespace like
1367 <bbdb:Carsten Dominik>.
1368 plain Plain links in normal text, no whitespace, like http://google.com.
1369 radio Text that is matched by a radio target, see manual for details.
1370 tag Tag settings in a headline (link to tag search).
1371 date Time stamps (link to calendar).
1372 footnote Footnote labels.
1374 Changing this variable requires a restart of Emacs to become effective."
1375 :group 'org-link
1376 :type '(set :greedy t
1377 (const :tag "Double bracket links" bracket)
1378 (const :tag "Angular bracket links" angle)
1379 (const :tag "Plain text links" plain)
1380 (const :tag "Radio target matches" radio)
1381 (const :tag "Tags" tag)
1382 (const :tag "Timestamps" date)
1383 (const :tag "Footnotes" footnote)))
1385 (defcustom org-make-link-description-function nil
1386 "Function to use to generate link descriptions from links.
1387 If nil the link location will be used. This function must take
1388 two parameters; the first is the link and the second the
1389 description `org-insert-link' has generated, and should return the
1390 description to use."
1391 :group 'org-link
1392 :type 'function)
1394 (defgroup org-link-store nil
1395 "Options concerning storing links in Org-mode."
1396 :tag "Org Store Link"
1397 :group 'org-link)
1399 (defcustom org-email-link-description-format "Email %c: %.30s"
1400 "Format of the description part of a link to an email or usenet message.
1401 The following %-escapes will be replaced by corresponding information:
1403 %F full \"From\" field
1404 %f name, taken from \"From\" field, address if no name
1405 %T full \"To\" field
1406 %t first name in \"To\" field, address if no name
1407 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1408 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1409 %s subject
1410 %d date
1411 %m message-id.
1413 You may use normal field width specification between the % and the letter.
1414 This is for example useful to limit the length of the subject.
1416 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1417 :group 'org-link-store
1418 :type 'string)
1420 (defcustom org-from-is-user-regexp
1421 (let (r1 r2)
1422 (when (and user-mail-address (not (string= user-mail-address "")))
1423 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1424 (when (and user-full-name (not (string= user-full-name "")))
1425 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1426 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1427 "Regexp matched against the \"From:\" header of an email or usenet message.
1428 It should match if the message is from the user him/herself."
1429 :group 'org-link-store
1430 :type 'regexp)
1432 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1433 "Non-nil means storing a link to an Org file will use entry IDs.
1435 Note that before this variable is even considered, org-id must be loaded,
1436 so please customize `org-modules' and turn it on.
1438 The variable can have the following values:
1440 t Create an ID if needed to make a link to the current entry.
1442 create-if-interactive
1443 If `org-store-link' is called directly (interactively, as a user
1444 command), do create an ID to support the link. But when doing the
1445 job for remember, only use the ID if it already exists. The
1446 purpose of this setting is to avoid proliferation of unwanted
1447 IDs, just because you happen to be in an Org file when you
1448 call `org-remember' that automatically and preemptively
1449 creates a link. If you do want to get an ID link in a remember
1450 template to an entry not having an ID, create it first by
1451 explicitly creating a link to it, using `C-c C-l' first.
1453 create-if-interactive-and-no-custom-id
1454 Like create-if-interactive, but do not create an ID if there is
1455 a CUSTOM_ID property defined in the entry. This is the default.
1457 use-existing
1458 Use existing ID, do not create one.
1460 nil Never use an ID to make a link, instead link using a text search for
1461 the headline text."
1462 :group 'org-link-store
1463 :type '(choice
1464 (const :tag "Create ID to make link" t)
1465 (const :tag "Create if storing link interactively"
1466 create-if-interactive)
1467 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1468 create-if-interactive-and-no-custom-id)
1469 (const :tag "Only use existing" use-existing)
1470 (const :tag "Do not use ID to create link" nil)))
1472 (defcustom org-context-in-file-links t
1473 "Non-nil means file links from `org-store-link' contain context.
1474 A search string will be added to the file name with :: as separator and
1475 used to find the context when the link is activated by the command
1476 `org-open-at-point'. When this option is t, the entire active region
1477 will be placed in the search string of the file link. If set to a
1478 positive integer, only the first n lines of context will be stored.
1480 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1481 negates this setting for the duration of the command."
1482 :group 'org-link-store
1483 :type '(choice boolean integer))
1485 (defcustom org-keep-stored-link-after-insertion nil
1486 "Non-nil means keep link in list for entire session.
1488 The command `org-store-link' adds a link pointing to the current
1489 location to an internal list. These links accumulate during a session.
1490 The command `org-insert-link' can be used to insert links into any
1491 Org-mode file (offering completion for all stored links). When this
1492 option is nil, every link which has been inserted once using \\[org-insert-link]
1493 will be removed from the list, to make completing the unused links
1494 more efficient."
1495 :group 'org-link-store
1496 :type 'boolean)
1498 (defgroup org-link-follow nil
1499 "Options concerning following links in Org-mode."
1500 :tag "Org Follow Link"
1501 :group 'org-link)
1503 (defcustom org-link-translation-function nil
1504 "Function to translate links with different syntax to Org syntax.
1505 This can be used to translate links created for example by the Planner
1506 or emacs-wiki packages to Org syntax.
1507 The function must accept two parameters, a TYPE containing the link
1508 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1509 which is everything after the link protocol. It should return a cons
1510 with possibly modified values of type and path.
1511 Org contains a function for this, so if you set this variable to
1512 `org-translate-link-from-planner', you should be able follow many
1513 links created by planner."
1514 :group 'org-link-follow
1515 :type 'function)
1517 (defcustom org-follow-link-hook nil
1518 "Hook that is run after a link has been followed."
1519 :group 'org-link-follow
1520 :type 'hook)
1522 (defcustom org-tab-follows-link nil
1523 "Non-nil means on links TAB will follow the link.
1524 Needs to be set before org.el is loaded.
1525 This really should not be used, it does not make sense, and the
1526 implementation is bad."
1527 :group 'org-link-follow
1528 :type 'boolean)
1530 (defcustom org-return-follows-link nil
1531 "Non-nil means on links RET will follow the link."
1532 :group 'org-link-follow
1533 :type 'boolean)
1535 (defcustom org-mouse-1-follows-link
1536 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1537 "Non-nil means mouse-1 on a link will follow the link.
1538 A longer mouse click will still set point. Does not work on XEmacs.
1539 Needs to be set before org.el is loaded."
1540 :group 'org-link-follow
1541 :type 'boolean)
1543 (defcustom org-mark-ring-length 4
1544 "Number of different positions to be recorded in the ring.
1545 Changing this requires a restart of Emacs to work correctly."
1546 :group 'org-link-follow
1547 :type 'integer)
1549 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1550 "Non-nil means internal links in Org files must exactly match a headline.
1551 When nil, the link search tries to match a phrase with all words
1552 in the search text."
1553 :group 'org-link-follow
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Use fuzzy text search" nil)
1557 (const :tag "Match only exact headline" t)
1558 (const :tag "Match exact headline or query to create it"
1559 query-to-create)))
1561 (defcustom org-link-frame-setup
1562 '((vm . vm-visit-folder-other-frame)
1563 (gnus . org-gnus-no-new-news)
1564 (file . find-file-other-window)
1565 (wl . wl-other-frame))
1566 "Setup the frame configuration for following links.
1567 When following a link with Emacs, it may often be useful to display
1568 this link in another window or frame. This variable can be used to
1569 set this up for the different types of links.
1570 For VM, use any of
1571 `vm-visit-folder'
1572 `vm-visit-folder-other-window'
1573 `vm-visit-folder-other-frame'
1574 For Gnus, use any of
1575 `gnus'
1576 `gnus-other-frame'
1577 `org-gnus-no-new-news'
1578 For FILE, use any of
1579 `find-file'
1580 `find-file-other-window'
1581 `find-file-other-frame'
1582 For Wanderlust use any of
1583 `wl'
1584 `wl-other-frame'
1585 For the calendar, use the variable `calendar-setup'.
1586 For BBDB, it is currently only possible to display the matches in
1587 another window."
1588 :group 'org-link-follow
1589 :type '(list
1590 (cons (const vm)
1591 (choice
1592 (const vm-visit-folder)
1593 (const vm-visit-folder-other-window)
1594 (const vm-visit-folder-other-frame)))
1595 (cons (const gnus)
1596 (choice
1597 (const gnus)
1598 (const gnus-other-frame)
1599 (const org-gnus-no-new-news)))
1600 (cons (const file)
1601 (choice
1602 (const find-file)
1603 (const find-file-other-window)
1604 (const find-file-other-frame)))
1605 (cons (const wl)
1606 (choice
1607 (const wl)
1608 (const wl-other-frame)))))
1610 (defcustom org-display-internal-link-with-indirect-buffer nil
1611 "Non-nil means use indirect buffer to display infile links.
1612 Activating internal links (from one location in a file to another location
1613 in the same file) normally just jumps to the location. When the link is
1614 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1615 is displayed in
1616 another window. When this option is set, the other window actually displays
1617 an indirect buffer clone of the current buffer, to avoid any visibility
1618 changes to the current buffer."
1619 :group 'org-link-follow
1620 :type 'boolean)
1622 (defcustom org-open-non-existing-files nil
1623 "Non-nil means `org-open-file' will open non-existing files.
1624 When nil, an error will be generated.
1625 This variable applies only to external applications because they
1626 might choke on non-existing files. If the link is to a file that
1627 will be opened in Emacs, the variable is ignored."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-open-directory-means-index-dot-org nil
1632 "Non-nil means a link to a directory really means to index.org.
1633 When nil, following a directory link will run dired or open a finder/explorer
1634 window on that directory."
1635 :group 'org-link-follow
1636 :type 'boolean)
1638 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1639 "Function and arguments to call for following mailto links.
1640 This is a list with the first element being a Lisp function, and the
1641 remaining elements being arguments to the function. In string arguments,
1642 %a will be replaced by the address, and %s will be replaced by the subject
1643 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1644 :group 'org-link-follow
1645 :type '(choice
1646 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1647 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1648 (const :tag "message-mail" (message-mail "%a" "%s"))
1649 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1651 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1652 "Non-nil means ask for confirmation before executing shell links.
1653 Shell links can be dangerous: just think about a link
1655 [[shell:rm -rf ~/*][Google Search]]
1657 This link would show up in your Org-mode document as \"Google Search\",
1658 but really it would remove your entire home directory.
1659 Therefore we advise against setting this variable to nil.
1660 Just change it to `y-or-n-p' if you want to confirm with a
1661 single keystroke rather than having to type \"yes\"."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1665 (const :tag "with y-or-n (faster)" y-or-n-p)
1666 (const :tag "no confirmation (dangerous)" nil)))
1667 (put 'org-confirm-shell-link-function
1668 'safe-local-variable
1669 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1671 (defcustom org-confirm-shell-link-not-regexp ""
1672 "A regexp to skip confirmation for shell links."
1673 :group 'org-link-follow
1674 :version "24.1"
1675 :type 'regexp)
1677 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1678 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1679 Elisp links can be dangerous: just think about a link
1681 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1683 This link would show up in your Org-mode document as \"Google Search\",
1684 but really it would remove your entire home directory.
1685 Therefore we advise against setting this variable to nil.
1686 Just change it to `y-or-n-p' if you want to confirm with a
1687 single keystroke rather than having to type \"yes\"."
1688 :group 'org-link-follow
1689 :type '(choice
1690 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1691 (const :tag "with y-or-n (faster)" y-or-n-p)
1692 (const :tag "no confirmation (dangerous)" nil)))
1693 (put 'org-confirm-shell-link-function
1694 'safe-local-variable
1695 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1697 (defcustom org-confirm-elisp-link-not-regexp ""
1698 "A regexp to skip confirmation for Elisp links."
1699 :group 'org-link-follow
1700 :version "24.1"
1701 :type 'regexp)
1703 (defconst org-file-apps-defaults-gnu
1704 '((remote . emacs)
1705 (system . mailcap)
1706 (t . mailcap))
1707 "Default file applications on a UNIX or GNU/Linux system.
1708 See `org-file-apps'.")
1710 (defconst org-file-apps-defaults-macosx
1711 '((remote . emacs)
1712 (t . "open %s")
1713 (system . "open %s")
1714 ("ps.gz" . "gv %s")
1715 ("eps.gz" . "gv %s")
1716 ("dvi" . "xdvi %s")
1717 ("fig" . "xfig %s"))
1718 "Default file applications on a MacOS X system.
1719 The system \"open\" is known as a default, but we use X11 applications
1720 for some files for which the OS does not have a good default.
1721 See `org-file-apps'.")
1723 (defconst org-file-apps-defaults-windowsnt
1724 (list
1725 '(remote . emacs)
1726 (cons t
1727 (list (if (featurep 'xemacs)
1728 'mswindows-shell-execute
1729 'w32-shell-execute)
1730 "open" 'file))
1731 (cons 'system
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file)))
1736 "Default file applications on a Windows NT system.
1737 The system \"open\" is used for most files.
1738 See `org-file-apps'.")
1740 (defcustom org-file-apps
1742 (auto-mode . emacs)
1743 ("\\.mm\\'" . default)
1744 ("\\.x?html?\\'" . default)
1745 ("\\.pdf\\'" . default)
1747 "External applications for opening `file:path' items in a document.
1748 Org-mode uses system defaults for different file types, but
1749 you can use this variable to set the application for a given file
1750 extension. The entries in this list are cons cells where the car identifies
1751 files and the cdr the corresponding command. Possible values for the
1752 file identifier are
1753 \"string\" A string as a file identifier can be interpreted in different
1754 ways, depending on its contents:
1756 - Alphanumeric characters only:
1757 Match links with this file extension.
1758 Example: (\"pdf\" . \"evince %s\")
1759 to open PDFs with evince.
1761 - Regular expression: Match links where the
1762 filename matches the regexp. If you want to
1763 use groups here, use shy groups.
1765 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1766 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1767 to open *.html and *.xhtml with firefox.
1769 - Regular expression which contains (non-shy) groups:
1770 Match links where the whole link, including \"::\", and
1771 anything after that, matches the regexp.
1772 In a custom command string, %1, %2, etc. are replaced with
1773 the parts of the link that were matched by the groups.
1774 For backwards compatibility, if a command string is given
1775 that does not use any of the group matches, this case is
1776 handled identically to the second one (i.e. match against
1777 file name only).
1778 In a custom lisp form, you can access the group matches with
1779 (match-string n link).
1781 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1782 to open [[file:document.pdf::5]] with evince at page 5.
1784 `directory' Matches a directory
1785 `remote' Matches a remote file, accessible through tramp or efs.
1786 Remote files most likely should be visited through Emacs
1787 because external applications cannot handle such paths.
1788 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1789 so all files Emacs knows how to handle. Using this with
1790 command `emacs' will open most files in Emacs. Beware that this
1791 will also open html files inside Emacs, unless you add
1792 (\"html\" . default) to the list as well.
1793 t Default for files not matched by any of the other options.
1794 `system' The system command to open files, like `open' on Windows
1795 and Mac OS X, and mailcap under GNU/Linux. This is the command
1796 that will be selected if you call `C-c C-o' with a double
1797 \\[universal-argument] \\[universal-argument] prefix.
1799 Possible values for the command are:
1800 `emacs' The file will be visited by the current Emacs process.
1801 `default' Use the default application for this file type, which is the
1802 association for t in the list, most likely in the system-specific
1803 part.
1804 This can be used to overrule an unwanted setting in the
1805 system-specific variable.
1806 `system' Use the system command for opening files, like \"open\".
1807 This command is specified by the entry whose car is `system'.
1808 Most likely, the system-specific version of this variable
1809 does define this command, but you can overrule/replace it
1810 here.
1811 string A command to be executed by a shell; %s will be replaced
1812 by the path to the file.
1813 sexp A Lisp form which will be evaluated. The file path will
1814 be available in the Lisp variable `file'.
1815 For more examples, see the system specific constants
1816 `org-file-apps-defaults-macosx'
1817 `org-file-apps-defaults-windowsnt'
1818 `org-file-apps-defaults-gnu'."
1819 :group 'org-link-follow
1820 :type '(repeat
1821 (cons (choice :value ""
1822 (string :tag "Extension")
1823 (const :tag "System command to open files" system)
1824 (const :tag "Default for unrecognized files" t)
1825 (const :tag "Remote file" remote)
1826 (const :tag "Links to a directory" directory)
1827 (const :tag "Any files that have Emacs modes"
1828 auto-mode))
1829 (choice :value ""
1830 (const :tag "Visit with Emacs" emacs)
1831 (const :tag "Use default" default)
1832 (const :tag "Use the system command" system)
1833 (string :tag "Command")
1834 (sexp :tag "Lisp form")))))
1838 (defgroup org-refile nil
1839 "Options concerning refiling entries in Org-mode."
1840 :tag "Org Refile"
1841 :group 'org)
1843 (defcustom org-directory "~/org"
1844 "Directory with org files.
1845 This is just a default location to look for Org files. There is no need
1846 at all to put your files into this directory. It is only used in the
1847 following situations:
1849 1. When a remember template specifies a target file that is not an
1850 absolute path. The path will then be interpreted relative to
1851 `org-directory'
1852 2. When a remember note is filed away in an interactive way (when exiting the
1853 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1854 with `org-directory' as the default path."
1855 :group 'org-refile
1856 :group 'org-remember
1857 :type 'directory)
1859 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1860 "Default target for storing notes.
1861 Used as a fall back file for org-remember.el and org-capture.el, for
1862 templates that do not specify a target file."
1863 :group 'org-refile
1864 :group 'org-remember
1865 :type '(choice
1866 (const :tag "Default from remember-data-file" nil)
1867 file))
1869 (defcustom org-goto-interface 'outline
1870 "The default interface to be used for `org-goto'.
1871 Allowed values are:
1872 outline The interface shows an outline of the relevant file
1873 and the correct heading is found by moving through
1874 the outline or by searching with incremental search.
1875 outline-path-completion Headlines in the current buffer are offered via
1876 completion. This is the interface also used by
1877 the refile command."
1878 :group 'org-refile
1879 :type '(choice
1880 (const :tag "Outline" outline)
1881 (const :tag "Outline-path-completion" outline-path-completion)))
1883 (defcustom org-goto-max-level 5
1884 "Maximum target level when running `org-goto' with refile interface."
1885 :group 'org-refile
1886 :type 'integer)
1888 (defcustom org-reverse-note-order nil
1889 "Non-nil means store new notes at the beginning of a file or entry.
1890 When nil, new notes will be filed to the end of a file or entry.
1891 This can also be a list with cons cells of regular expressions that
1892 are matched against file names, and values."
1893 :group 'org-remember
1894 :group 'org-refile
1895 :type '(choice
1896 (const :tag "Reverse always" t)
1897 (const :tag "Reverse never" nil)
1898 (repeat :tag "By file name regexp"
1899 (cons regexp boolean))))
1901 (defcustom org-log-refile nil
1902 "Information to record when a task is refiled.
1904 Possible values are:
1906 nil Don't add anything
1907 time Add a time stamp to the task
1908 note Prompt for a note and add it with template `org-log-note-headings'
1910 This option can also be set with on a per-file-basis with
1912 #+STARTUP: nologrefile
1913 #+STARTUP: logrefile
1914 #+STARTUP: lognoterefile
1916 You can have local logging settings for a subtree by setting the LOGGING
1917 property to one or more of these keywords.
1919 When bulk-refiling from the agenda, the value `note' is forbidden and
1920 will temporarily be changed to `time'."
1921 :group 'org-refile
1922 :group 'org-progress
1923 :version "24.1"
1924 :type '(choice
1925 (const :tag "No logging" nil)
1926 (const :tag "Record timestamp" time)
1927 (const :tag "Record timestamp with note." note)))
1929 (defcustom org-refile-targets nil
1930 "Targets for refiling entries with \\[org-refile].
1931 This is a list of cons cells. Each cell contains:
1932 - a specification of the files to be considered, either a list of files,
1933 or a symbol whose function or variable value will be used to retrieve
1934 a file name or a list of file names. If you use `org-agenda-files' for
1935 that, all agenda files will be scanned for targets. Nil means consider
1936 headings in the current buffer.
1937 - A specification of how to find candidate refile targets. This may be
1938 any of:
1939 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1940 This tag has to be present in all target headlines, inheritance will
1941 not be considered.
1942 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1943 todo keyword.
1944 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1945 headlines that are refiling targets.
1946 - a cons cell (:level . N). Any headline of level N is considered a target.
1947 Note that, when `org-odd-levels-only' is set, level corresponds to
1948 order in hierarchy, not to the number of stars.
1949 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1950 Note that, when `org-odd-levels-only' is set, level corresponds to
1951 order in hierarchy, not to the number of stars.
1953 Each element of this list generates a set of possible targets.
1954 The union of these sets is presented (with completion) to
1955 the user by `org-refile'.
1957 You can set the variable `org-refile-target-verify-function' to a function
1958 to verify each headline found by the simple criteria above.
1960 When this variable is nil, all top-level headlines in the current buffer
1961 are used, equivalent to the value `((nil . (:level . 1))'."
1962 :group 'org-refile
1963 :type '(repeat
1964 (cons
1965 (choice :value org-agenda-files
1966 (const :tag "All agenda files" org-agenda-files)
1967 (const :tag "Current buffer" nil)
1968 (function) (variable) (file))
1969 (choice :tag "Identify target headline by"
1970 (cons :tag "Specific tag" (const :value :tag) (string))
1971 (cons :tag "TODO keyword" (const :value :todo) (string))
1972 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1973 (cons :tag "Level number" (const :value :level) (integer))
1974 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1976 (defcustom org-refile-target-verify-function nil
1977 "Function to verify if the headline at point should be a refile target.
1978 The function will be called without arguments, with point at the
1979 beginning of the headline. It should return t and leave point
1980 where it is if the headline is a valid target for refiling.
1982 If the target should not be selected, the function must return nil.
1983 In addition to this, it may move point to a place from where the search
1984 should be continued. For example, the function may decide that the entire
1985 subtree of the current entry should be excluded and move point to the end
1986 of the subtree."
1987 :group 'org-refile
1988 :type 'function)
1990 (defcustom org-refile-use-cache nil
1991 "Non-nil means cache refile targets to speed up the process.
1992 The cache for a particular file will be updated automatically when
1993 the buffer has been killed, or when any of the marker used for flagging
1994 refile targets no longer points at a live buffer.
1995 If you have added new entries to a buffer that might themselves be targets,
1996 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1997 find that easier, `C-u C-u C-u C-c C-w'."
1998 :group 'org-refile
1999 :version "24.1"
2000 :type 'boolean)
2002 (defcustom org-refile-use-outline-path nil
2003 "Non-nil means provide refile targets as paths.
2004 So a level 3 headline will be available as level1/level2/level3.
2006 When the value is `file', also include the file name (without directory)
2007 into the path. In this case, you can also stop the completion after
2008 the file name, to get entries inserted as top level in the file.
2010 When `full-file-path', include the full file path."
2011 :group 'org-refile
2012 :type '(choice
2013 (const :tag "Not" nil)
2014 (const :tag "Yes" t)
2015 (const :tag "Start with file name" file)
2016 (const :tag "Start with full file path" full-file-path)))
2018 (defcustom org-outline-path-complete-in-steps t
2019 "Non-nil means complete the outline path in hierarchical steps.
2020 When Org-mode uses the refile interface to select an outline path
2021 \(see variable `org-refile-use-outline-path'), the completion of
2022 the path can be done is a single go, or if can be done in steps down
2023 the headline hierarchy. Going in steps is probably the best if you
2024 do not use a special completion package like `ido' or `icicles'.
2025 However, when using these packages, going in one step can be very
2026 fast, while still showing the whole path to the entry."
2027 :group 'org-refile
2028 :type 'boolean)
2030 (defcustom org-refile-allow-creating-parent-nodes nil
2031 "Non-nil means allow to create new nodes as refile targets.
2032 New nodes are then created by adding \"/new node name\" to the completion
2033 of an existing node. When the value of this variable is `confirm',
2034 new node creation must be confirmed by the user (recommended)
2035 When nil, the completion must match an existing entry.
2037 Note that, if the new heading is not seen by the criteria
2038 listed in `org-refile-targets', multiple instances of the same
2039 heading would be created by trying again to file under the new
2040 heading."
2041 :group 'org-refile
2042 :type '(choice
2043 (const :tag "Never" nil)
2044 (const :tag "Always" t)
2045 (const :tag "Prompt for confirmation" confirm)))
2047 (defcustom org-refile-active-region-within-subtree nil
2048 "Non-nil means also refile active region within a subtree.
2050 By default `org-refile' doesn't allow refiling regions if they
2051 don't contain a set of subtrees, but it might be convenient to
2052 do so sometimes: in that case, the first line of the region is
2053 converted to a headline before refiling."
2054 :group 'org-refile
2055 :version "24.1"
2056 :type 'boolean)
2058 (defgroup org-todo nil
2059 "Options concerning TODO items in Org-mode."
2060 :tag "Org TODO"
2061 :group 'org)
2063 (defgroup org-progress nil
2064 "Options concerning Progress logging in Org-mode."
2065 :tag "Org Progress"
2066 :group 'org-time)
2068 (defvar org-todo-interpretation-widgets
2069 '((:tag "Sequence (cycling hits every state)" sequence)
2070 (:tag "Type (cycling directly to DONE)" type))
2071 "The available interpretation symbols for customizing `org-todo-keywords'.
2072 Interested libraries should add to this list.")
2074 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2075 "List of TODO entry keyword sequences and their interpretation.
2076 \\<org-mode-map>This is a list of sequences.
2078 Each sequence starts with a symbol, either `sequence' or `type',
2079 indicating if the keywords should be interpreted as a sequence of
2080 action steps, or as different types of TODO items. The first
2081 keywords are states requiring action - these states will select a headline
2082 for inclusion into the global TODO list Org-mode produces. If one of
2083 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2084 signify that no further action is necessary. If \"|\" is not found,
2085 the last keyword is treated as the only DONE state of the sequence.
2087 The command \\[org-todo] cycles an entry through these states, and one
2088 additional state where no keyword is present. For details about this
2089 cycling, see the manual.
2091 TODO keywords and interpretation can also be set on a per-file basis with
2092 the special #+SEQ_TODO and #+TYP_TODO lines.
2094 Each keyword can optionally specify a character for fast state selection
2095 \(in combination with the variable `org-use-fast-todo-selection')
2096 and specifiers for state change logging, using the same syntax
2097 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2098 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2099 indicates to record a time stamp each time this state is selected.
2101 Each keyword may also specify if a timestamp or a note should be
2102 recorded when entering or leaving the state, by adding additional
2103 characters in the parenthesis after the keyword. This looks like this:
2104 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2105 record only the time of the state change. With X and Y being either
2106 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2107 Y when leaving the state if and only if the *target* state does not
2108 define X. You may omit any of the fast-selection key or X or /Y,
2109 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2111 For backward compatibility, this variable may also be just a list
2112 of keywords - in this case the interpretation (sequence or type) will be
2113 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2114 :group 'org-todo
2115 :group 'org-keywords
2116 :type '(choice
2117 (repeat :tag "Old syntax, just keywords"
2118 (string :tag "Keyword"))
2119 (repeat :tag "New syntax"
2120 (cons
2121 (choice
2122 :tag "Interpretation"
2123 ;;Quick and dirty way to see
2124 ;;`org-todo-interpretations'. This takes the
2125 ;;place of item arguments
2126 :convert-widget
2127 (lambda (widget)
2128 (widget-put widget
2129 :args (mapcar
2130 #'(lambda (x)
2131 (widget-convert
2132 (cons 'const x)))
2133 org-todo-interpretation-widgets))
2134 widget))
2135 (repeat
2136 (string :tag "Keyword"))))))
2138 (defvar org-todo-keywords-1 nil
2139 "All TODO and DONE keywords active in a buffer.")
2140 (make-variable-buffer-local 'org-todo-keywords-1)
2141 (defvar org-todo-keywords-for-agenda nil)
2142 (defvar org-done-keywords-for-agenda nil)
2143 (defvar org-drawers-for-agenda nil)
2144 (defvar org-todo-keyword-alist-for-agenda nil)
2145 (defvar org-tag-alist-for-agenda nil)
2146 (defvar org-agenda-contributing-files nil)
2147 (defvar org-not-done-keywords nil)
2148 (make-variable-buffer-local 'org-not-done-keywords)
2149 (defvar org-done-keywords nil)
2150 (make-variable-buffer-local 'org-done-keywords)
2151 (defvar org-todo-heads nil)
2152 (make-variable-buffer-local 'org-todo-heads)
2153 (defvar org-todo-sets nil)
2154 (make-variable-buffer-local 'org-todo-sets)
2155 (defvar org-todo-log-states nil)
2156 (make-variable-buffer-local 'org-todo-log-states)
2157 (defvar org-todo-kwd-alist nil)
2158 (make-variable-buffer-local 'org-todo-kwd-alist)
2159 (defvar org-todo-key-alist nil)
2160 (make-variable-buffer-local 'org-todo-key-alist)
2161 (defvar org-todo-key-trigger nil)
2162 (make-variable-buffer-local 'org-todo-key-trigger)
2164 (defcustom org-todo-interpretation 'sequence
2165 "Controls how TODO keywords are interpreted.
2166 This variable is in principle obsolete and is only used for
2167 backward compatibility, if the interpretation of todo keywords is
2168 not given already in `org-todo-keywords'. See that variable for
2169 more information."
2170 :group 'org-todo
2171 :group 'org-keywords
2172 :type '(choice (const sequence)
2173 (const type)))
2175 (defcustom org-use-fast-todo-selection t
2176 "Non-nil means use the fast todo selection scheme with C-c C-t.
2177 This variable describes if and under what circumstances the cycling
2178 mechanism for TODO keywords will be replaced by a single-key, direct
2179 selection scheme.
2181 When nil, fast selection is never used.
2183 When the symbol `prefix', it will be used when `org-todo' is called with
2184 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2185 in an agenda buffer.
2187 When t, fast selection is used by default. In this case, the prefix
2188 argument forces cycling instead.
2190 In all cases, the special interface is only used if access keys have actually
2191 been assigned by the user, i.e. if keywords in the configuration are followed
2192 by a letter in parenthesis, like TODO(t)."
2193 :group 'org-todo
2194 :type '(choice
2195 (const :tag "Never" nil)
2196 (const :tag "By default" t)
2197 (const :tag "Only with C-u C-c C-t" prefix)))
2199 (defcustom org-provide-todo-statistics t
2200 "Non-nil means update todo statistics after insert and toggle.
2201 ALL-HEADLINES means update todo statistics by including headlines
2202 with no TODO keyword as well, counting them as not done.
2203 A list of TODO keywords means the same, but skip keywords that are
2204 not in this list.
2206 When this is set, todo statistics is updated in the parent of the
2207 current entry each time a todo state is changed."
2208 :group 'org-todo
2209 :type '(choice
2210 (const :tag "Yes, only for TODO entries" t)
2211 (const :tag "Yes, including all entries" 'all-headlines)
2212 (repeat :tag "Yes, for TODOs in this list"
2213 (string :tag "TODO keyword"))
2214 (other :tag "No TODO statistics" nil)))
2216 (defcustom org-hierarchical-todo-statistics t
2217 "Non-nil means TODO statistics covers just direct children.
2218 When nil, all entries in the subtree are considered.
2219 This has only an effect if `org-provide-todo-statistics' is set.
2220 To set this to nil for only a single subtree, use a COOKIE_DATA
2221 property and include the word \"recursive\" into the value."
2222 :group 'org-todo
2223 :type 'boolean)
2225 (defcustom org-after-todo-state-change-hook nil
2226 "Hook which is run after the state of a TODO item was changed.
2227 The new state (a string with a TODO keyword, or nil) is available in the
2228 Lisp variable `org-state'."
2229 :group 'org-todo
2230 :type 'hook)
2232 (defvar org-blocker-hook nil
2233 "Hook for functions that are allowed to block a state change.
2235 Each function gets as its single argument a property list, see
2236 `org-trigger-hook' for more information about this list.
2238 If any of the functions in this hook returns nil, the state change
2239 is blocked.")
2241 (defvar org-trigger-hook nil
2242 "Hook for functions that are triggered by a state change.
2244 Each function gets as its single argument a property list with at least
2245 the following elements:
2247 (:type type-of-change :position pos-at-entry-start
2248 :from old-state :to new-state)
2250 Depending on the type, more properties may be present.
2252 This mechanism is currently implemented for:
2254 TODO state changes
2255 ------------------
2256 :type todo-state-change
2257 :from previous state (keyword as a string), or nil, or a symbol
2258 'todo' or 'done', to indicate the general type of state.
2259 :to new state, like in :from")
2261 (defcustom org-enforce-todo-dependencies nil
2262 "Non-nil means undone TODO entries will block switching the parent to DONE.
2263 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2264 be blocked if any prior sibling is not yet done.
2265 Finally, if the parent is blocked because of ordered siblings of its own,
2266 the child will also be blocked."
2267 :set (lambda (var val)
2268 (set var val)
2269 (if val
2270 (add-hook 'org-blocker-hook
2271 'org-block-todo-from-children-or-siblings-or-parent)
2272 (remove-hook 'org-blocker-hook
2273 'org-block-todo-from-children-or-siblings-or-parent)))
2274 :group 'org-todo
2275 :type 'boolean)
2277 (defcustom org-enforce-todo-checkbox-dependencies nil
2278 "Non-nil means unchecked boxes will block switching the parent to DONE.
2279 When this is nil, checkboxes have no influence on switching TODO states.
2280 When non-nil, you first need to check off all check boxes before the TODO
2281 entry can be switched to DONE.
2282 This variable needs to be set before org.el is loaded, and you need to
2283 restart Emacs after a change to make the change effective. The only way
2284 to change is while Emacs is running is through the customize interface."
2285 :set (lambda (var val)
2286 (set var val)
2287 (if val
2288 (add-hook 'org-blocker-hook
2289 'org-block-todo-from-checkboxes)
2290 (remove-hook 'org-blocker-hook
2291 'org-block-todo-from-checkboxes)))
2292 :group 'org-todo
2293 :type 'boolean)
2295 (defcustom org-treat-insert-todo-heading-as-state-change nil
2296 "Non-nil means inserting a TODO heading is treated as state change.
2297 So when the command \\[org-insert-todo-heading] is used, state change
2298 logging will apply if appropriate. When nil, the new TODO item will
2299 be inserted directly, and no logging will take place."
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2304 "Non-nil means switching TODO states with S-cursor counts as state change.
2305 This is the default behavior. However, setting this to nil allows a
2306 convenient way to select a TODO state and bypass any logging associated
2307 with that."
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-todo-state-tags-triggers nil
2312 "Tag changes that should be triggered by TODO state changes.
2313 This is a list. Each entry is
2315 (state-change (tag . flag) .......)
2317 State-change can be a string with a state, and empty string to indicate the
2318 state that has no TODO keyword, or it can be one of the symbols `todo'
2319 or `done', meaning any not-done or done state, respectively."
2320 :group 'org-todo
2321 :group 'org-tags
2322 :type '(repeat
2323 (cons (choice :tag "When changing to"
2324 (const :tag "Not-done state" todo)
2325 (const :tag "Done state" done)
2326 (string :tag "State"))
2327 (repeat
2328 (cons :tag "Tag action"
2329 (string :tag "Tag")
2330 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2332 (defcustom org-log-done nil
2333 "Information to record when a task moves to the DONE state.
2335 Possible values are:
2337 nil Don't add anything, just change the keyword
2338 time Add a time stamp to the task
2339 note Prompt for a note and add it with template `org-log-note-headings'
2341 This option can also be set with on a per-file-basis with
2343 #+STARTUP: nologdone
2344 #+STARTUP: logdone
2345 #+STARTUP: lognotedone
2347 You can have local logging settings for a subtree by setting the LOGGING
2348 property to one or more of these keywords."
2349 :group 'org-todo
2350 :group 'org-progress
2351 :type '(choice
2352 (const :tag "No logging" nil)
2353 (const :tag "Record CLOSED timestamp" time)
2354 (const :tag "Record CLOSED timestamp with note." note)))
2356 ;; Normalize old uses of org-log-done.
2357 (cond
2358 ((eq org-log-done t) (setq org-log-done 'time))
2359 ((and (listp org-log-done) (memq 'done org-log-done))
2360 (setq org-log-done 'note)))
2362 (defcustom org-log-reschedule nil
2363 "Information to record when the scheduling date of a tasks is modified.
2365 Possible values are:
2367 nil Don't add anything, just change the date
2368 time Add a time stamp to the task
2369 note Prompt for a note and add it with template `org-log-note-headings'
2371 This option can also be set with on a per-file-basis with
2373 #+STARTUP: nologreschedule
2374 #+STARTUP: logreschedule
2375 #+STARTUP: lognotereschedule"
2376 :group 'org-todo
2377 :group 'org-progress
2378 :type '(choice
2379 (const :tag "No logging" nil)
2380 (const :tag "Record timestamp" time)
2381 (const :tag "Record timestamp with note." note)))
2383 (defcustom org-log-redeadline nil
2384 "Information to record when the deadline date of a tasks is modified.
2386 Possible values are:
2388 nil Don't add anything, just change the date
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2392 This option can also be set with on a per-file-basis with
2394 #+STARTUP: nologredeadline
2395 #+STARTUP: logredeadline
2396 #+STARTUP: lognoteredeadline
2398 You can have local logging settings for a subtree by setting the LOGGING
2399 property to one or more of these keywords."
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2407 (defcustom org-log-note-clock-out nil
2408 "Non-nil means record a note when clocking out of an item.
2409 This can also be configured on a per-file basis by adding one of
2410 the following lines anywhere in the buffer:
2412 #+STARTUP: lognoteclock-out
2413 #+STARTUP: nolognoteclock-out"
2414 :group 'org-todo
2415 :group 'org-progress
2416 :type 'boolean)
2418 (defcustom org-log-done-with-time t
2419 "Non-nil means the CLOSED time stamp will contain date and time.
2420 When nil, only the date will be recorded."
2421 :group 'org-progress
2422 :type 'boolean)
2424 (defcustom org-log-note-headings
2425 '((done . "CLOSING NOTE %t")
2426 (state . "State %-12s from %-12S %t")
2427 (note . "Note taken on %t")
2428 (reschedule . "Rescheduled from %S on %t")
2429 (delschedule . "Not scheduled, was %S on %t")
2430 (redeadline . "New deadline from %S on %t")
2431 (deldeadline . "Removed deadline, was %S on %t")
2432 (refile . "Refiled on %t")
2433 (clock-out . ""))
2434 "Headings for notes added to entries.
2435 The value is an alist, with the car being a symbol indicating the note
2436 context, and the cdr is the heading to be used. The heading may also be the
2437 empty string.
2438 %t in the heading will be replaced by a time stamp.
2439 %T will be an active time stamp instead the default inactive one
2440 %d will be replaced by a short-format time stamp.
2441 %D will be replaced by an active short-format time stamp.
2442 %s will be replaced by the new TODO state, in double quotes.
2443 %S will be replaced by the old TODO state, in double quotes.
2444 %u will be replaced by the user name.
2445 %U will be replaced by the full user name.
2447 In fact, it is not a good idea to change the `state' entry, because
2448 agenda log mode depends on the format of these entries."
2449 :group 'org-todo
2450 :group 'org-progress
2451 :type '(list :greedy t
2452 (cons (const :tag "Heading when closing an item" done) string)
2453 (cons (const :tag
2454 "Heading when changing todo state (todo sequence only)"
2455 state) string)
2456 (cons (const :tag "Heading when just taking a note" note) string)
2457 (cons (const :tag "Heading when clocking out" clock-out) string)
2458 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2459 (cons (const :tag "Heading when rescheduling" reschedule) string)
2460 (cons (const :tag "Heading when changing deadline" redeadline) string)
2461 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2462 (cons (const :tag "Heading when refiling" refile) string)))
2464 (unless (assq 'note org-log-note-headings)
2465 (push '(note . "%t") org-log-note-headings))
2467 (defcustom org-log-into-drawer nil
2468 "Non-nil means insert state change notes and time stamps into a drawer.
2469 When nil, state changes notes will be inserted after the headline and
2470 any scheduling and clock lines, but not inside a drawer.
2472 The value of this variable should be the name of the drawer to use.
2473 LOGBOOK is proposed as the default drawer for this purpose, you can
2474 also set this to a string to define the drawer of your choice.
2476 A value of t is also allowed, representing \"LOGBOOK\".
2478 If this variable is set, `org-log-state-notes-insert-after-drawers'
2479 will be ignored.
2481 You can set the property LOG_INTO_DRAWER to overrule this setting for
2482 a subtree."
2483 :group 'org-todo
2484 :group 'org-progress
2485 :type '(choice
2486 (const :tag "Not into a drawer" nil)
2487 (const :tag "LOGBOOK" t)
2488 (string :tag "Other")))
2490 (if (fboundp 'defvaralias)
2491 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2493 (defun org-log-into-drawer ()
2494 "Return the value of `org-log-into-drawer', but let properties overrule.
2495 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2496 used instead of the default value."
2497 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2498 (cond
2499 ((or (not p) (equal p "nil")) org-log-into-drawer)
2500 ((equal p "t") "LOGBOOK")
2501 (t p))))
2503 (defcustom org-log-state-notes-insert-after-drawers nil
2504 "Non-nil means insert state change notes after any drawers in entry.
2505 Only the drawers that *immediately* follow the headline and the
2506 deadline/scheduled line are skipped.
2507 When nil, insert notes right after the heading and perhaps the line
2508 with deadline/scheduling if present.
2510 This variable will have no effect if `org-log-into-drawer' is
2511 set."
2512 :group 'org-todo
2513 :group 'org-progress
2514 :type 'boolean)
2516 (defcustom org-log-states-order-reversed t
2517 "Non-nil means the latest state note will be directly after heading.
2518 When nil, the state change notes will be ordered according to time."
2519 :group 'org-todo
2520 :group 'org-progress
2521 :type 'boolean)
2523 (defcustom org-todo-repeat-to-state nil
2524 "The TODO state to which a repeater should return the repeating task.
2525 By default this is the first task in a TODO sequence, or the previous state
2526 in a TODO_TYP set. But you can specify another task here.
2527 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2528 :group 'org-todo
2529 :version "24.1"
2530 :type '(choice (const :tag "Head of sequence" nil)
2531 (string :tag "Specific state")))
2533 (defcustom org-log-repeat 'time
2534 "Non-nil means record moving through the DONE state when triggering repeat.
2535 An auto-repeating task is immediately switched back to TODO when
2536 marked DONE. If you are not logging state changes (by adding \"@\"
2537 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2538 record a closing note, there will be no record of the task moving
2539 through DONE. This variable forces taking a note anyway.
2541 nil Don't force a record
2542 time Record a time stamp
2543 note Record a note
2545 This option can also be set with on a per-file-basis with
2547 #+STARTUP: logrepeat
2548 #+STARTUP: lognoterepeat
2549 #+STARTUP: nologrepeat
2551 You can have local logging settings for a subtree by setting the LOGGING
2552 property to one or more of these keywords."
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type '(choice
2556 (const :tag "Don't force a record" nil)
2557 (const :tag "Force recording the DONE state" time)
2558 (const :tag "Force recording a note with the DONE state" note)))
2561 (defgroup org-priorities nil
2562 "Priorities in Org-mode."
2563 :tag "Org Priorities"
2564 :group 'org-todo)
2566 (defcustom org-enable-priority-commands t
2567 "Non-nil means priority commands are active.
2568 When nil, these commands will be disabled, so that you never accidentally
2569 set a priority."
2570 :group 'org-priorities
2571 :type 'boolean)
2573 (defcustom org-highest-priority ?A
2574 "The highest priority of TODO items. A character like ?A, ?B etc.
2575 Must have a smaller ASCII number than `org-lowest-priority'."
2576 :group 'org-priorities
2577 :type 'character)
2579 (defcustom org-lowest-priority ?C
2580 "The lowest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a larger ASCII number than `org-highest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-default-priority ?B
2586 "The default priority of TODO items.
2587 This is the priority an item gets if no explicit priority is given.
2588 When starting to cycle on an empty priority the first step in the cycle
2589 depends on `org-priority-start-cycle-with-default'. The resulting first
2590 step priority must not exceed the range from `org-highest-priority' to
2591 `org-lowest-priority' which means that `org-default-priority' has to be
2592 in this range exclusive or inclusive the range boundaries. Else the
2593 first step refuses to set the default and the second will fall back
2594 to (depending on the command used) the highest or lowest priority."
2595 :group 'org-priorities
2596 :type 'character)
2598 (defcustom org-priority-start-cycle-with-default t
2599 "Non-nil means start with default priority when starting to cycle.
2600 When this is nil, the first step in the cycle will be (depending on the
2601 command used) one higher or lower than the default priority.
2602 See also `org-default-priority'."
2603 :group 'org-priorities
2604 :type 'boolean)
2606 (defcustom org-get-priority-function nil
2607 "Function to extract the priority from a string.
2608 The string is normally the headline. If this is nil Org computes the
2609 priority from the priority cookie like [#A] in the headline. It returns
2610 an integer, increasing by 1000 for each priority level.
2611 The user can set a different function here, which should take a string
2612 as an argument and return the numeric priority."
2613 :group 'org-priorities
2614 :version "24.1"
2615 :type 'function)
2617 (defgroup org-time nil
2618 "Options concerning time stamps and deadlines in Org-mode."
2619 :tag "Org Time"
2620 :group 'org)
2622 (defcustom org-insert-labeled-timestamps-at-point nil
2623 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2624 When nil, these labeled time stamps are forces into the second line of an
2625 entry, just after the headline. When scheduling from the global TODO list,
2626 the time stamp will always be forced into the second line."
2627 :group 'org-time
2628 :type 'boolean)
2630 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2631 "Formats for `format-time-string' which are used for time stamps.
2632 It is not recommended to change this constant.")
2634 (defcustom org-time-stamp-rounding-minutes '(0 5)
2635 "Number of minutes to round time stamps to.
2636 These are two values, the first applies when first creating a time stamp.
2637 The second applies when changing it with the commands `S-up' and `S-down'.
2638 When changing the time stamp, this means that it will change in steps
2639 of N minutes, as given by the second value.
2641 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2642 numbers should be factors of 60, so for example 5, 10, 15.
2644 When this is larger than 1, you can still force an exact time stamp by using
2645 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2646 and by using a prefix arg to `S-up/down' to specify the exact number
2647 of minutes to shift."
2648 :group 'org-time
2649 :get #'(lambda (var) ; Make sure both elements are there
2650 (if (integerp (default-value var))
2651 (list (default-value var) 5)
2652 (default-value var)))
2653 :type '(list
2654 (integer :tag "when inserting times")
2655 (integer :tag "when modifying times")))
2657 ;; Normalize old customizations of this variable.
2658 (when (integerp org-time-stamp-rounding-minutes)
2659 (setq org-time-stamp-rounding-minutes
2660 (list org-time-stamp-rounding-minutes
2661 org-time-stamp-rounding-minutes)))
2663 (defcustom org-display-custom-times nil
2664 "Non-nil means overlay custom formats over all time stamps.
2665 The formats are defined through the variable `org-time-stamp-custom-formats'.
2666 To turn this on on a per-file basis, insert anywhere in the file:
2667 #+STARTUP: customtime"
2668 :group 'org-time
2669 :set 'set-default
2670 :type 'sexp)
2671 (make-variable-buffer-local 'org-display-custom-times)
2673 (defcustom org-time-stamp-custom-formats
2674 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2675 "Custom formats for time stamps. See `format-time-string' for the syntax.
2676 These are overlaid over the default ISO format if the variable
2677 `org-display-custom-times' is set. Time like %H:%M should be at the
2678 end of the second format. The custom formats are also honored by export
2679 commands, if custom time display is turned on at the time of export."
2680 :group 'org-time
2681 :type 'sexp)
2683 (defun org-time-stamp-format (&optional long inactive)
2684 "Get the right format for a time string."
2685 (let ((f (if long (cdr org-time-stamp-formats)
2686 (car org-time-stamp-formats))))
2687 (if inactive
2688 (concat "[" (substring f 1 -1) "]")
2689 f)))
2691 (defcustom org-time-clocksum-format "%d:%02d"
2692 "The format string used when creating CLOCKSUM lines.
2693 This is also used when org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2697 (defcustom org-time-clocksum-use-fractional nil
2698 "If non-nil, \\[org-clock-display] uses fractional times.
2699 org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'boolean)
2703 (defcustom org-time-clocksum-fractional-format "%.2f"
2704 "The format string used when creating CLOCKSUM lines, or when
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'string)
2709 (defcustom org-deadline-warning-days 14
2710 "No. of days before expiration during which a deadline becomes active.
2711 This variable governs the display in sparse trees and in the agenda.
2712 When 0 or negative, it means use this number (the absolute value of it)
2713 even if a deadline has a different individual lead time specified.
2715 Custom commands can set this variable in the options section."
2716 :group 'org-time
2717 :group 'org-agenda-daily/weekly
2718 :type 'integer)
2720 (defcustom org-read-date-prefer-future t
2721 "Non-nil means assume future for incomplete date input from user.
2722 This affects the following situations:
2723 1. The user gives a month but not a year.
2724 For example, if it is April and you enter \"feb 2\", this will be read
2725 as Feb 2, *next* year. \"May 5\", however, will be this year.
2726 2. The user gives a day, but no month.
2727 For example, if today is the 15th, and you enter \"3\", Org-mode will
2728 read this as the third of *next* month. However, if you enter \"17\",
2729 it will be considered as *this* month.
2731 If you set this variable to the symbol `time', then also the following
2732 will work:
2734 3. If the user gives a time, but no day. If the time is before now,
2735 to will be interpreted as tomorrow.
2737 Currently none of this works for ISO week specifications.
2739 When this option is nil, the current day, month and year will always be
2740 used as defaults.
2742 See also `org-agenda-jump-prefer-future'."
2743 :group 'org-time
2744 :type '(choice
2745 (const :tag "Never" nil)
2746 (const :tag "Check month and day" t)
2747 (const :tag "Check month, day, and time" time)))
2749 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2750 "Should the agenda jump command prefer the future for incomplete dates?
2751 The default is to do the same as configured in `org-read-date-prefer-future'.
2752 But you can also set a deviating value here.
2753 This may t or nil, or the symbol `org-read-date-prefer-future'."
2754 :group 'org-agenda
2755 :group 'org-time
2756 :version "24.1"
2757 :type '(choice
2758 (const :tag "Use org-read-date-prefer-future"
2759 org-read-date-prefer-future)
2760 (const :tag "Never" nil)
2761 (const :tag "Always" t)))
2763 (defcustom org-read-date-force-compatible-dates t
2764 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2766 Depending on the system Emacs is running on, certain dates cannot
2767 be represented with the type used internally to represent time.
2768 Dates between 1970-1-1 and 2038-1-1 can always be represented
2769 correctly. Some systems allow for earlier dates, some for later,
2770 some for both. One way to find out it to insert any date into an
2771 Org buffer, putting the cursor on the year and hitting S-up and
2772 S-down to test the range.
2774 When this variable is set to t, the date/time prompt will not let
2775 you specify dates outside the 1970-2037 range, so it is certain that
2776 these dates will work in whatever version of Emacs you are
2777 running, and also that you can move a file from one Emacs implementation
2778 to another. WHenever Org is forcing the year for you, it will display
2779 a message and beep.
2781 When this variable is nil, Org will check if the date is
2782 representable in the specific Emacs implementation you are using.
2783 If not, it will force a year, usually the current year, and beep
2784 to remind you. Currently this setting is not recommended because
2785 the likelihood that you will open your Org files in an Emacs that
2786 has limited date range is not negligible.
2788 A workaround for this problem is to use diary sexp dates for time
2789 stamps outside of this range."
2790 :group 'org-time
2791 :version "24.1"
2792 :type 'boolean)
2794 (defcustom org-read-date-display-live t
2795 "Non-nil means display current interpretation of date prompt live.
2796 This display will be in an overlay, in the minibuffer."
2797 :group 'org-time
2798 :type 'boolean)
2800 (defcustom org-read-date-popup-calendar t
2801 "Non-nil means pop up a calendar when prompting for a date.
2802 In the calendar, the date can be selected with mouse-1. However, the
2803 minibuffer will also be active, and you can simply enter the date as well.
2804 When nil, only the minibuffer will be available."
2805 :group 'org-time
2806 :type 'boolean)
2807 (if (fboundp 'defvaralias)
2808 (defvaralias 'org-popup-calendar-for-date-prompt
2809 'org-read-date-popup-calendar))
2811 (defcustom org-read-date-minibuffer-setup-hook nil
2812 "Hook to be used to set up keys for the date/time interface.
2813 Add key definitions to `minibuffer-local-map', which will be a temporary
2814 copy."
2815 :group 'org-time
2816 :type 'hook)
2818 (defcustom org-extend-today-until 0
2819 "The hour when your day really ends. Must be an integer.
2820 This has influence for the following applications:
2821 - When switching the agenda to \"today\". It it is still earlier than
2822 the time given here, the day recognized as TODAY is actually yesterday.
2823 - When a date is read from the user and it is still before the time given
2824 here, the current date and time will be assumed to be yesterday, 23:59.
2825 Also, timestamps inserted in remember templates follow this rule.
2827 IMPORTANT: This is a feature whose implementation is and likely will
2828 remain incomplete. Really, it is only here because past midnight seems to
2829 be the favorite working time of John Wiegley :-)"
2830 :group 'org-time
2831 :type 'integer)
2833 (defcustom org-use-effective-time nil
2834 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2835 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2836 \"effective time\" of any timestamps between midnight and 8am will be
2837 23:59 of the previous day."
2838 :group 'org-time
2839 :version "24.1"
2840 :type 'boolean)
2842 (defcustom org-edit-timestamp-down-means-later nil
2843 "Non-nil means S-down will increase the time in a time stamp.
2844 When nil, S-up will increase."
2845 :group 'org-time
2846 :type 'boolean)
2848 (defcustom org-calendar-follow-timestamp-change t
2849 "Non-nil means make the calendar window follow timestamp changes.
2850 When a timestamp is modified and the calendar window is visible, it will be
2851 moved to the new date."
2852 :group 'org-time
2853 :type 'boolean)
2855 (defgroup org-tags nil
2856 "Options concerning tags in Org-mode."
2857 :tag "Org Tags"
2858 :group 'org)
2860 (defcustom org-tag-alist nil
2861 "List of tags allowed in Org-mode files.
2862 When this list is nil, Org-mode will base TAG input on what is already in the
2863 buffer.
2864 The value of this variable is an alist, the car of each entry must be a
2865 keyword as a string, the cdr may be a character that is used to select
2866 that tag through the fast-tag-selection interface.
2867 See the manual for details."
2868 :group 'org-tags
2869 :type '(repeat
2870 (choice
2871 (cons (string :tag "Tag name")
2872 (character :tag "Access char"))
2873 (list :tag "Start radio group"
2874 (const :startgroup)
2875 (option (string :tag "Group description")))
2876 (list :tag "End radio group"
2877 (const :endgroup)
2878 (option (string :tag "Group description")))
2879 (const :tag "New line" (:newline)))))
2881 (defcustom org-tag-persistent-alist nil
2882 "List of tags that will always appear in all Org-mode files.
2883 This is in addition to any in buffer settings or customizations
2884 of `org-tag-alist'.
2885 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2886 The value of this variable is an alist, the car of each entry must be a
2887 keyword as a string, the cdr may be a character that is used to select
2888 that tag through the fast-tag-selection interface.
2889 See the manual for details.
2890 To disable these tags on a per-file basis, insert anywhere in the file:
2891 #+STARTUP: noptag"
2892 :group 'org-tags
2893 :type '(repeat
2894 (choice
2895 (cons (string :tag "Tag name")
2896 (character :tag "Access char"))
2897 (const :tag "Start radio group" (:startgroup))
2898 (const :tag "End radio group" (:endgroup))
2899 (const :tag "New line" (:newline)))))
2901 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2902 "If non-nil, always offer completion for all tags of all agenda files.
2903 Instead of customizing this variable directly, you might want to
2904 set it locally for capture buffers, because there no list of
2905 tags in that file can be created dynamically (there are none).
2907 (add-hook 'org-capture-mode-hook
2908 (lambda ()
2909 (set (make-local-variable
2910 'org-complete-tags-always-offer-all-agenda-tags)
2911 t)))"
2912 :group 'org-tags
2913 :version "24.1"
2914 :type 'boolean)
2916 (defvar org-file-tags nil
2917 "List of tags that can be inherited by all entries in the file.
2918 The tags will be inherited if the variable `org-use-tag-inheritance'
2919 says they should be.
2920 This variable is populated from #+FILETAGS lines.")
2922 (defcustom org-use-fast-tag-selection 'auto
2923 "Non-nil means use fast tag selection scheme.
2924 This is a special interface to select and deselect tags with single keys.
2925 When nil, fast selection is never used.
2926 When the symbol `auto', fast selection is used if and only if selection
2927 characters for tags have been configured, either through the variable
2928 `org-tag-alist' or through a #+TAGS line in the buffer.
2929 When t, fast selection is always used and selection keys are assigned
2930 automatically if necessary."
2931 :group 'org-tags
2932 :type '(choice
2933 (const :tag "Always" t)
2934 (const :tag "Never" nil)
2935 (const :tag "When selection characters are configured" 'auto)))
2937 (defcustom org-fast-tag-selection-single-key nil
2938 "Non-nil means fast tag selection exits after first change.
2939 When nil, you have to press RET to exit it.
2940 During fast tag selection, you can toggle this flag with `C-c'.
2941 This variable can also have the value `expert'. In this case, the window
2942 displaying the tags menu is not even shown, until you press C-c again."
2943 :group 'org-tags
2944 :type '(choice
2945 (const :tag "No" nil)
2946 (const :tag "Yes" t)
2947 (const :tag "Expert" expert)))
2949 (defvar org-fast-tag-selection-include-todo nil
2950 "Non-nil means fast tags selection interface will also offer TODO states.
2951 This is an undocumented feature, you should not rely on it.")
2953 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2954 "The column to which tags should be indented in a headline.
2955 If this number is positive, it specifies the column. If it is negative,
2956 it means that the tags should be flushright to that column. For example,
2957 -80 works well for a normal 80 character screen.
2958 When 0, place tags directly after headline text, with only one space in
2959 between."
2960 :group 'org-tags
2961 :type 'integer)
2963 (defcustom org-auto-align-tags t
2964 "Non-nil keeps tags aligned when modifying headlines.
2965 Some operations (i.e. demoting) change the length of a headline and
2966 therefore shift the tags around. With this option turned on, after
2967 each such operation the tags are again aligned to `org-tags-column'."
2968 :group 'org-tags
2969 :type 'boolean)
2971 (defcustom org-use-tag-inheritance t
2972 "Non-nil means tags in levels apply also for sublevels.
2973 When nil, only the tags directly given in a specific line apply there.
2974 This may also be a list of tags that should be inherited, or a regexp that
2975 matches tags that should be inherited. Additional control is possible
2976 with the variable `org-tags-exclude-from-inheritance' which gives an
2977 explicit list of tags to be excluded from inheritance., even if the value of
2978 `org-use-tag-inheritance' would select it for inheritance.
2980 If this option is t, a match early-on in a tree can lead to a large
2981 number of matches in the subtree when constructing the agenda or creating
2982 a sparse tree. If you only want to see the first match in a tree during
2983 a search, check out the variable `org-tags-match-list-sublevels'."
2984 :group 'org-tags
2985 :type '(choice
2986 (const :tag "Not" nil)
2987 (const :tag "Always" t)
2988 (repeat :tag "Specific tags" (string :tag "Tag"))
2989 (regexp :tag "Tags matched by regexp")))
2991 (defcustom org-tags-exclude-from-inheritance nil
2992 "List of tags that should never be inherited.
2993 This is a way to exclude a few tags from inheritance. For way to do
2994 the opposite, to actively allow inheritance for selected tags,
2995 see the variable `org-use-tag-inheritance'."
2996 :group 'org-tags
2997 :type '(repeat (string :tag "Tag")))
2999 (defun org-tag-inherit-p (tag)
3000 "Check if TAG is one that should be inherited."
3001 (cond
3002 ((member tag org-tags-exclude-from-inheritance) nil)
3003 ((eq org-use-tag-inheritance t) t)
3004 ((not org-use-tag-inheritance) nil)
3005 ((stringp org-use-tag-inheritance)
3006 (string-match org-use-tag-inheritance tag))
3007 ((listp org-use-tag-inheritance)
3008 (member tag org-use-tag-inheritance))
3009 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3011 (defcustom org-tags-match-list-sublevels t
3012 "Non-nil means list also sublevels of headlines matching a search.
3013 This variable applies to tags/property searches, and also to stuck
3014 projects because this search is based on a tags match as well.
3016 When set to the symbol `indented', sublevels are indented with
3017 leading dots.
3019 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3020 the sublevels of a headline matching a tag search often also match
3021 the same search. Listing all of them can create very long lists.
3022 Setting this variable to nil causes subtrees of a match to be skipped.
3024 This variable is semi-obsolete and probably should always be true. It
3025 is better to limit inheritance to certain tags using the variables
3026 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3027 :group 'org-tags
3028 :type '(choice
3029 (const :tag "No, don't list them" nil)
3030 (const :tag "Yes, do list them" t)
3031 (const :tag "List them, indented with leading dots" indented)))
3033 (defcustom org-tags-sort-function nil
3034 "When set, tags are sorted using this function as a comparator."
3035 :group 'org-tags
3036 :type '(choice
3037 (const :tag "No sorting" nil)
3038 (const :tag "Alphabetical" string<)
3039 (const :tag "Reverse alphabetical" string>)
3040 (function :tag "Custom function" nil)))
3042 (defvar org-tags-history nil
3043 "History of minibuffer reads for tags.")
3044 (defvar org-last-tags-completion-table nil
3045 "The last used completion table for tags.")
3046 (defvar org-after-tags-change-hook nil
3047 "Hook that is run after the tags in a line have changed.")
3049 (defgroup org-properties nil
3050 "Options concerning properties in Org-mode."
3051 :tag "Org Properties"
3052 :group 'org)
3054 (defcustom org-property-format "%-10s %s"
3055 "How property key/value pairs should be formatted by `indent-line'.
3056 When `indent-line' hits a property definition, it will format the line
3057 according to this format, mainly to make sure that the values are
3058 lined-up with respect to each other."
3059 :group 'org-properties
3060 :type 'string)
3062 (defcustom org-properties-postprocess-alist nil
3063 "Alist of properties and functions to adjust inserted values.
3064 Elements of this alist must be of the form
3066 ([string] [function])
3068 where [string] must be a property name and [function] must be a
3069 lambda expression: this lambda expression must take one argument,
3070 the value to adjust, and return the new value as a string.
3072 For example, this element will allow the property \"Remaining\"
3073 to be updated wrt the relation between the \"Effort\" property
3074 and the clock summary:
3076 ((\"Remaining\" (lambda(value)
3077 (let ((clocksum (org-clock-sum-current-item))
3078 (effort (org-duration-string-to-minutes
3079 (org-entry-get (point) \"Effort\"))))
3080 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3081 :group 'org-properties
3082 :version "24.1"
3083 :type 'alist)
3085 (defcustom org-use-property-inheritance nil
3086 "Non-nil means properties apply also for sublevels.
3088 This setting is chiefly used during property searches. Turning it on can
3089 cause significant overhead when doing a search, which is why it is not
3090 on by default.
3092 When nil, only the properties directly given in the current entry count.
3093 When t, every property is inherited. The value may also be a list of
3094 properties that should have inheritance, or a regular expression matching
3095 properties that should be inherited.
3097 However, note that some special properties use inheritance under special
3098 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3099 and the properties ending in \"_ALL\" when they are used as descriptor
3100 for valid values of a property.
3102 Note for programmers:
3103 When querying an entry with `org-entry-get', you can control if inheritance
3104 should be used. By default, `org-entry-get' looks only at the local
3105 properties. You can request inheritance by setting the inherit argument
3106 to t (to force inheritance) or to `selective' (to respect the setting
3107 in this variable)."
3108 :group 'org-properties
3109 :type '(choice
3110 (const :tag "Not" nil)
3111 (const :tag "Always" t)
3112 (repeat :tag "Specific properties" (string :tag "Property"))
3113 (regexp :tag "Properties matched by regexp")))
3115 (defun org-property-inherit-p (property)
3116 "Check if PROPERTY is one that should be inherited."
3117 (cond
3118 ((eq org-use-property-inheritance t) t)
3119 ((not org-use-property-inheritance) nil)
3120 ((stringp org-use-property-inheritance)
3121 (string-match org-use-property-inheritance property))
3122 ((listp org-use-property-inheritance)
3123 (member property org-use-property-inheritance))
3124 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3126 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3127 "The default column format, if no other format has been defined.
3128 This variable can be set on the per-file basis by inserting a line
3130 #+COLUMNS: %25ITEM ....."
3131 :group 'org-properties
3132 :type 'string)
3134 (defcustom org-columns-ellipses ".."
3135 "The ellipses to be used when a field in column view is truncated.
3136 When this is the empty string, as many characters as possible are shown,
3137 but then there will be no visual indication that the field has been truncated.
3138 When this is a string of length N, the last N characters of a truncated
3139 field are replaced by this string. If the column is narrower than the
3140 ellipses string, only part of the ellipses string will be shown."
3141 :group 'org-properties
3142 :type 'string)
3144 (defcustom org-columns-modify-value-for-display-function nil
3145 "Function that modifies values for display in column view.
3146 For example, it can be used to cut out a certain part from a time stamp.
3147 The function must take 2 arguments:
3149 column-title The title of the column (*not* the property name)
3150 value The value that should be modified.
3152 The function should return the value that should be displayed,
3153 or nil if the normal value should be used."
3154 :group 'org-properties
3155 :type 'function)
3157 (defcustom org-effort-property "Effort"
3158 "The property that is being used to keep track of effort estimates.
3159 Effort estimates given in this property need to have the format H:MM."
3160 :group 'org-properties
3161 :group 'org-progress
3162 :type '(string :tag "Property"))
3164 (defconst org-global-properties-fixed
3165 '(("VISIBILITY_ALL" . "folded children content all")
3166 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3167 "List of property/value pairs that can be inherited by any entry.
3169 These are fixed values, for the preset properties. The user variable
3170 that can be used to add to this list is `org-global-properties'.
3172 The entries in this list are cons cells where the car is a property
3173 name and cdr is a string with the value. If the value represents
3174 multiple items like an \"_ALL\" property, separate the items by
3175 spaces.")
3177 (defcustom org-global-properties nil
3178 "List of property/value pairs that can be inherited by any entry.
3180 This list will be combined with the constant `org-global-properties-fixed'.
3182 The entries in this list are cons cells where the car is a property
3183 name and cdr is a string with the value.
3185 You can set buffer-local values for the same purpose in the variable
3186 `org-file-properties' this by adding lines like
3188 #+PROPERTY: NAME VALUE"
3189 :group 'org-properties
3190 :type '(repeat
3191 (cons (string :tag "Property")
3192 (string :tag "Value"))))
3194 (defvar org-file-properties nil
3195 "List of property/value pairs that can be inherited by any entry.
3196 Valid for the current buffer.
3197 This variable is populated from #+PROPERTY lines.")
3198 (make-variable-buffer-local 'org-file-properties)
3200 (defgroup org-agenda nil
3201 "Options concerning agenda views in Org-mode."
3202 :tag "Org Agenda"
3203 :group 'org)
3205 (defvar org-category nil
3206 "Variable used by org files to set a category for agenda display.
3207 Such files should use a file variable to set it, for example
3209 # -*- mode: org; org-category: \"ELisp\"
3211 or contain a special line
3213 #+CATEGORY: ELisp
3215 If the file does not specify a category, then file's base name
3216 is used instead.")
3217 (make-variable-buffer-local 'org-category)
3218 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3220 (defcustom org-agenda-files nil
3221 "The files to be used for agenda display.
3222 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3223 \\[org-remove-file]. You can also use customize to edit the list.
3225 If an entry is a directory, all files in that directory that are matched by
3226 `org-agenda-file-regexp' will be part of the file list.
3228 If the value of the variable is not a list but a single file name, then
3229 the list of agenda files is actually stored and maintained in that file, one
3230 agenda file per line. In this file paths can be given relative to
3231 `org-directory'. Tilde expansion and environment variable substitution
3232 are also made."
3233 :group 'org-agenda
3234 :type '(choice
3235 (repeat :tag "List of files and directories" file)
3236 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3238 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3239 "Regular expression to match files for `org-agenda-files'.
3240 If any element in the list in that variable contains a directory instead
3241 of a normal file, all files in that directory that are matched by this
3242 regular expression will be included."
3243 :group 'org-agenda
3244 :type 'regexp)
3246 (defcustom org-agenda-text-search-extra-files nil
3247 "List of extra files to be searched by text search commands.
3248 These files will be search in addition to the agenda files by the
3249 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3250 Note that these files will only be searched for text search commands,
3251 not for the other agenda views like todo lists, tag searches or the weekly
3252 agenda. This variable is intended to list notes and possibly archive files
3253 that should also be searched by these two commands.
3254 In fact, if the first element in the list is the symbol `agenda-archives',
3255 than all archive files of all agenda files will be added to the search
3256 scope."
3257 :group 'org-agenda
3258 :type '(set :greedy t
3259 (const :tag "Agenda Archives" agenda-archives)
3260 (repeat :inline t (file))))
3262 (if (fboundp 'defvaralias)
3263 (defvaralias 'org-agenda-multi-occur-extra-files
3264 'org-agenda-text-search-extra-files))
3266 (defcustom org-agenda-skip-unavailable-files nil
3267 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3268 A nil value means to remove them, after a query, from the list."
3269 :group 'org-agenda
3270 :type 'boolean)
3272 (defcustom org-calendar-to-agenda-key [?c]
3273 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3274 The command `org-calendar-goto-agenda' will be bound to this key. The
3275 default is the character `c' because then `c' can be used to switch back and
3276 forth between agenda and calendar."
3277 :group 'org-agenda
3278 :type 'sexp)
3280 (defcustom org-calendar-agenda-action-key [?k]
3281 "The key to be installed in `calendar-mode-map' for agenda-action.
3282 The command `org-agenda-action' will be bound to this key. The
3283 default is the character `k' because we use the same key in the agenda."
3284 :group 'org-agenda
3285 :type 'sexp)
3287 (defcustom org-calendar-insert-diary-entry-key [?i]
3288 "The key to be installed in `calendar-mode-map' for adding diary entries.
3289 This option is irrelevant until `org-agenda-diary-file' has been configured
3290 to point to an Org-mode file. When that is the case, the command
3291 `org-agenda-diary-entry' will be bound to the key given here, by default
3292 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3293 if you want to continue doing this, you need to change this to a different
3294 key."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-agenda-diary-file 'diary-file
3299 "File to which to add new entries with the `i' key in agenda and calendar.
3300 When this is the symbol `diary-file', the functionality in the Emacs
3301 calendar will be used to add entries to the `diary-file'. But when this
3302 points to a file, `org-agenda-diary-entry' will be used instead."
3303 :group 'org-agenda
3304 :type '(choice
3305 (const :tag "The standard Emacs diary file" diary-file)
3306 (file :tag "Special Org file diary entries")))
3308 (eval-after-load "calendar"
3309 '(progn
3310 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3311 'org-calendar-goto-agenda)
3312 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3313 'org-agenda-action)
3314 (add-hook 'calendar-mode-hook
3315 (lambda ()
3316 (unless (eq org-agenda-diary-file 'diary-file)
3317 (define-key calendar-mode-map
3318 org-calendar-insert-diary-entry-key
3319 'org-agenda-diary-entry))))))
3321 (defgroup org-latex nil
3322 "Options for embedding LaTeX code into Org-mode."
3323 :tag "Org LaTeX"
3324 :group 'org)
3326 (defcustom org-format-latex-options
3327 '(:foreground default :background default :scale 1.0
3328 :html-foreground "Black" :html-background "Transparent"
3329 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3330 "Options for creating images from LaTeX fragments.
3331 This is a property list with the following properties:
3332 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3333 `default' means use the foreground of the default face.
3334 :background the background color, or \"Transparent\".
3335 `default' means use the background of the default face.
3336 :scale a scaling factor for the size of the images, to get more pixels
3337 :html-foreground, :html-background, :html-scale
3338 the same numbers for HTML export.
3339 :matchers a list indicating which matchers should be used to
3340 find LaTeX fragments. Valid members of this list are:
3341 \"begin\" find environments
3342 \"$1\" find single characters surrounded by $.$
3343 \"$\" find math expressions surrounded by $...$
3344 \"$$\" find math expressions surrounded by $$....$$
3345 \"\\(\" find math expressions surrounded by \\(...\\)
3346 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3347 :group 'org-latex
3348 :type 'plist)
3350 (defcustom org-format-latex-signal-error t
3351 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3352 When nil, just push out a message."
3353 :group 'org-latex
3354 :version "24.1"
3355 :type 'boolean)
3356 (defcustom org-latex-to-mathml-jar-file nil
3357 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3358 Use this to specify additional executable file say a jar file.
3360 When using MathToWeb as the converter, specify the full-path to
3361 your mathtoweb.jar file."
3362 :group 'org-latex
3363 :version "24.1"
3364 :type '(choice
3365 (const :tag "None" nil)
3366 (file :tag "JAR file" :must-match t)))
3368 (defcustom org-latex-to-mathml-convert-command nil
3369 "Command to convert LaTeX fragments to MathML.
3370 Replace format-specifiers in the command as noted below and use
3371 `shell-command' to convert LaTeX to MathML.
3372 %j: Executable file in fully expanded form as specified by
3373 `org-latex-to-mathml-jar-file'.
3374 %I: Input LaTeX file in fully expanded form
3375 %o: Output MathML file
3376 This command is used by `org-create-math-formula'.
3378 When using MathToWeb as the converter, set this to
3379 \"java -jar %j -unicode -force -df %o %I\"."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type '(choice
3383 (const :tag "None" nil)
3384 (string :tag "\nShell command")))
3386 (defun org-format-latex-mathml-available-p ()
3387 "Return t if `org-latex-to-mathml-convert-command' is usable."
3388 (save-match-data
3389 (when (and (boundp 'org-latex-to-mathml-convert-command)
3390 org-latex-to-mathml-convert-command)
3391 (let ((executable (car (split-string
3392 org-latex-to-mathml-convert-command))))
3393 (when (executable-find executable)
3394 (if (string-match
3395 "%j" org-latex-to-mathml-convert-command)
3396 (file-readable-p org-latex-to-mathml-jar-file)
3397 t))))))
3399 (defcustom org-format-latex-header "\\documentclass{article}
3400 \\usepackage[usenames]{color}
3401 \\usepackage{amsmath}
3402 \\usepackage[mathscr]{eucal}
3403 \\pagestyle{empty} % do not remove
3404 \[PACKAGES]
3405 \[DEFAULT-PACKAGES]
3406 % The settings below are copied from fullpage.sty
3407 \\setlength{\\textwidth}{\\paperwidth}
3408 \\addtolength{\\textwidth}{-3cm}
3409 \\setlength{\\oddsidemargin}{1.5cm}
3410 \\addtolength{\\oddsidemargin}{-2.54cm}
3411 \\setlength{\\evensidemargin}{\\oddsidemargin}
3412 \\setlength{\\textheight}{\\paperheight}
3413 \\addtolength{\\textheight}{-\\headheight}
3414 \\addtolength{\\textheight}{-\\headsep}
3415 \\addtolength{\\textheight}{-\\footskip}
3416 \\addtolength{\\textheight}{-3cm}
3417 \\setlength{\\topmargin}{1.5cm}
3418 \\addtolength{\\topmargin}{-2.54cm}"
3419 "The document header used for processing LaTeX fragments.
3420 It is imperative that this header make sure that no page number
3421 appears on the page. The package defined in the variables
3422 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3423 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3424 will be appended."
3425 :group 'org-latex
3426 :type 'string)
3428 (defvar org-format-latex-header-extra nil)
3430 (defun org-set-packages-alist (var val)
3431 "Set the packages alist and make sure it has 3 elements per entry."
3432 (set var (mapcar (lambda (x)
3433 (if (and (consp x) (= (length x) 2))
3434 (list (car x) (nth 1 x) t)
3436 val)))
3438 (defun org-get-packages-alist (var)
3440 "Get the packages alist and make sure it has 3 elements per entry."
3441 (mapcar (lambda (x)
3442 (if (and (consp x) (= (length x) 2))
3443 (list (car x) (nth 1 x) t)
3445 (default-value var)))
3447 ;; The following variables are defined here because is it also used
3448 ;; when formatting latex fragments. Originally it was part of the
3449 ;; LaTeX exporter, which is why the name includes "export".
3450 (defcustom org-export-latex-default-packages-alist
3451 '(("AUTO" "inputenc" t)
3452 ("T1" "fontenc" t)
3453 ("" "fixltx2e" nil)
3454 ("" "graphicx" t)
3455 ("" "longtable" nil)
3456 ("" "float" nil)
3457 ("" "wrapfig" nil)
3458 ("" "soul" t)
3459 ("" "textcomp" t)
3460 ("" "marvosym" t)
3461 ("" "wasysym" t)
3462 ("" "latexsym" t)
3463 ("" "amssymb" t)
3464 ("" "hyperref" nil)
3465 "\\tolerance=1000"
3467 "Alist of default packages to be inserted in the header.
3468 Change this only if one of the packages here causes an incompatibility
3469 with another package you are using.
3470 The packages in this list are needed by one part or another of Org-mode
3471 to function properly.
3473 - inputenc, fontenc: for basic font and character selection
3474 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3475 for interpreting the entities in `org-entities'. You can skip some of these
3476 packages if you don't use any of the symbols in it.
3477 - graphicx: for including images
3478 - float, wrapfig: for figure placement
3479 - longtable: for long tables
3480 - hyperref: for cross references
3482 Therefore you should not modify this variable unless you know what you
3483 are doing. The one reason to change it anyway is that you might be loading
3484 some other package that conflicts with one of the default packages.
3485 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3486 If SNIPPET-FLAG is t, the package also needs to be included when
3487 compiling LaTeX snippets into images for inclusion into HTML."
3488 :group 'org-export-latex
3489 :set 'org-set-packages-alist
3490 :get 'org-get-packages-alist
3491 :version "24.1"
3492 :type '(repeat
3493 (choice
3494 (list :tag "options/package pair"
3495 (string :tag "options")
3496 (string :tag "package")
3497 (boolean :tag "Snippet"))
3498 (string :tag "A line of LaTeX"))))
3500 (defcustom org-export-latex-packages-alist nil
3501 "Alist of packages to be inserted in every LaTeX header.
3502 These will be inserted after `org-export-latex-default-packages-alist'.
3503 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3504 SNIPPET-FLAG, when t, indicates that this package is also needed when
3505 turning LaTeX snippets into images for inclusion into HTML.
3506 Make sure that you only list packages here which:
3507 - you want in every file
3508 - do not conflict with the default packages in
3509 `org-export-latex-default-packages-alist'
3510 - do not conflict with the setup in `org-format-latex-header'."
3511 :group 'org-export-latex
3512 :set 'org-set-packages-alist
3513 :get 'org-get-packages-alist
3514 :type '(repeat
3515 (choice
3516 (list :tag "options/package pair"
3517 (string :tag "options")
3518 (string :tag "package")
3519 (boolean :tag "Snippet"))
3520 (string :tag "A line of LaTeX"))))
3523 (defgroup org-appearance nil
3524 "Settings for Org-mode appearance."
3525 :tag "Org Appearance"
3526 :group 'org)
3528 (defcustom org-level-color-stars-only nil
3529 "Non-nil means fontify only the stars in each headline.
3530 When nil, the entire headline is fontified.
3531 Changing it requires restart of `font-lock-mode' to become effective
3532 also in regions already fontified."
3533 :group 'org-appearance
3534 :type 'boolean)
3536 (defcustom org-hide-leading-stars nil
3537 "Non-nil means hide the first N-1 stars in a headline.
3538 This works by using the face `org-hide' for these stars. This
3539 face is white for a light background, and black for a dark
3540 background. You may have to customize the face `org-hide' to
3541 make this work.
3542 Changing it requires restart of `font-lock-mode' to become effective
3543 also in regions already fontified.
3544 You may also set this on a per-file basis by adding one of the following
3545 lines to the buffer:
3547 #+STARTUP: hidestars
3548 #+STARTUP: showstars"
3549 :group 'org-appearance
3550 :type 'boolean)
3552 (defcustom org-hidden-keywords nil
3553 "List of symbols corresponding to keywords to be hidden the org buffer.
3554 For example, a value '(title) for this list will make the document's title
3555 appear in the buffer without the initial #+TITLE: keyword."
3556 :group 'org-appearance
3557 :version "24.1"
3558 :type '(set (const :tag "#+AUTHOR" author)
3559 (const :tag "#+DATE" date)
3560 (const :tag "#+EMAIL" email)
3561 (const :tag "#+TITLE" title)))
3563 (defcustom org-fontify-done-headline nil
3564 "Non-nil means change the face of a headline if it is marked DONE.
3565 Normally, only the TODO/DONE keyword indicates the state of a headline.
3566 When this is non-nil, the headline after the keyword is set to the
3567 `org-headline-done' as an additional indication."
3568 :group 'org-appearance
3569 :type 'boolean)
3571 (defcustom org-fontify-emphasized-text t
3572 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3573 Changing this variable requires a restart of Emacs to take effect."
3574 :group 'org-appearance
3575 :type 'boolean)
3577 (defcustom org-fontify-whole-heading-line nil
3578 "Non-nil means fontify the whole line for headings.
3579 This is useful when setting a background color for the
3580 org-level-* faces."
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-highlight-latex-fragments-and-specials nil
3585 "Non-nil means fontify what is treated specially by the exporters."
3586 :group 'org-appearance
3587 :type 'boolean)
3589 (defcustom org-hide-emphasis-markers nil
3590 "Non-nil mean font-lock should hide the emphasis marker characters."
3591 :group 'org-appearance
3592 :type 'boolean)
3594 (defcustom org-pretty-entities nil
3595 "Non-nil means show entities as UTF8 characters.
3596 When nil, the \\name form remains in the buffer."
3597 :group 'org-appearance
3598 :version "24.1"
3599 :type 'boolean)
3601 (defcustom org-pretty-entities-include-sub-superscripts t
3602 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3603 :group 'org-appearance
3604 :version "24.1"
3605 :type 'boolean)
3607 (defvar org-emph-re nil
3608 "Regular expression for matching emphasis.
3609 After a match, the match groups contain these elements:
3610 0 The match of the full regular expression, including the characters
3611 before and after the proper match
3612 1 The character before the proper match, or empty at beginning of line
3613 2 The proper match, including the leading and trailing markers
3614 3 The leading marker like * or /, indicating the type of highlighting
3615 4 The text between the emphasis markers, not including the markers
3616 5 The character after the match, empty at the end of a line")
3617 (defvar org-verbatim-re nil
3618 "Regular expression for matching verbatim text.")
3619 (defvar org-emphasis-regexp-components) ; defined just below
3620 (defvar org-emphasis-alist) ; defined just below
3621 (defun org-set-emph-re (var val)
3622 "Set variable and compute the emphasis regular expression."
3623 (set var val)
3624 (when (and (boundp 'org-emphasis-alist)
3625 (boundp 'org-emphasis-regexp-components)
3626 org-emphasis-alist org-emphasis-regexp-components)
3627 (let* ((e org-emphasis-regexp-components)
3628 (pre (car e))
3629 (post (nth 1 e))
3630 (border (nth 2 e))
3631 (body (nth 3 e))
3632 (nl (nth 4 e))
3633 (body1 (concat body "*?"))
3634 (markers (mapconcat 'car org-emphasis-alist ""))
3635 (vmarkers (mapconcat
3636 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3637 org-emphasis-alist "")))
3638 ;; make sure special characters appear at the right position in the class
3639 (if (string-match "\\^" markers)
3640 (setq markers (concat (replace-match "" t t markers) "^")))
3641 (if (string-match "-" markers)
3642 (setq markers (concat (replace-match "" t t markers) "-")))
3643 (if (string-match "\\^" vmarkers)
3644 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3645 (if (string-match "-" vmarkers)
3646 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3647 (if (> nl 0)
3648 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3649 (int-to-string nl) "\\}")))
3650 ;; Make the regexp
3651 (setq org-emph-re
3652 (concat "\\([" pre "]\\|^\\)"
3653 "\\("
3654 "\\([" markers "]\\)"
3655 "\\("
3656 "[^" border "]\\|"
3657 "[^" border "]"
3658 body1
3659 "[^" border "]"
3660 "\\)"
3661 "\\3\\)"
3662 "\\([" post "]\\|$\\)"))
3663 (setq org-verbatim-re
3664 (concat "\\([" pre "]\\|^\\)"
3665 "\\("
3666 "\\([" vmarkers "]\\)"
3667 "\\("
3668 "[^" border "]\\|"
3669 "[^" border "]"
3670 body1
3671 "[^" border "]"
3672 "\\)"
3673 "\\3\\)"
3674 "\\([" post "]\\|$\\)")))))
3676 (defcustom org-emphasis-regexp-components
3677 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3678 "Components used to build the regular expression for emphasis.
3679 This is a list with five entries. Terminology: In an emphasis string
3680 like \" *strong word* \", we call the initial space PREMATCH, the final
3681 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3682 and \"trong wor\" is the body. The different components in this variable
3683 specify what is allowed/forbidden in each part:
3685 pre Chars allowed as prematch. Beginning of line will be allowed too.
3686 post Chars allowed as postmatch. End of line will be allowed too.
3687 border The chars *forbidden* as border characters.
3688 body-regexp A regexp like \".\" to match a body character. Don't use
3689 non-shy groups here, and don't allow newline here.
3690 newline The maximum number of newlines allowed in an emphasis exp.
3692 Use customize to modify this, or restart Emacs after changing it."
3693 :group 'org-appearance
3694 :set 'org-set-emph-re
3695 :type '(list
3696 (sexp :tag "Allowed chars in pre ")
3697 (sexp :tag "Allowed chars in post ")
3698 (sexp :tag "Forbidden chars in border ")
3699 (sexp :tag "Regexp for body ")
3700 (integer :tag "number of newlines allowed")
3701 (option (boolean :tag "Please ignore this button"))))
3703 (defcustom org-emphasis-alist
3704 `(("*" bold "<b>" "</b>")
3705 ("/" italic "<i>" "</i>")
3706 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3707 ("=" org-code "<code>" "</code>" verbatim)
3708 ("~" org-verbatim "<code>" "</code>" verbatim)
3709 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3710 "<del>" "</del>")
3712 "Special syntax for emphasized text.
3713 Text starting and ending with a special character will be emphasized, for
3714 example *bold*, _underlined_ and /italic/. This variable sets the marker
3715 characters, the face to be used by font-lock for highlighting in Org-mode
3716 Emacs buffers, and the HTML tags to be used for this.
3717 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3718 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3719 Use customize to modify this, or restart Emacs after changing it."
3720 :group 'org-appearance
3721 :set 'org-set-emph-re
3722 :type '(repeat
3723 (list
3724 (string :tag "Marker character")
3725 (choice
3726 (face :tag "Font-lock-face")
3727 (plist :tag "Face property list"))
3728 (string :tag "HTML start tag")
3729 (string :tag "HTML end tag")
3730 (option (const verbatim)))))
3732 (defvar org-protecting-blocks
3733 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3734 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3735 This is needed for font-lock setup.")
3737 ;;; Miscellaneous options
3739 (defgroup org-completion nil
3740 "Completion in Org-mode."
3741 :tag "Org Completion"
3742 :group 'org)
3744 (defcustom org-completion-use-ido nil
3745 "Non-nil means use ido completion wherever possible.
3746 Note that `ido-mode' must be active for this variable to be relevant.
3747 If you decide to turn this variable on, you might well want to turn off
3748 `org-outline-path-complete-in-steps'.
3749 See also `org-completion-use-iswitchb'."
3750 :group 'org-completion
3751 :type 'boolean)
3753 (defcustom org-completion-use-iswitchb nil
3754 "Non-nil means use iswitchb completion wherever possible.
3755 Note that `iswitchb-mode' must be active for this variable to be relevant.
3756 If you decide to turn this variable on, you might well want to turn off
3757 `org-outline-path-complete-in-steps'.
3758 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3759 :group 'org-completion
3760 :type 'boolean)
3762 (defcustom org-completion-fallback-command 'hippie-expand
3763 "The expansion command called by \\[pcomplete] in normal context.
3764 Normal means, no org-mode-specific context."
3765 :group 'org-completion
3766 :type 'function)
3768 ;;; Functions and variables from their packages
3769 ;; Declared here to avoid compiler warnings
3771 ;; XEmacs only
3772 (defvar outline-mode-menu-heading)
3773 (defvar outline-mode-menu-show)
3774 (defvar outline-mode-menu-hide)
3775 (defvar zmacs-regions) ; XEmacs regions
3777 ;; Emacs only
3778 (defvar mark-active)
3780 ;; Various packages
3781 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3782 (declare-function calendar-forward-day "cal-move" (arg))
3783 (declare-function calendar-goto-date "cal-move" (date))
3784 (declare-function calendar-goto-today "cal-move" ())
3785 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3786 (defvar calc-embedded-close-formula)
3787 (defvar calc-embedded-open-formula)
3788 (declare-function cdlatex-tab "ext:cdlatex" ())
3789 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3790 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3791 (defvar font-lock-unfontify-region-function)
3792 (declare-function iswitchb-read-buffer "iswitchb"
3793 (prompt &optional default require-match start matches-set))
3794 (defvar iswitchb-temp-buflist)
3795 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3796 (defvar org-agenda-tags-todo-honor-ignore-options)
3797 (declare-function org-agenda-skip "org-agenda" ())
3798 (declare-function
3799 org-agenda-format-item "org-agenda"
3800 (extra txt &optional category tags dotime noprefix remove-re habitp))
3801 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3802 (declare-function org-agenda-change-all-lines "org-agenda"
3803 (newhead hdmarker &optional fixface just-this))
3804 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3805 (declare-function org-agenda-maybe-redo "org-agenda" ())
3806 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3807 (beg end))
3808 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3809 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3810 "org-agenda" (&optional end))
3811 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3812 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3813 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3814 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3815 (declare-function org-indent-mode "org-indent" (&optional arg))
3816 (declare-function parse-time-string "parse-time" (string))
3817 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3818 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3819 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3820 (defvar remember-data-file)
3821 (defvar texmathp-why)
3822 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3823 (declare-function table--at-cell-p "table" (position &optional object at-column))
3825 (defvar w3m-current-url)
3826 (defvar w3m-current-title)
3828 (defvar org-latex-regexps)
3830 ;;; Autoload and prepare some org modules
3832 ;; Some table stuff that needs to be defined here, because it is used
3833 ;; by the functions setting up org-mode or checking for table context.
3835 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3836 "Detect an org-type or table-type table.")
3837 (defconst org-table-line-regexp "^[ \t]*|"
3838 "Detect an org-type table line.")
3839 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3840 "Detect an org-type table line.")
3841 (defconst org-table-hline-regexp "^[ \t]*|-"
3842 "Detect an org-type table hline.")
3843 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3844 "Detect a table-type table hline.")
3845 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3846 "Detect the first line outside a table when searching from within it.
3847 This works for both table types.")
3849 ;; Autoload the functions in org-table.el that are needed by functions here.
3851 (eval-and-compile
3852 (org-autoload "org-table"
3853 '(org-table-align org-table-begin org-table-blank-field
3854 org-table-convert org-table-convert-region org-table-copy-down
3855 org-table-copy-region org-table-create
3856 org-table-create-or-convert-from-region
3857 org-table-create-with-table.el org-table-current-dline
3858 org-table-cut-region org-table-delete-column org-table-edit-field
3859 org-table-edit-formulas org-table-end org-table-eval-formula
3860 org-table-export org-table-field-info
3861 org-table-get-stored-formulas org-table-goto-column
3862 org-table-hline-and-move org-table-import org-table-insert-column
3863 org-table-insert-hline org-table-insert-row org-table-iterate
3864 org-table-justify-field-maybe org-table-kill-row
3865 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3866 org-table-move-column org-table-move-column-left
3867 org-table-move-column-right org-table-move-row
3868 org-table-move-row-down org-table-move-row-up
3869 org-table-next-field org-table-next-row org-table-paste-rectangle
3870 org-table-previous-field org-table-recalculate
3871 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3872 org-table-toggle-coordinate-overlays
3873 org-table-toggle-formula-debugger org-table-wrap-region
3874 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3875 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3876 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3878 (defun org-at-table-p (&optional table-type)
3879 "Return t if the cursor is inside an org-type table.
3880 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3881 (if org-enable-table-editor
3882 (save-excursion
3883 (beginning-of-line 1)
3884 (looking-at (if table-type org-table-any-line-regexp
3885 org-table-line-regexp)))
3886 nil))
3887 (defsubst org-table-p () (org-at-table-p))
3889 (defun org-at-table.el-p ()
3890 "Return t if and only if we are at a table.el table."
3891 (and (org-at-table-p 'any)
3892 (save-excursion
3893 (goto-char (org-table-begin 'any))
3894 (looking-at org-table1-hline-regexp))))
3895 (defun org-table-recognize-table.el ()
3896 "If there is a table.el table nearby, recognize it and move into it."
3897 (if org-table-tab-recognizes-table.el
3898 (if (org-at-table.el-p)
3899 (progn
3900 (beginning-of-line 1)
3901 (if (looking-at org-table-dataline-regexp)
3903 (if (looking-at org-table1-hline-regexp)
3904 (progn
3905 (beginning-of-line 2)
3906 (if (looking-at org-table-any-border-regexp)
3907 (beginning-of-line -1)))))
3908 (if (re-search-forward "|" (org-table-end t) t)
3909 (progn
3910 (require 'table)
3911 (if (table--at-cell-p (point))
3913 (message "recognizing table.el table...")
3914 (table-recognize-table)
3915 (message "recognizing table.el table...done")))
3916 (error "This should not happen"))
3918 nil)
3919 nil))
3921 (defun org-at-table-hline-p ()
3922 "Return t if the cursor is inside a hline in a table."
3923 (if org-enable-table-editor
3924 (save-excursion
3925 (beginning-of-line 1)
3926 (looking-at org-table-hline-regexp))
3927 nil))
3929 (defvar org-table-clean-did-remove-column nil)
3931 (defun org-table-map-tables (function &optional quietly)
3932 "Apply FUNCTION to the start of all tables in the buffer."
3933 (save-excursion
3934 (save-restriction
3935 (widen)
3936 (goto-char (point-min))
3937 (while (re-search-forward org-table-any-line-regexp nil t)
3938 (unless quietly
3939 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3940 (beginning-of-line 1)
3941 (when (looking-at org-table-line-regexp)
3942 (save-excursion (funcall function))
3943 (or (looking-at org-table-line-regexp)
3944 (forward-char 1)))
3945 (re-search-forward org-table-any-border-regexp nil 1))))
3946 (unless quietly (message "Mapping tables: done")))
3948 ;; Declare and autoload functions from org-exp.el & Co
3950 (declare-function org-default-export-plist "org-exp")
3951 (declare-function org-infile-export-plist "org-exp")
3952 (declare-function org-get-current-options "org-exp")
3953 (eval-and-compile
3954 (org-autoload "org-exp"
3955 '(org-export org-export-visible
3956 org-insert-export-options-template
3957 org-table-clean-before-export))
3958 (org-autoload "org-ascii"
3959 '(org-export-as-ascii org-export-ascii-preprocess
3960 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3961 org-export-region-as-ascii))
3962 (org-autoload "org-latex"
3963 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3964 org-replace-region-by-latex org-export-region-as-latex
3965 org-export-as-latex org-export-as-pdf
3966 org-export-as-pdf-and-open))
3967 (org-autoload "org-html"
3968 '(org-export-as-html-and-open
3969 org-export-as-html-batch org-export-as-html-to-buffer
3970 org-replace-region-by-html org-export-region-as-html
3971 org-export-as-html))
3972 (org-autoload "org-docbook"
3973 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3974 org-replace-region-by-docbook org-export-region-as-docbook
3975 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3976 org-export-as-docbook))
3977 (org-autoload "org-icalendar"
3978 '(org-export-icalendar-this-file
3979 org-export-icalendar-all-agenda-files
3980 org-export-icalendar-combine-agenda-files))
3981 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3982 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3984 ;; Declare and autoload functions from org-agenda.el
3986 (eval-and-compile
3987 (org-autoload "org-agenda"
3988 '(org-agenda org-agenda-list org-search-view
3989 org-todo-list org-tags-view org-agenda-list-stuck-projects
3990 org-diary org-agenda-to-appt
3991 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3993 ;; Autoload org-remember
3995 (eval-and-compile
3996 (org-autoload "org-remember"
3997 '(org-remember-insinuate org-remember-annotation
3998 org-remember-apply-template org-remember org-remember-handler)))
4000 (eval-and-compile
4001 (org-autoload "org-capture"
4002 '(org-capture org-capture-insert-template-here
4003 org-capture-import-remember-templates)))
4005 ;; Autoload org-clock.el
4007 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4008 (beg end))
4009 (declare-function org-clock-update-mode-line "org-clock" ())
4010 (declare-function org-resolve-clocks "org-clock"
4011 (&optional also-non-dangling-p prompt last-valid))
4012 (defvar org-clock-start-time)
4013 (defvar org-clock-marker (make-marker)
4014 "Marker recording the last clock-in.")
4015 (defvar org-clock-hd-marker (make-marker)
4016 "Marker recording the last clock-in, but the headline position.")
4017 (defvar org-clock-heading ""
4018 "The heading of the current clock entry.")
4019 (defun org-clock-is-active ()
4020 "Return non-nil if clock is currently running.
4021 The return value is actually the clock marker."
4022 (marker-buffer org-clock-marker))
4024 (eval-and-compile
4025 (org-autoload
4026 "org-clock"
4027 '(org-clock-in org-clock-out org-clock-cancel
4028 org-clock-goto org-clock-sum org-clock-display
4029 org-clock-remove-overlays org-clock-report
4030 org-clocktable-shift org-dblock-write:clocktable
4031 org-get-clocktable org-resolve-clocks)))
4033 (defun org-clock-update-time-maybe ()
4034 "If this is a CLOCK line, update it and return t.
4035 Otherwise, return nil."
4036 (interactive)
4037 (save-excursion
4038 (beginning-of-line 1)
4039 (skip-chars-forward " \t")
4040 (when (looking-at org-clock-string)
4041 (let ((re (concat "[ \t]*" org-clock-string
4042 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4043 "\\([ \t]*=>.*\\)?\\)?"))
4044 ts te h m s neg)
4045 (cond
4046 ((not (looking-at re))
4047 nil)
4048 ((not (match-end 2))
4049 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4050 (> org-clock-marker (point))
4051 (<= org-clock-marker (point-at-eol)))
4052 ;; The clock is running here
4053 (setq org-clock-start-time
4054 (apply 'encode-time
4055 (org-parse-time-string (match-string 1))))
4056 (org-clock-update-mode-line)))
4058 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4059 (end-of-line 1)
4060 (setq ts (match-string 1)
4061 te (match-string 3))
4062 (setq s (- (org-float-time
4063 (apply 'encode-time (org-parse-time-string te)))
4064 (org-float-time
4065 (apply 'encode-time (org-parse-time-string ts))))
4066 neg (< s 0)
4067 s (abs s)
4068 h (floor (/ s 3600))
4069 s (- s (* 3600 h))
4070 m (floor (/ s 60))
4071 s (- s (* 60 s)))
4072 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4073 t))))))
4075 (defun org-check-running-clock ()
4076 "Check if the current buffer contains the running clock.
4077 If yes, offer to stop it and to save the buffer with the changes."
4078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4079 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4080 (buffer-name))))
4081 (org-clock-out)
4082 (when (y-or-n-p "Save changed buffer?")
4083 (save-buffer))))
4085 (defun org-clocktable-try-shift (dir n)
4086 "Check if this line starts a clock table, if yes, shift the time block."
4087 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4088 (org-clocktable-shift dir n)))
4090 ;; Autoload org-timer.el
4092 (eval-and-compile
4093 (org-autoload
4094 "org-timer"
4095 '(org-timer-start org-timer org-timer-item
4096 org-timer-change-times-in-region
4097 org-timer-set-timer
4098 org-timer-reset-timers
4099 org-timer-show-remaining-time)))
4101 ;; Autoload org-feed.el
4103 (eval-and-compile
4104 (org-autoload
4105 "org-feed"
4106 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4109 ;; Autoload org-indent.el
4111 ;; Define the variable already here, to make sure we have it.
4112 (defvar org-indent-mode nil
4113 "Non-nil if Org-Indent mode is enabled.
4114 Use the command `org-indent-mode' to change this variable.")
4116 (eval-and-compile
4117 (org-autoload
4118 "org-indent"
4119 '(org-indent-mode)))
4121 ;; Autoload org-mobile.el
4123 (eval-and-compile
4124 (org-autoload
4125 "org-mobile"
4126 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4128 ;; Autoload archiving code
4129 ;; The stuff that is needed for cycling and tags has to be defined here.
4131 (defgroup org-archive nil
4132 "Options concerning archiving in Org-mode."
4133 :tag "Org Archive"
4134 :group 'org-structure)
4136 (defcustom org-archive-location "%s_archive::"
4137 "The location where subtrees should be archived.
4139 The value of this variable is a string, consisting of two parts,
4140 separated by a double-colon. The first part is a filename and
4141 the second part is a headline.
4143 When the filename is omitted, archiving happens in the same file.
4144 %s in the filename will be replaced by the current file
4145 name (without the directory part). Archiving to a different file
4146 is useful to keep archived entries from contributing to the
4147 Org-mode Agenda.
4149 The archived entries will be filed as subtrees of the specified
4150 headline. When the headline is omitted, the subtrees are simply
4151 filed away at the end of the file, as top-level entries. Also in
4152 the heading you can use %s to represent the file name, this can be
4153 useful when using the same archive for a number of different files.
4155 Here are a few examples:
4156 \"%s_archive::\"
4157 If the current file is Projects.org, archive in file
4158 Projects.org_archive, as top-level trees. This is the default.
4160 \"::* Archived Tasks\"
4161 Archive in the current file, under the top-level headline
4162 \"* Archived Tasks\".
4164 \"~/org/archive.org::\"
4165 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4167 \"~/org/archive.org::* From %s\"
4168 Archive in file ~/org/archive.org (absolute path), under headlines
4169 \"From FILENAME\" where file name is the current file name.
4171 \"basement::** Finished Tasks\"
4172 Archive in file ./basement (relative path), as level 3 trees
4173 below the level 2 heading \"** Finished Tasks\".
4175 You may set this option on a per-file basis by adding to the buffer a
4176 line like
4178 #+ARCHIVE: basement::** Finished Tasks
4180 You may also define it locally for a subtree by setting an ARCHIVE property
4181 in the entry. If such a property is found in an entry, or anywhere up
4182 the hierarchy, it will be used."
4183 :group 'org-archive
4184 :type 'string)
4186 (defcustom org-archive-tag "ARCHIVE"
4187 "The tag that marks a subtree as archived.
4188 An archived subtree does not open during visibility cycling, and does
4189 not contribute to the agenda listings.
4190 After changing this, font-lock must be restarted in the relevant buffers to
4191 get the proper fontification."
4192 :group 'org-archive
4193 :group 'org-keywords
4194 :type 'string)
4196 (defcustom org-agenda-skip-archived-trees t
4197 "Non-nil means the agenda will skip any items located in archived trees.
4198 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4199 variable is no longer recommended, you should leave it at the value t.
4200 Instead, use the key `v' to cycle the archives-mode in the agenda."
4201 :group 'org-archive
4202 :group 'org-agenda-skip
4203 :type 'boolean)
4205 (defcustom org-columns-skip-archived-trees t
4206 "Non-nil means ignore archived trees when creating column view."
4207 :group 'org-archive
4208 :group 'org-properties
4209 :type 'boolean)
4211 (defcustom org-cycle-open-archived-trees nil
4212 "Non-nil means `org-cycle' will open archived trees.
4213 An archived tree is a tree marked with the tag ARCHIVE.
4214 When nil, archived trees will stay folded. You can still open them with
4215 normal outline commands like `show-all', but not with the cycling commands."
4216 :group 'org-archive
4217 :group 'org-cycle
4218 :type 'boolean)
4220 (defcustom org-sparse-tree-open-archived-trees nil
4221 "Non-nil means sparse tree construction shows matches in archived trees.
4222 When nil, matches in these trees are highlighted, but the trees are kept in
4223 collapsed state."
4224 :group 'org-archive
4225 :group 'org-sparse-trees
4226 :type 'boolean)
4228 (defun org-cycle-hide-archived-subtrees (state)
4229 "Re-hide all archived subtrees after a visibility state change."
4230 (when (and (not org-cycle-open-archived-trees)
4231 (not (memq state '(overview folded))))
4232 (save-excursion
4233 (let* ((globalp (memq state '(contents all)))
4234 (beg (if globalp (point-min) (point)))
4235 (end (if globalp (point-max) (org-end-of-subtree t))))
4236 (org-hide-archived-subtrees beg end)
4237 (goto-char beg)
4238 (if (looking-at (concat ".*:" org-archive-tag ":"))
4239 (message "%s" (substitute-command-keys
4240 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4242 (defun org-force-cycle-archived ()
4243 "Cycle subtree even if it is archived."
4244 (interactive)
4245 (setq this-command 'org-cycle)
4246 (let ((org-cycle-open-archived-trees t))
4247 (call-interactively 'org-cycle)))
4249 (defun org-hide-archived-subtrees (beg end)
4250 "Re-hide all archived subtrees after a visibility state change."
4251 (save-excursion
4252 (let* ((re (concat ":" org-archive-tag ":")))
4253 (goto-char beg)
4254 (while (re-search-forward re end t)
4255 (when (org-at-heading-p)
4256 (org-flag-subtree t)
4257 (org-end-of-subtree t))))))
4259 (defun org-flag-subtree (flag)
4260 (save-excursion
4261 (org-back-to-heading t)
4262 (outline-end-of-heading)
4263 (outline-flag-region (point)
4264 (progn (org-end-of-subtree t) (point))
4265 flag)))
4267 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4269 (eval-and-compile
4270 (org-autoload "org-archive"
4271 '(org-add-archive-files org-archive-subtree
4272 org-archive-to-archive-sibling org-toggle-archive-tag
4273 org-archive-subtree-default
4274 org-archive-subtree-default-with-confirmation)))
4276 ;; Autoload Column View Code
4278 (declare-function org-columns-number-to-string "org-colview")
4279 (declare-function org-columns-get-format-and-top-level "org-colview")
4280 (declare-function org-columns-compute "org-colview")
4282 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4283 '(org-columns-number-to-string org-columns-get-format-and-top-level
4284 org-columns-compute org-agenda-columns org-columns-remove-overlays
4285 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4287 ;; Autoload ID code
4289 (declare-function org-id-store-link "org-id")
4290 (declare-function org-id-locations-load "org-id")
4291 (declare-function org-id-locations-save "org-id")
4292 (defvar org-id-track-globally)
4293 (org-autoload "org-id"
4294 '(org-id-get-create org-id-new org-id-copy org-id-get
4295 org-id-get-with-outline-path-completion
4296 org-id-get-with-outline-drilling org-id-store-link
4297 org-id-goto org-id-find org-id-store-link))
4299 ;; Autoload Plotting Code
4301 (org-autoload "org-plot"
4302 '(org-plot/gnuplot))
4304 ;;; Variables for pre-computed regular expressions, all buffer local
4306 (defvar org-drawer-regexp nil
4307 "Matches first line of a hidden block.")
4308 (make-variable-buffer-local 'org-drawer-regexp)
4309 (defvar org-todo-regexp nil
4310 "Matches any of the TODO state keywords.")
4311 (make-variable-buffer-local 'org-todo-regexp)
4312 (defvar org-not-done-regexp nil
4313 "Matches any of the TODO state keywords except the last one.")
4314 (make-variable-buffer-local 'org-not-done-regexp)
4315 (defvar org-not-done-heading-regexp nil
4316 "Matches a TODO headline that is not done.")
4317 (make-variable-buffer-local 'org-not-done-regexp)
4318 (defvar org-todo-line-regexp nil
4319 "Matches a headline and puts TODO state into group 2 if present.")
4320 (make-variable-buffer-local 'org-todo-line-regexp)
4321 (defvar org-complex-heading-regexp nil
4322 "Matches a headline and puts everything into groups:
4323 group 1: the stars
4324 group 2: The todo keyword, maybe
4325 group 3: Priority cookie
4326 group 4: True headline
4327 group 5: Tags")
4328 (make-variable-buffer-local 'org-complex-heading-regexp)
4329 (defvar org-complex-heading-regexp-format nil
4330 "Printf format to make regexp to match an exact headline.
4331 This regexp will match the headline of any node which has the
4332 exact headline text that is put into the format, but may have any
4333 TODO state, priority and tags.")
4334 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4335 (defvar org-todo-line-tags-regexp nil
4336 "Matches a headline and puts TODO state into group 2 if present.
4337 Also put tags into group 4 if tags are present.")
4338 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4339 (defvar org-ds-keyword-length 12
4340 "Maximum length of the Deadline and SCHEDULED keywords.")
4341 (make-variable-buffer-local 'org-ds-keyword-length)
4342 (defvar org-deadline-regexp nil
4343 "Matches the DEADLINE keyword.")
4344 (make-variable-buffer-local 'org-deadline-regexp)
4345 (defvar org-deadline-time-regexp nil
4346 "Matches the DEADLINE keyword together with a time stamp.")
4347 (make-variable-buffer-local 'org-deadline-time-regexp)
4348 (defvar org-deadline-line-regexp nil
4349 "Matches the DEADLINE keyword and the rest of the line.")
4350 (make-variable-buffer-local 'org-deadline-line-regexp)
4351 (defvar org-scheduled-regexp nil
4352 "Matches the SCHEDULED keyword.")
4353 (make-variable-buffer-local 'org-scheduled-regexp)
4354 (defvar org-scheduled-time-regexp nil
4355 "Matches the SCHEDULED keyword together with a time stamp.")
4356 (make-variable-buffer-local 'org-scheduled-time-regexp)
4357 (defvar org-closed-time-regexp nil
4358 "Matches the CLOSED keyword together with a time stamp.")
4359 (make-variable-buffer-local 'org-closed-time-regexp)
4361 (defvar org-keyword-time-regexp nil
4362 "Matches any of the 4 keywords, together with the time stamp.")
4363 (make-variable-buffer-local 'org-keyword-time-regexp)
4364 (defvar org-keyword-time-not-clock-regexp nil
4365 "Matches any of the 3 keywords, together with the time stamp.")
4366 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4367 (defvar org-maybe-keyword-time-regexp nil
4368 "Matches a timestamp, possibly preceded by a keyword.")
4369 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4370 (defvar org-planning-or-clock-line-re nil
4371 "Matches a line with planning or clock info.")
4372 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4373 (defvar org-all-time-keywords nil
4374 "List of time keywords.")
4375 (make-variable-buffer-local 'org-all-time-keywords)
4377 (defconst org-plain-time-of-day-regexp
4378 (concat
4379 "\\(\\<[012]?[0-9]"
4380 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4381 "\\(--?"
4382 "\\(\\<[012]?[0-9]"
4383 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4384 "\\)?")
4385 "Regular expression to match a plain time or time range.
4386 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4387 groups carry important information:
4388 0 the full match
4389 1 the first time, range or not
4390 8 the second time, if it is a range.")
4392 (defconst org-plain-time-extension-regexp
4393 (concat
4394 "\\(\\<[012]?[0-9]"
4395 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4396 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4397 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4398 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4399 groups carry important information:
4400 0 the full match
4401 7 hours of duration
4402 9 minutes of duration")
4404 (defconst org-stamp-time-of-day-regexp
4405 (concat
4406 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4407 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4408 "\\(--?"
4409 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4410 "Regular expression to match a timestamp time or time range.
4411 After a match, the following groups carry important information:
4412 0 the full match
4413 1 date plus weekday, for back referencing to make sure both times are on the same day
4414 2 the first time, range or not
4415 4 the second time, if it is a range.")
4417 (defconst org-startup-options
4418 '(("fold" org-startup-folded t)
4419 ("overview" org-startup-folded t)
4420 ("nofold" org-startup-folded nil)
4421 ("showall" org-startup-folded nil)
4422 ("showeverything" org-startup-folded showeverything)
4423 ("content" org-startup-folded content)
4424 ("indent" org-startup-indented t)
4425 ("noindent" org-startup-indented nil)
4426 ("hidestars" org-hide-leading-stars t)
4427 ("showstars" org-hide-leading-stars nil)
4428 ("odd" org-odd-levels-only t)
4429 ("oddeven" org-odd-levels-only nil)
4430 ("align" org-startup-align-all-tables t)
4431 ("noalign" org-startup-align-all-tables nil)
4432 ("inlineimages" org-startup-with-inline-images t)
4433 ("noinlineimages" org-startup-with-inline-images nil)
4434 ("customtime" org-display-custom-times t)
4435 ("logdone" org-log-done time)
4436 ("lognotedone" org-log-done note)
4437 ("nologdone" org-log-done nil)
4438 ("lognoteclock-out" org-log-note-clock-out t)
4439 ("nolognoteclock-out" org-log-note-clock-out nil)
4440 ("logrepeat" org-log-repeat state)
4441 ("lognoterepeat" org-log-repeat note)
4442 ("nologrepeat" org-log-repeat nil)
4443 ("logreschedule" org-log-reschedule time)
4444 ("lognotereschedule" org-log-reschedule note)
4445 ("nologreschedule" org-log-reschedule nil)
4446 ("logredeadline" org-log-redeadline time)
4447 ("lognoteredeadline" org-log-redeadline note)
4448 ("nologredeadline" org-log-redeadline nil)
4449 ("logrefile" org-log-refile time)
4450 ("lognoterefile" org-log-refile note)
4451 ("nologrefile" org-log-refile nil)
4452 ("fninline" org-footnote-define-inline t)
4453 ("nofninline" org-footnote-define-inline nil)
4454 ("fnlocal" org-footnote-section nil)
4455 ("fnauto" org-footnote-auto-label t)
4456 ("fnprompt" org-footnote-auto-label nil)
4457 ("fnconfirm" org-footnote-auto-label confirm)
4458 ("fnplain" org-footnote-auto-label plain)
4459 ("fnadjust" org-footnote-auto-adjust t)
4460 ("nofnadjust" org-footnote-auto-adjust nil)
4461 ("constcgs" constants-unit-system cgs)
4462 ("constSI" constants-unit-system SI)
4463 ("noptag" org-tag-persistent-alist nil)
4464 ("hideblocks" org-hide-block-startup t)
4465 ("nohideblocks" org-hide-block-startup nil)
4466 ("beamer" org-startup-with-beamer-mode t)
4467 ("entitiespretty" org-pretty-entities t)
4468 ("entitiesplain" org-pretty-entities nil))
4469 "Variable associated with STARTUP options for org-mode.
4470 Each element is a list of three items: The startup options as written
4471 in the #+STARTUP line, the corresponding variable, and the value to
4472 set this variable to if the option is found. An optional forth element PUSH
4473 means to push this value onto the list in the variable.")
4475 (defun org-update-property-plist (key val props)
4476 "Update PROPS with KEY and VAL."
4477 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4478 (key (if appending (substring key 0 (- (length key) 1)) key))
4479 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4480 (previous (cdr (assoc key props))))
4481 (if appending
4482 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4483 (cons (cons key val) remainder))))
4485 (defconst org-block-regexp
4486 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4487 "Regular expression for hiding blocks.")
4488 (defconst org-heading-keyword-regexp-format
4489 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4490 "Printf format for a regexp matching an headline with some keyword.
4491 This regexp will match the headline of any node which has the
4492 exact keyword that is put into the format. The keyword isn't in
4493 any group by default, but the stars and the body are.")
4494 (defconst org-heading-keyword-maybe-regexp-format
4495 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4496 "Printf format for a regexp matching an headline, possibly with some keyword.
4497 This regexp can match any headline with the specified keyword, or
4498 without a keyword. The keyword isn't in any group by default,
4499 but the stars and the body are.")
4501 (defun org-set-regexps-and-options ()
4502 "Precompute regular expressions for current buffer."
4503 (when (eq major-mode 'org-mode)
4504 (org-set-local 'org-todo-kwd-alist nil)
4505 (org-set-local 'org-todo-key-alist nil)
4506 (org-set-local 'org-todo-key-trigger nil)
4507 (org-set-local 'org-todo-keywords-1 nil)
4508 (org-set-local 'org-done-keywords nil)
4509 (org-set-local 'org-todo-heads nil)
4510 (org-set-local 'org-todo-sets nil)
4511 (org-set-local 'org-todo-log-states nil)
4512 (org-set-local 'org-file-properties nil)
4513 (org-set-local 'org-file-tags nil)
4514 (let ((re (org-make-options-regexp
4515 '("CATEGORY" "TODO" "COLUMNS"
4516 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4517 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4518 "OPTIONS")
4519 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4520 (splitre "[ \t]+")
4521 (scripts org-use-sub-superscripts)
4522 kwds kws0 kwsa key log value cat arch tags const links hw dws
4523 tail sep kws1 prio props ftags drawers beamer-p
4524 ext-setup-or-nil setup-contents (start 0))
4525 (save-excursion
4526 (save-restriction
4527 (widen)
4528 (goto-char (point-min))
4529 (while (or (and ext-setup-or-nil
4530 (string-match re ext-setup-or-nil start)
4531 (setq start (match-end 0)))
4532 (and (setq ext-setup-or-nil nil start 0)
4533 (re-search-forward re nil t)))
4534 (setq key (upcase (match-string 1 ext-setup-or-nil))
4535 value (org-match-string-no-properties 2 ext-setup-or-nil))
4536 (if (stringp value) (setq value (org-trim value)))
4537 (cond
4538 ((equal key "CATEGORY")
4539 (setq cat value))
4540 ((member key '("SEQ_TODO" "TODO"))
4541 (push (cons 'sequence (org-split-string value splitre)) kwds))
4542 ((equal key "TYP_TODO")
4543 (push (cons 'type (org-split-string value splitre)) kwds))
4544 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4545 ;; general TODO-like setup
4546 (push (cons (intern (downcase (match-string 1 key)))
4547 (org-split-string value splitre)) kwds))
4548 ((equal key "TAGS")
4549 (setq tags (append tags (if tags '("\\n") nil)
4550 (org-split-string value splitre))))
4551 ((equal key "COLUMNS")
4552 (org-set-local 'org-columns-default-format value))
4553 ((equal key "LINK")
4554 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4555 (push (cons (match-string 1 value)
4556 (org-trim (match-string 2 value)))
4557 links)))
4558 ((equal key "PRIORITIES")
4559 (setq prio (org-split-string value " +")))
4560 ((equal key "PROPERTY")
4561 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4562 (setq props (org-update-property-plist (match-string 1 value)
4563 (match-string 2 value)
4564 props))))
4565 ((equal key "FILETAGS")
4566 (when (string-match "\\S-" value)
4567 (setq ftags
4568 (append
4569 ftags
4570 (apply 'append
4571 (mapcar (lambda (x) (org-split-string x ":"))
4572 (org-split-string value)))))))
4573 ((equal key "DRAWERS")
4574 (setq drawers (org-split-string value splitre)))
4575 ((equal key "CONSTANTS")
4576 (setq const (append const (org-split-string value splitre))))
4577 ((equal key "STARTUP")
4578 (let ((opts (org-split-string value splitre))
4579 l var val)
4580 (while (setq l (pop opts))
4581 (when (setq l (assoc l org-startup-options))
4582 (setq var (nth 1 l) val (nth 2 l))
4583 (if (not (nth 3 l))
4584 (set (make-local-variable var) val)
4585 (if (not (listp (symbol-value var)))
4586 (set (make-local-variable var) nil))
4587 (set (make-local-variable var) (symbol-value var))
4588 (add-to-list var val))))))
4589 ((equal key "ARCHIVE")
4590 (setq arch value)
4591 (remove-text-properties 0 (length arch)
4592 '(face t fontified t) arch))
4593 ((equal key "LATEX_CLASS")
4594 (setq beamer-p (equal value "beamer")))
4595 ((equal key "OPTIONS")
4596 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4597 (setq scripts (read (match-string 2 value)))))
4598 ((equal key "SETUPFILE")
4599 (setq setup-contents (org-file-contents
4600 (expand-file-name
4601 (org-remove-double-quotes value))
4602 'noerror))
4603 (if (not ext-setup-or-nil)
4604 (setq ext-setup-or-nil setup-contents start 0)
4605 (setq ext-setup-or-nil
4606 (concat (substring ext-setup-or-nil 0 start)
4607 "\n" setup-contents "\n"
4608 (substring ext-setup-or-nil start)))))))
4609 ;; search for property blocks
4610 (goto-char (point-min))
4611 (while (re-search-forward org-block-regexp nil t)
4612 (when (equal "PROPERTY" (upcase (match-string 1)))
4613 (setq value (replace-regexp-in-string
4614 "[\n\r]" " " (match-string 4)))
4615 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4616 (setq props (org-update-property-plist (match-string 1 value)
4617 (match-string 2 value)
4618 props)))))))
4619 (org-set-local 'org-use-sub-superscripts scripts)
4620 (when cat
4621 (org-set-local 'org-category (intern cat))
4622 (push (cons "CATEGORY" cat) props))
4623 (when prio
4624 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4625 (setq prio (mapcar 'string-to-char prio))
4626 (org-set-local 'org-highest-priority (nth 0 prio))
4627 (org-set-local 'org-lowest-priority (nth 1 prio))
4628 (org-set-local 'org-default-priority (nth 2 prio)))
4629 (and props (org-set-local 'org-file-properties (nreverse props)))
4630 (and ftags (org-set-local 'org-file-tags
4631 (mapcar 'org-add-prop-inherited ftags)))
4632 (and drawers (org-set-local 'org-drawers drawers))
4633 (and arch (org-set-local 'org-archive-location arch))
4634 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4635 ;; Process the TODO keywords
4636 (unless kwds
4637 ;; Use the global values as if they had been given locally.
4638 (setq kwds (default-value 'org-todo-keywords))
4639 (if (stringp (car kwds))
4640 (setq kwds (list (cons org-todo-interpretation
4641 (default-value 'org-todo-keywords)))))
4642 (setq kwds (reverse kwds)))
4643 (setq kwds (nreverse kwds))
4644 (let (inter kws kw)
4645 (while (setq kws (pop kwds))
4646 (let ((kws (or
4647 (run-hook-with-args-until-success
4648 'org-todo-setup-filter-hook kws)
4649 kws)))
4650 (setq inter (pop kws) sep (member "|" kws)
4651 kws0 (delete "|" (copy-sequence kws))
4652 kwsa nil
4653 kws1 (mapcar
4654 (lambda (x)
4655 ;; 1 2
4656 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4657 (progn
4658 (setq kw (match-string 1 x)
4659 key (and (match-end 2) (match-string 2 x))
4660 log (org-extract-log-state-settings x))
4661 (push (cons kw (and key (string-to-char key))) kwsa)
4662 (and log (push log org-todo-log-states))
4664 (error "Invalid TODO keyword %s" x)))
4665 kws0)
4666 kwsa (if kwsa (append '((:startgroup))
4667 (nreverse kwsa)
4668 '((:endgroup))))
4669 hw (car kws1)
4670 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4671 tail (list inter hw (car dws) (org-last dws))))
4672 (add-to-list 'org-todo-heads hw 'append)
4673 (push kws1 org-todo-sets)
4674 (setq org-done-keywords (append org-done-keywords dws nil))
4675 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4676 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4677 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4678 (setq org-todo-sets (nreverse org-todo-sets)
4679 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4680 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4681 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4682 ;; Process the constants
4683 (when const
4684 (let (e cst)
4685 (while (setq e (pop const))
4686 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4687 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4688 (setq org-table-formula-constants-local cst)))
4690 ;; Process the tags.
4691 (when tags
4692 (let (e tgs)
4693 (while (setq e (pop tags))
4694 (cond
4695 ((equal e "{") (push '(:startgroup) tgs))
4696 ((equal e "}") (push '(:endgroup) tgs))
4697 ((equal e "\\n") (push '(:newline) tgs))
4698 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4699 (push (cons (match-string 1 e)
4700 (string-to-char (match-string 2 e)))
4701 tgs))
4702 (t (push (list e) tgs))))
4703 (org-set-local 'org-tag-alist nil)
4704 (while (setq e (pop tgs))
4705 (or (and (stringp (car e))
4706 (assoc (car e) org-tag-alist))
4707 (push e org-tag-alist)))))
4709 ;; Compute the regular expressions and other local variables.
4710 ;; Using `org-outline-regexp-bol' would complicate them much,
4711 ;; because of the fixed white space at the end of that string.
4712 (if (not org-done-keywords)
4713 (setq org-done-keywords (and org-todo-keywords-1
4714 (list (org-last org-todo-keywords-1)))))
4715 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4716 (length org-scheduled-string)
4717 (length org-clock-string)
4718 (length org-closed-string)))
4719 org-drawer-regexp
4720 (concat "^[ \t]*:\\("
4721 (mapconcat 'regexp-quote org-drawers "\\|")
4722 "\\):[ \t]*$")
4723 org-not-done-keywords
4724 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4725 org-todo-regexp
4726 (concat "\\("
4727 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4728 "\\)")
4729 org-not-done-regexp
4730 (concat "\\("
4731 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4732 "\\)")
4733 org-not-done-heading-regexp
4734 (format org-heading-keyword-regexp-format org-not-done-regexp)
4735 org-todo-line-regexp
4736 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4737 org-complex-heading-regexp
4738 (concat "^\\(\\*+\\)"
4739 "\\(?: +" org-todo-regexp "\\)?"
4740 "\\(?: +\\(\\[#.\\]\\)\\)?"
4741 "\\(?: +\\(.*?\\)\\)?"
4742 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4743 "[ \t]*$")
4744 org-complex-heading-regexp-format
4745 (concat "^\\(\\*+\\)"
4746 "\\(?: +" org-todo-regexp "\\)?"
4747 "\\(?: +\\(\\[#.\\]\\)\\)?"
4748 "\\(?: +"
4749 ;; Stats cookies can be stuck to body.
4750 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4751 "\\(%s\\)"
4752 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4753 "\\)"
4754 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4755 "[ \t]*$")
4756 org-todo-line-tags-regexp
4757 (concat "^\\(\\*+\\)"
4758 "\\(?: +" org-todo-regexp "\\)?"
4759 "\\(?: +\\(.*?\\)\\)?"
4760 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4761 "[ \t]*$")
4762 org-deadline-regexp (concat "\\<" org-deadline-string)
4763 org-deadline-time-regexp
4764 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4765 org-deadline-line-regexp
4766 (concat "\\<\\(" org-deadline-string "\\).*")
4767 org-scheduled-regexp
4768 (concat "\\<" org-scheduled-string)
4769 org-scheduled-time-regexp
4770 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4771 org-closed-time-regexp
4772 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4773 org-keyword-time-regexp
4774 (concat "\\<\\(" org-scheduled-string
4775 "\\|" org-deadline-string
4776 "\\|" org-closed-string
4777 "\\|" org-clock-string "\\)"
4778 " *[[<]\\([^]>]+\\)[]>]")
4779 org-keyword-time-not-clock-regexp
4780 (concat "\\<\\(" org-scheduled-string
4781 "\\|" org-deadline-string
4782 "\\|" org-closed-string
4783 "\\)"
4784 " *[[<]\\([^]>]+\\)[]>]")
4785 org-maybe-keyword-time-regexp
4786 (concat "\\(\\<\\(" org-scheduled-string
4787 "\\|" org-deadline-string
4788 "\\|" org-closed-string
4789 "\\|" org-clock-string "\\)\\)?"
4790 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4791 org-planning-or-clock-line-re
4792 (concat "^[ \t]*\\("
4793 org-scheduled-string "\\|"
4794 org-deadline-string "\\|"
4795 org-closed-string "\\|"
4796 org-clock-string "\\)")
4797 org-all-time-keywords
4798 (mapcar (lambda (w) (substring w 0 -1))
4799 (list org-scheduled-string org-deadline-string
4800 org-clock-string org-closed-string))
4802 (org-compute-latex-and-specials-regexp)
4803 (org-set-font-lock-defaults))))
4805 (defun org-file-contents (file &optional noerror)
4806 "Return the contents of FILE, as a string."
4807 (if (or (not file)
4808 (not (file-readable-p file)))
4809 (if noerror
4810 (progn
4811 (message "Cannot read file \"%s\"" file)
4812 (ding) (sit-for 2)
4814 (error "Cannot read file \"%s\"" file))
4815 (with-temp-buffer
4816 (insert-file-contents file)
4817 (buffer-string))))
4819 (defun org-extract-log-state-settings (x)
4820 "Extract the log state setting from a TODO keyword string.
4821 This will extract info from a string like \"WAIT(w@/!)\"."
4822 (let (kw key log1 log2)
4823 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4824 (setq kw (match-string 1 x)
4825 key (and (match-end 2) (match-string 2 x))
4826 log1 (and (match-end 3) (match-string 3 x))
4827 log2 (and (match-end 4) (match-string 4 x)))
4828 (and (or log1 log2)
4829 (list kw
4830 (and log1 (if (equal log1 "!") 'time 'note))
4831 (and log2 (if (equal log2 "!") 'time 'note)))))))
4833 (defun org-remove-keyword-keys (list)
4834 "Remove a pair of parenthesis at the end of each string in LIST."
4835 (mapcar (lambda (x)
4836 (if (string-match "(.*)$" x)
4837 (substring x 0 (match-beginning 0))
4839 list))
4841 (defun org-assign-fast-keys (alist)
4842 "Assign fast keys to a keyword-key alist.
4843 Respect keys that are already there."
4844 (let (new e (alt ?0))
4845 (while (setq e (pop alist))
4846 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4847 (cdr e)) ;; Key already assigned.
4848 (push e new)
4849 (let ((clist (string-to-list (downcase (car e))))
4850 (used (append new alist)))
4851 (when (= (car clist) ?@)
4852 (pop clist))
4853 (while (and clist (rassoc (car clist) used))
4854 (pop clist))
4855 (unless clist
4856 (while (rassoc alt used)
4857 (incf alt)))
4858 (push (cons (car e) (or (car clist) alt)) new))))
4859 (nreverse new)))
4861 ;;; Some variables used in various places
4863 (defvar org-window-configuration nil
4864 "Used in various places to store a window configuration.")
4865 (defvar org-selected-window nil
4866 "Used in various places to store a window configuration.")
4867 (defvar org-finish-function nil
4868 "Function to be called when `C-c C-c' is used.
4869 This is for getting out of special buffers like remember.")
4872 ;; FIXME: Occasionally check by commenting these, to make sure
4873 ;; no other functions uses these, forgetting to let-bind them.
4874 (defvar entry)
4875 (defvar org-last-state)
4876 (defvar date)
4878 ;; Defined somewhere in this file, but used before definition.
4879 (defvar org-entities) ;; defined in org-entities.el
4880 (defvar org-struct-menu)
4881 (defvar org-org-menu)
4882 (defvar org-tbl-menu)
4884 ;;;; Define the Org-mode
4886 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4887 (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"))
4890 ;; We use a before-change function to check if a table might need
4891 ;; an update.
4892 (defvar org-table-may-need-update t
4893 "Indicates that a table might need an update.
4894 This variable is set by `org-before-change-function'.
4895 `org-table-align' sets it back to nil.")
4896 (defun org-before-change-function (beg end)
4897 "Every change indicates that a table might need an update."
4898 (setq org-table-may-need-update t))
4899 (defvar org-mode-map)
4900 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4901 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4902 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4903 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4904 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4905 (defvar org-table-buffer-is-an nil)
4907 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4908 ;; some places -- e.g. see the macro org-with-limited-levels.
4910 ;; In Org buffers, the value of `outline-regexp' is that of
4911 ;; `org-outline-regexp'. The only function still directly relying on
4912 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4913 ;; job when `orgstruct-mode' is active.
4914 (defvar org-outline-regexp "\\*+ "
4915 "Regexp to match Org headlines.")
4916 (defconst org-outline-regexp-bol "^\\*+ "
4917 "Regexp to match Org headlines.
4918 This is similar to `org-outline-regexp' but additionally makes
4919 sure that we are at the beginning of the line.")
4921 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4922 "Matches an headline, putting stars and text into groups.
4923 Stars are put in group 1 and the trimmed body in group 2.")
4925 (defvar buffer-face-mode-face)
4927 ;;;###autoload
4928 (define-derived-mode org-mode outline-mode "Org"
4929 "Outline-based notes management and organizer, alias
4930 \"Carsten's outline-mode for keeping track of everything.\"
4932 Org-mode develops organizational tasks around a NOTES file which
4933 contains information about projects as plain text. Org-mode is
4934 implemented on top of outline-mode, which is ideal to keep the content
4935 of large files well structured. It supports ToDo items, deadlines and
4936 time stamps, which magically appear in the diary listing of the Emacs
4937 calendar. Tables are easily created with a built-in table editor.
4938 Plain text URL-like links connect to websites, emails (VM), Usenet
4939 messages (Gnus), BBDB entries, and any files related to the project.
4940 For printing and sharing of notes, an Org-mode file (or a part of it)
4941 can be exported as a structured ASCII or HTML file.
4943 The following commands are available:
4945 \\{org-mode-map}"
4947 ;; Get rid of Outline menus, they are not needed
4948 ;; Need to do this here because define-derived-mode sets up
4949 ;; the keymap so late. Still, it is a waste to call this each time
4950 ;; we switch another buffer into org-mode.
4951 (if (featurep 'xemacs)
4952 (when (boundp 'outline-mode-menu-heading)
4953 ;; Assume this is Greg's port, it uses easymenu
4954 (easy-menu-remove outline-mode-menu-heading)
4955 (easy-menu-remove outline-mode-menu-show)
4956 (easy-menu-remove outline-mode-menu-hide))
4957 (define-key org-mode-map [menu-bar headings] 'undefined)
4958 (define-key org-mode-map [menu-bar hide] 'undefined)
4959 (define-key org-mode-map [menu-bar show] 'undefined))
4961 (org-load-modules-maybe)
4962 (easy-menu-add org-org-menu)
4963 (easy-menu-add org-tbl-menu)
4964 (org-install-agenda-files-menu)
4965 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4966 (add-to-invisibility-spec '(org-cwidth))
4967 (add-to-invisibility-spec '(org-hide-block . t))
4968 (when (featurep 'xemacs)
4969 (org-set-local 'line-move-ignore-invisible t))
4970 (org-set-local 'outline-regexp org-outline-regexp)
4971 (org-set-local 'outline-level 'org-outline-level)
4972 (setq bidi-paragraph-direction 'left-to-right)
4973 (when (and org-ellipsis
4974 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4975 (fboundp 'make-glyph-code))
4976 (unless org-display-table
4977 (setq org-display-table (make-display-table)))
4978 (set-display-table-slot
4979 org-display-table 4
4980 (vconcat (mapcar
4981 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4982 org-ellipsis)))
4983 (if (stringp org-ellipsis) org-ellipsis "..."))))
4984 (setq buffer-display-table org-display-table))
4985 (org-set-regexps-and-options)
4986 (when (and org-tag-faces (not org-tags-special-faces-re))
4987 ;; tag faces set outside customize.... force initialization.
4988 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4989 ;; Calc embedded
4990 (org-set-local 'calc-embedded-open-mode "# ")
4991 (modify-syntax-entry ?@ "w")
4992 (if org-startup-truncated (setq truncate-lines t))
4993 (org-set-local 'font-lock-unfontify-region-function
4994 'org-unfontify-region)
4995 ;; Activate before-change-function
4996 (org-set-local 'org-table-may-need-update t)
4997 (org-add-hook 'before-change-functions 'org-before-change-function nil
4998 'local)
4999 ;; Check for running clock before killing a buffer
5000 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5001 ;; Paragraphs and auto-filling
5002 (org-set-autofill-regexps)
5003 (setq indent-line-function 'org-indent-line-function)
5004 (org-update-radio-target-regexp)
5005 ;; Beginning/end of defun
5006 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5007 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5008 ;; Next error for sparse trees
5009 (org-set-local 'next-error-function 'org-occur-next-match)
5010 ;; Make sure dependence stuff works reliably, even for users who set it
5011 ;; too late :-(
5012 (if org-enforce-todo-dependencies
5013 (add-hook 'org-blocker-hook
5014 'org-block-todo-from-children-or-siblings-or-parent)
5015 (remove-hook 'org-blocker-hook
5016 'org-block-todo-from-children-or-siblings-or-parent))
5017 (if org-enforce-todo-checkbox-dependencies
5018 (add-hook 'org-blocker-hook
5019 'org-block-todo-from-checkboxes)
5020 (remove-hook 'org-blocker-hook
5021 'org-block-todo-from-checkboxes))
5023 ;; Comment characters
5024 (org-set-local 'comment-start "#")
5025 (org-set-local 'comment-padding " ")
5027 ;; Align options lines
5028 (org-set-local
5029 'align-mode-rules-list
5030 '((org-in-buffer-settings
5031 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5032 (modes . '(org-mode)))))
5034 ;; Imenu
5035 (org-set-local 'imenu-create-index-function
5036 'org-imenu-get-tree)
5038 ;; Make isearch reveal context
5039 (if (or (featurep 'xemacs)
5040 (not (boundp 'outline-isearch-open-invisible-function)))
5041 ;; Emacs 21 and XEmacs make use of the hook
5042 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5043 ;; Emacs 22 deals with this through a special variable
5044 (org-set-local 'outline-isearch-open-invisible-function
5045 (lambda (&rest ignore) (org-show-context 'isearch))))
5047 ;; Turn on org-beamer-mode?
5048 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5050 ;; Setup the pcomplete hooks
5051 (set (make-local-variable 'pcomplete-command-completion-function)
5052 'org-pcomplete-initial)
5053 (set (make-local-variable 'pcomplete-command-name-function)
5054 'org-command-at-point)
5055 (set (make-local-variable 'pcomplete-default-completion-function)
5056 'ignore)
5057 (set (make-local-variable 'pcomplete-parse-arguments-function)
5058 'org-parse-arguments)
5059 (set (make-local-variable 'pcomplete-termination-string) "")
5060 (when (>= emacs-major-version 23)
5061 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5063 ;; If empty file that did not turn on org-mode automatically, make it to.
5064 (if (and org-insert-mode-line-in-empty-file
5065 (org-called-interactively-p 'any)
5066 (= (point-min) (point-max)))
5067 (insert "# -*- mode: org -*-\n\n"))
5068 (unless org-inhibit-startup
5069 (when org-startup-align-all-tables
5070 (let ((bmp (buffer-modified-p)))
5071 (org-table-map-tables 'org-table-align 'quietly)
5072 (set-buffer-modified-p bmp)))
5073 (when org-startup-with-inline-images
5074 (org-display-inline-images))
5075 (when org-startup-indented
5076 (require 'org-indent)
5077 (org-indent-mode 1))
5078 (unless org-inhibit-startup-visibility-stuff
5079 (org-set-startup-visibility))))
5081 (when (fboundp 'abbrev-table-put)
5082 (abbrev-table-put org-mode-abbrev-table
5083 :parents (list text-mode-abbrev-table)))
5085 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5087 (defun org-current-time ()
5088 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5089 (if (> (car org-time-stamp-rounding-minutes) 1)
5090 (let ((r (car org-time-stamp-rounding-minutes))
5091 (time (decode-time)))
5092 (apply 'encode-time
5093 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5094 (nthcdr 2 time))))
5095 (current-time)))
5097 (defun org-today ()
5098 "Return today date, considering `org-extend-today-until'."
5099 (time-to-days
5100 (time-subtract (current-time)
5101 (list 0 (* 3600 org-extend-today-until) 0))))
5103 ;;;; Font-Lock stuff, including the activators
5105 (defvar org-mouse-map (make-sparse-keymap))
5106 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5107 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5108 (when org-mouse-1-follows-link
5109 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5110 (when org-tab-follows-link
5111 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5112 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5114 (require 'font-lock)
5116 (defconst org-non-link-chars "]\t\n\r<>")
5117 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5118 "shell" "elisp" "doi" "message"))
5119 (defvar org-link-types-re nil
5120 "Matches a link that has a url-like prefix like \"http:\"")
5121 (defvar org-link-re-with-space nil
5122 "Matches a link with spaces, optional angular brackets around it.")
5123 (defvar org-link-re-with-space2 nil
5124 "Matches a link with spaces, optional angular brackets around it.")
5125 (defvar org-link-re-with-space3 nil
5126 "Matches a link with spaces, only for internal part in bracket links.")
5127 (defvar org-angle-link-re nil
5128 "Matches link with angular brackets, spaces are allowed.")
5129 (defvar org-plain-link-re nil
5130 "Matches plain link, without spaces.")
5131 (defvar org-bracket-link-regexp nil
5132 "Matches a link in double brackets.")
5133 (defvar org-bracket-link-analytic-regexp nil
5134 "Regular expression used to analyze links.
5135 Here is what the match groups contain after a match:
5136 1: http:
5137 2: http
5138 3: path
5139 4: [desc]
5140 5: desc")
5141 (defvar org-bracket-link-analytic-regexp++ nil
5142 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5143 (defvar org-any-link-re nil
5144 "Regular expression matching any link.")
5146 (defcustom org-match-sexp-depth 3
5147 "Number of stacked braces for sub/superscript matching.
5148 This has to be set before loading org.el to be effective."
5149 :group 'org-export-translation ; ??????????????????????????/
5150 :type 'integer)
5152 (defun org-create-multibrace-regexp (left right n)
5153 "Create a regular expression which will match a balanced sexp.
5154 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5155 as single character strings.
5156 The regexp returned will match the entire expression including the
5157 delimiters. It will also define a single group which contains the
5158 match except for the outermost delimiters. The maximum depth of
5159 stacked delimiters is N. Escaping delimiters is not possible."
5160 (let* ((nothing (concat "[^" left right "]*?"))
5161 (or "\\|")
5162 (re nothing)
5163 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5164 (while (> n 1)
5165 (setq n (1- n)
5166 re (concat re or next)
5167 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5168 (concat left "\\(" re "\\)" right)))
5170 (defvar org-match-substring-regexp
5171 (concat
5172 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5173 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5174 "\\|"
5175 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5176 "\\|"
5177 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5178 "The regular expression matching a sub- or superscript.")
5180 (defvar org-match-substring-with-braces-regexp
5181 (concat
5182 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5183 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5184 "\\)")
5185 "The regular expression matching a sub- or superscript, forcing braces.")
5187 (defun org-make-link-regexps ()
5188 "Update the link regular expressions.
5189 This should be called after the variable `org-link-types' has changed."
5190 (setq org-link-types-re
5191 (concat
5192 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5193 org-link-re-with-space
5194 (concat
5195 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5196 "\\([^" org-non-link-chars " ]"
5197 "[^" org-non-link-chars "]*"
5198 "[^" org-non-link-chars " ]\\)>?")
5199 org-link-re-with-space2
5200 (concat
5201 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5202 "\\([^" org-non-link-chars " ]"
5203 "[^\t\n\r]*"
5204 "[^" org-non-link-chars " ]\\)>?")
5205 org-link-re-with-space3
5206 (concat
5207 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5208 "\\([^" org-non-link-chars " ]"
5209 "[^\t\n\r]*\\)")
5210 org-angle-link-re
5211 (concat
5212 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^" org-non-link-chars "]*"
5215 "\\)>")
5216 org-plain-link-re
5217 (concat
5218 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5219 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5220 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5221 org-bracket-link-regexp
5222 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5223 org-bracket-link-analytic-regexp
5224 (concat
5225 "\\[\\["
5226 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5227 "\\([^]]+\\)"
5228 "\\]"
5229 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5230 "\\]")
5231 org-bracket-link-analytic-regexp++
5232 (concat
5233 "\\[\\["
5234 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5235 "\\([^]]+\\)"
5236 "\\]"
5237 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5238 "\\]")
5239 org-any-link-re
5240 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5241 org-angle-link-re "\\)\\|\\("
5242 org-plain-link-re "\\)")))
5244 (org-make-link-regexps)
5246 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5247 "Regular expression for fast time stamp matching.")
5248 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5249 "Regular expression for fast time stamp matching.")
5250 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5251 "Regular expression matching time strings for analysis.
5252 This one does not require the space after the date, so it can be used
5253 on a string that terminates immediately after the date.")
5254 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5255 "Regular expression matching time strings for analysis.")
5256 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5257 "Regular expression matching time stamps, with groups.")
5258 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5259 "Regular expression matching time stamps (also [..]), with groups.")
5260 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5261 "Regular expression matching a time stamp range.")
5262 (defconst org-tr-regexp-both
5263 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5264 "Regular expression matching a time stamp range.")
5265 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5266 org-ts-regexp "\\)?")
5267 "Regular expression matching a time stamp or time stamp range.")
5268 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5269 org-ts-regexp-both "\\)?")
5270 "Regular expression matching a time stamp or time stamp range.
5271 The time stamps may be either active or inactive.")
5273 (defvar org-emph-face nil)
5275 (defun org-do-emphasis-faces (limit)
5276 "Run through the buffer and add overlays to emphasized strings."
5277 (let (rtn a)
5278 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5279 (if (not (= (char-after (match-beginning 3))
5280 (char-after (match-beginning 4))))
5281 (progn
5282 (setq rtn t)
5283 (setq a (assoc (match-string 3) org-emphasis-alist))
5284 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5285 'face
5286 (nth 1 a))
5287 (and (nth 4 a)
5288 (org-remove-flyspell-overlays-in
5289 (match-beginning 0) (match-end 0)))
5290 (add-text-properties (match-beginning 2) (match-end 2)
5291 '(font-lock-multiline t org-emphasis t))
5292 (when org-hide-emphasis-markers
5293 (add-text-properties (match-end 4) (match-beginning 5)
5294 '(invisible org-link))
5295 (add-text-properties (match-beginning 3) (match-end 3)
5296 '(invisible org-link)))))
5297 (backward-char 1))
5298 rtn))
5300 (defun org-emphasize (&optional char)
5301 "Insert or change an emphasis, i.e. a font like bold or italic.
5302 If there is an active region, change that region to a new emphasis.
5303 If there is no region, just insert the marker characters and position
5304 the cursor between them.
5305 CHAR should be either the marker character, or the first character of the
5306 HTML tag associated with that emphasis. If CHAR is a space, the means
5307 to remove the emphasis of the selected region.
5308 If char is not given (for example in an interactive call) it
5309 will be prompted for."
5310 (interactive)
5311 (let ((eal org-emphasis-alist) e det
5312 (erc org-emphasis-regexp-components)
5313 (prompt "")
5314 (string "") beg end move tag c s)
5315 (if (org-region-active-p)
5316 (setq beg (region-beginning) end (region-end)
5317 string (buffer-substring beg end))
5318 (setq move t))
5320 (while (setq e (pop eal))
5321 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5322 c (aref tag 0))
5323 (push (cons c (string-to-char (car e))) det)
5324 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5325 (substring tag 1)))))
5326 (setq det (nreverse det))
5327 (unless char
5328 (message "%s" (concat "Emphasis marker or tag:" prompt))
5329 (setq char (read-char-exclusive)))
5330 (setq char (or (cdr (assoc char det)) char))
5331 (if (equal char ?\ )
5332 (setq s "" move nil)
5333 (unless (assoc (char-to-string char) org-emphasis-alist)
5334 (error "No such emphasis marker: \"%c\"" char))
5335 (setq s (char-to-string char)))
5336 (while (and (> (length string) 1)
5337 (equal (substring string 0 1) (substring string -1))
5338 (assoc (substring string 0 1) org-emphasis-alist))
5339 (setq string (substring string 1 -1)))
5340 (setq string (concat s string s))
5341 (if beg (delete-region beg end))
5342 (unless (or (bolp)
5343 (string-match (concat "[" (nth 0 erc) "\n]")
5344 (char-to-string (char-before (point)))))
5345 (insert " "))
5346 (unless (or (eobp)
5347 (string-match (concat "[" (nth 1 erc) "\n]")
5348 (char-to-string (char-after (point)))))
5349 (insert " ") (backward-char 1))
5350 (insert string)
5351 (and move (backward-char 1))))
5353 (defconst org-nonsticky-props
5354 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5356 (defsubst org-rear-nonsticky-at (pos)
5357 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5359 (defun org-activate-plain-links (limit)
5360 "Run through the buffer and add overlays to links."
5361 (catch 'exit
5362 (let (f)
5363 (if (re-search-forward org-plain-link-re limit t)
5364 (progn
5365 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5366 (setq f (get-text-property (match-beginning 0) 'face))
5367 (if (or (eq f 'org-tag)
5368 (and (listp f) (memq 'org-tag f)))
5370 (add-text-properties (match-beginning 0) (match-end 0)
5371 (list 'mouse-face 'highlight
5372 'face 'org-link
5373 'keymap org-mouse-map))
5374 (org-rear-nonsticky-at (match-end 0)))
5375 t)))))
5377 (defun org-activate-code (limit)
5378 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5379 (progn
5380 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5381 (remove-text-properties (match-beginning 0) (match-end 0)
5382 '(display t invisible t intangible t))
5383 t)))
5385 (defcustom org-src-fontify-natively nil
5386 "When non-nil, fontify code in code blocks."
5387 :type 'boolean
5388 :version "24.1"
5389 :group 'org-appearance
5390 :group 'org-babel)
5392 (defun org-fontify-meta-lines-and-blocks (limit)
5393 (condition-case nil
5394 (org-fontify-meta-lines-and-blocks-1 limit)
5395 (error (message "org-mode fontification error"))))
5397 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5398 "Fontify #+ lines and blocks, in the correct ways."
5399 (let ((case-fold-search t))
5400 (if (re-search-forward
5401 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5402 limit t)
5403 (let ((beg (match-beginning 0))
5404 (block-start (match-end 0))
5405 (block-end nil)
5406 (lang (match-string 7))
5407 (beg1 (line-beginning-position 2))
5408 (dc1 (downcase (match-string 2)))
5409 (dc3 (downcase (match-string 3)))
5410 end end1 quoting block-type ovl)
5411 (cond
5412 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5413 ;; a single line of backend-specific content
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 (add-text-properties (match-beginning 1) (match-end 3)
5418 '(font-lock-fontified t face org-meta-line))
5419 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5420 '(font-lock-fontified t face org-block))
5421 ; for backend-specific code
5423 ((and (match-end 4) (equal dc3 "begin"))
5424 ;; Truly a block
5425 (setq block-type (downcase (match-string 5))
5426 quoting (member block-type org-protecting-blocks))
5427 (when (re-search-forward
5428 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5429 nil t) ;; on purpose, we look further than LIMIT
5430 (setq end (min (point-max) (match-end 0))
5431 end1 (min (point-max) (1- (match-beginning 0))))
5432 (setq block-end (match-beginning 0))
5433 (when quoting
5434 (remove-text-properties beg end
5435 '(display t invisible t intangible t)))
5436 (add-text-properties
5437 beg end
5438 '(font-lock-fontified t font-lock-multiline t))
5439 (add-text-properties beg beg1 '(face org-meta-line))
5440 (add-text-properties end1 (min (point-max) (1+ end))
5441 '(face org-meta-line)) ; for end_src
5442 (cond
5443 ((and lang (not (string= lang "")) org-src-fontify-natively)
5444 (org-src-font-lock-fontify-block lang block-start block-end)
5445 ;; remove old background overlays
5446 (mapc (lambda (ov)
5447 (if (eq (overlay-get ov 'face) 'org-block-background)
5448 (delete-overlay ov)))
5449 (overlays-at (/ (+ beg1 block-end) 2)))
5450 ;; add a background overlay
5451 (setq ovl (make-overlay beg1 block-end))
5452 (overlay-put ovl 'face 'org-block-background)
5453 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5454 (quoting
5455 (add-text-properties beg1 (min (point-max) (1+ end1))
5456 '(face org-block))) ; end of source block
5457 ((not org-fontify-quote-and-verse-blocks))
5458 ((string= block-type "quote")
5459 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5460 ((string= block-type "verse")
5461 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5462 (add-text-properties beg beg1 '(face org-block-begin-line))
5463 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5464 '(face org-block-end-line))
5466 ((member dc1 '("title:" "author:" "email:" "date:"))
5467 (add-text-properties
5468 beg (match-end 3)
5469 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5470 '(font-lock-fontified t invisible t)
5471 '(font-lock-fontified t face org-document-info-keyword)))
5472 (add-text-properties
5473 (match-beginning 6) (match-end 6)
5474 (if (string-equal dc1 "title:")
5475 '(font-lock-fontified t face org-document-title)
5476 '(font-lock-fontified t face org-document-info))))
5477 ((not (member (char-after beg) '(?\ ?\t)))
5478 ;; just any other in-buffer setting, but not indented
5479 (add-text-properties
5480 beg (match-end 0)
5481 '(font-lock-fontified t face org-meta-line))
5483 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5484 "orgtbl:" "tblfm:" "tblname:" "results:"
5485 "call:" "header:" "headers:" "name:"))
5486 (and (match-end 4) (equal dc3 "attr")))
5487 (add-text-properties
5488 beg (match-end 0)
5489 '(font-lock-fontified t face org-meta-line))
5491 ((member dc3 '(" " ""))
5492 (add-text-properties
5493 beg (match-end 0)
5494 '(font-lock-fontified t face font-lock-comment-face)))
5495 (t nil))))))
5497 (defun org-strip-protective-commas (beg end)
5498 "Strip protective commas between BEG and END in the current buffer."
5499 (interactive "r")
5500 (save-excursion
5501 (save-match-data
5502 (goto-char beg)
5503 (let ((front-line (save-excursion
5504 (re-search-forward
5505 "[^[:space:]]" end t)
5506 (goto-char (match-beginning 0))
5507 (current-column))))
5508 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5509 (goto-char (match-beginning 1))
5510 (when (= (current-column) front-line)
5511 (replace-match "" nil nil nil 1)))))))
5513 (defun org-activate-angle-links (limit)
5514 "Run through the buffer and add overlays to links."
5515 (if (re-search-forward org-angle-link-re limit t)
5516 (progn
5517 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5518 (add-text-properties (match-beginning 0) (match-end 0)
5519 (list 'mouse-face 'highlight
5520 'keymap org-mouse-map))
5521 (org-rear-nonsticky-at (match-end 0))
5522 t)))
5524 (defun org-activate-footnote-links (limit)
5525 "Run through the buffer and add overlays to footnotes."
5526 (let ((fn (org-footnote-next-reference-or-definition limit)))
5527 (when fn
5528 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5529 (org-remove-flyspell-overlays-in beg end)
5530 (add-text-properties beg end
5531 (list 'mouse-face 'highlight
5532 'keymap org-mouse-map
5533 'help-echo
5534 (if (= (point-at-bol) beg)
5535 "Footnote definition"
5536 "Footnote reference")
5537 'font-lock-fontified t
5538 'font-lock-multiline t
5539 'face 'org-footnote))))))
5541 (defun org-activate-bracket-links (limit)
5542 "Run through the buffer and add overlays to bracketed links."
5543 (if (re-search-forward org-bracket-link-regexp limit t)
5544 (let* ((help (concat "LINK: "
5545 (org-match-string-no-properties 1)))
5546 ;; FIXME: above we should remove the escapes.
5547 ;; but that requires another match, protecting match data,
5548 ;; a lot of overhead for font-lock.
5549 (ip (org-maybe-intangible
5550 (list 'invisible 'org-link
5551 'keymap org-mouse-map 'mouse-face 'highlight
5552 'font-lock-multiline t 'help-echo help)))
5553 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5554 'font-lock-multiline t 'help-echo help)))
5555 ;; We need to remove the invisible property here. Table narrowing
5556 ;; may have made some of this invisible.
5557 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5558 (remove-text-properties (match-beginning 0) (match-end 0)
5559 '(invisible nil))
5560 (if (match-end 3)
5561 (progn
5562 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5563 (org-rear-nonsticky-at (match-beginning 3))
5564 (add-text-properties (match-beginning 3) (match-end 3) vp)
5565 (org-rear-nonsticky-at (match-end 3))
5566 (add-text-properties (match-end 3) (match-end 0) ip)
5567 (org-rear-nonsticky-at (match-end 0)))
5568 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5569 (org-rear-nonsticky-at (match-beginning 1))
5570 (add-text-properties (match-beginning 1) (match-end 1) vp)
5571 (org-rear-nonsticky-at (match-end 1))
5572 (add-text-properties (match-end 1) (match-end 0) ip)
5573 (org-rear-nonsticky-at (match-end 0)))
5574 t)))
5576 (defun org-activate-dates (limit)
5577 "Run through the buffer and add overlays to dates."
5578 (if (re-search-forward org-tsr-regexp-both limit t)
5579 (progn
5580 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5581 (add-text-properties (match-beginning 0) (match-end 0)
5582 (list 'mouse-face 'highlight
5583 'keymap org-mouse-map))
5584 (org-rear-nonsticky-at (match-end 0))
5585 (when org-display-custom-times
5586 (if (match-end 3)
5587 (org-display-custom-time (match-beginning 3) (match-end 3)))
5588 (org-display-custom-time (match-beginning 1) (match-end 1)))
5589 t)))
5591 (defvar org-target-link-regexp nil
5592 "Regular expression matching radio targets in plain text.")
5593 (make-variable-buffer-local 'org-target-link-regexp)
5594 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5595 "Regular expression matching a link target.")
5596 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5597 "Regular expression matching a radio target.")
5598 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5599 "Regular expression matching any target.")
5601 (defun org-activate-target-links (limit)
5602 "Run through the buffer and add overlays to target matches."
5603 (when org-target-link-regexp
5604 (let ((case-fold-search t))
5605 (if (re-search-forward org-target-link-regexp limit t)
5606 (progn
5607 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5608 (add-text-properties (match-beginning 0) (match-end 0)
5609 (list 'mouse-face 'highlight
5610 'keymap org-mouse-map
5611 'help-echo "Radio target link"
5612 'org-linked-text t))
5613 (org-rear-nonsticky-at (match-end 0))
5614 t)))))
5616 (defun org-update-radio-target-regexp ()
5617 "Find all radio targets in this file and update the regular expression."
5618 (interactive)
5619 (when (memq 'radio org-activate-links)
5620 (setq org-target-link-regexp
5621 (org-make-target-link-regexp (org-all-targets 'radio)))
5622 (org-restart-font-lock)))
5624 (defun org-hide-wide-columns (limit)
5625 (let (s e)
5626 (setq s (text-property-any (point) (or limit (point-max))
5627 'org-cwidth t))
5628 (when s
5629 (setq e (next-single-property-change s 'org-cwidth))
5630 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5631 (goto-char e)
5632 t)))
5634 (defvar org-latex-and-specials-regexp nil
5635 "Regular expression for highlighting export special stuff.")
5636 (defvar org-match-substring-regexp)
5637 (defvar org-match-substring-with-braces-regexp)
5639 ;; This should be with the exporter code, but we also use if for font-locking
5640 (defconst org-export-html-special-string-regexps
5641 '(("\\\\-" . "&shy;")
5642 ("---\\([^-]\\)" . "&mdash;\\1")
5643 ("--\\([^-]\\)" . "&ndash;\\1")
5644 ("\\.\\.\\." . "&hellip;"))
5645 "Regular expressions for special string conversion.")
5648 (defun org-compute-latex-and-specials-regexp ()
5649 "Compute regular expression for stuff treated specially by exporters."
5650 (if (not org-highlight-latex-fragments-and-specials)
5651 (org-set-local 'org-latex-and-specials-regexp nil)
5652 (require 'org-exp)
5653 (let*
5654 ((matchers (plist-get org-format-latex-options :matchers))
5655 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5656 org-latex-regexps)))
5657 (org-export-allow-BIND nil)
5658 (options (org-combine-plists (org-default-export-plist)
5659 (org-infile-export-plist)))
5660 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5661 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5662 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5663 (org-export-html-expand (plist-get options :expand-quoted-html))
5664 (org-export-with-special-strings (plist-get options :special-strings))
5665 (re-sub
5666 (cond
5667 ((equal org-export-with-sub-superscripts '{})
5668 (list org-match-substring-with-braces-regexp))
5669 (org-export-with-sub-superscripts
5670 (list org-match-substring-regexp))
5671 (t nil)))
5672 (re-latex
5673 (if org-export-with-LaTeX-fragments
5674 (mapcar (lambda (x) (nth 1 x)) latexs)))
5675 (re-macros
5676 (if org-export-with-TeX-macros
5677 (list (concat "\\\\"
5678 (regexp-opt
5679 (append
5681 (delq nil
5682 (mapcar 'car-safe
5683 (append org-entities-user
5684 org-entities)))
5685 (if (boundp 'org-latex-entities)
5686 (mapcar (lambda (x)
5687 (or (car-safe x) x))
5688 org-latex-entities)
5689 nil))
5690 'words))) ; FIXME
5692 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5693 (re-special (if org-export-with-special-strings
5694 (mapcar (lambda (x) (car x))
5695 org-export-html-special-string-regexps)))
5696 (re-rest
5697 (delq nil
5698 (list
5699 (if org-export-html-expand "@<[^>\n]+>")
5700 ))))
5701 (org-set-local
5702 'org-latex-and-specials-regexp
5703 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5704 re-rest) "\\|")))))
5706 (defun org-do-latex-and-special-faces (limit)
5707 "Run through the buffer and add overlays to links."
5708 (when org-latex-and-specials-regexp
5709 (let (rtn d)
5710 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5711 limit t))
5712 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5713 'face))
5714 '(org-code org-verbatim underline)))
5715 (progn
5716 (setq rtn t
5717 d (cond ((member (char-after (1+ (match-beginning 0)))
5718 '(?_ ?^)) 1)
5719 (t 0)))
5720 (font-lock-prepend-text-property
5721 (+ d (match-beginning 0)) (match-end 0)
5722 'face 'org-latex-and-export-specials)
5723 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5724 '(font-lock-multiline t)))))
5725 rtn)))
5727 (defun org-restart-font-lock ()
5728 "Restart `font-lock-mode', to force refontification."
5729 (when (and (boundp 'font-lock-mode) font-lock-mode)
5730 (font-lock-mode -1)
5731 (font-lock-mode 1)))
5733 (defun org-all-targets (&optional radio)
5734 "Return a list of all targets in this file.
5735 With optional argument RADIO, only find radio targets."
5736 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5737 rtn)
5738 (save-excursion
5739 (goto-char (point-min))
5740 (while (re-search-forward re nil t)
5741 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5742 rtn)))
5744 (defun org-make-target-link-regexp (targets)
5745 "Make regular expression matching all strings in TARGETS.
5746 The regular expression finds the targets also if there is a line break
5747 between words."
5748 (and targets
5749 (concat
5750 "\\<\\("
5751 (mapconcat
5752 (lambda (x)
5753 (setq x (regexp-quote x))
5754 (while (string-match " +" x)
5755 (setq x (replace-match "\\s-+" t t x)))
5757 targets
5758 "\\|")
5759 "\\)\\>")))
5761 (defun org-activate-tags (limit)
5762 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5765 (add-text-properties (match-beginning 1) (match-end 1)
5766 (list 'mouse-face 'highlight
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 1))
5769 t)))
5771 (defun org-outline-level ()
5772 "Compute the outline level of the heading at point.
5773 This function assumes that the cursor is at the beginning of a line matched
5774 by `outline-regexp'. Otherwise it returns garbage.
5775 If this is called at a normal headline, the level is the number of stars.
5776 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5777 (save-excursion
5778 (looking-at org-outline-regexp)
5779 (1- (- (match-end 0) (match-beginning 0)))))
5781 (defvar org-font-lock-keywords nil)
5783 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5784 "Regular expression matching a property line.")
5786 (defvar org-font-lock-hook nil
5787 "Functions to be called for special font lock stuff.")
5789 (defvar org-font-lock-set-keywords-hook nil
5790 "Functions that can manipulate `org-font-lock-extra-keywords'.
5791 This is called after `org-font-lock-extra-keywords' is defined, but before
5792 it is installed to be used by font lock. This can be useful if something
5793 needs to be inserted at a specific position in the font-lock sequence.")
5795 (defun org-font-lock-hook (limit)
5796 (run-hook-with-args 'org-font-lock-hook limit))
5798 (defun org-set-font-lock-defaults ()
5799 (let* ((em org-fontify-emphasized-text)
5800 (lk org-activate-links)
5801 (org-font-lock-extra-keywords
5802 (list
5803 ;; Call the hook
5804 '(org-font-lock-hook)
5805 ;; Headlines
5806 `(,(if org-fontify-whole-heading-line
5807 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5808 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5809 (1 (org-get-level-face 1))
5810 (2 (org-get-level-face 2))
5811 (3 (org-get-level-face 3)))
5812 ;; Table lines
5813 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5814 (1 'org-table t))
5815 ;; Table internals
5816 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5817 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5818 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5819 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5820 ;; Drawers
5821 (list org-drawer-regexp '(0 'org-special-keyword t))
5822 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5823 ;; Properties
5824 (list org-property-re
5825 '(1 'org-special-keyword t)
5826 '(3 'org-property-value t))
5827 ;; Links
5828 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5829 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5830 (if (memq 'plain lk) '(org-activate-plain-links))
5831 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5832 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5833 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5834 (if (memq 'footnote lk) '(org-activate-footnote-links))
5835 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5836 '(org-hide-wide-columns (0 nil append))
5837 ;; TODO keyword
5838 (list (format org-heading-keyword-regexp-format
5839 org-todo-regexp)
5840 '(2 (org-get-todo-face 2) t))
5841 ;; DONE
5842 (if org-fontify-done-headline
5843 (list (format org-heading-keyword-regexp-format
5844 (concat
5845 "\\(?:"
5846 (mapconcat 'regexp-quote org-done-keywords "\\|")
5847 "\\)"))
5848 '(2 'org-headline-done t))
5849 nil)
5850 ;; Priorities
5851 '(org-font-lock-add-priority-faces)
5852 ;; Tags
5853 '(org-font-lock-add-tag-faces)
5854 ;; Special keywords
5855 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5856 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5857 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5858 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5859 ;; Emphasis
5860 (if em
5861 (if (featurep 'xemacs)
5862 '(org-do-emphasis-faces (0 nil append))
5863 '(org-do-emphasis-faces)))
5864 ;; Checkboxes
5865 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5866 1 'org-checkbox prepend)
5867 (if (cdr (assq 'checkbox org-list-automatic-rules))
5868 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5869 (0 (org-get-checkbox-statistics-face) t)))
5870 ;; Description list items
5871 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5872 1 'bold prepend)
5873 ;; ARCHIVEd headings
5874 (list (concat
5875 org-outline-regexp-bol
5876 "\\(.*:" org-archive-tag ":.*\\)")
5877 '(1 'org-archived prepend))
5878 ;; Specials
5879 '(org-do-latex-and-special-faces)
5880 '(org-fontify-entities)
5881 '(org-raise-scripts)
5882 ;; Code
5883 '(org-activate-code (1 'org-code t))
5884 ;; COMMENT
5885 (list (format org-heading-keyword-regexp-format
5886 (concat "\\("
5887 org-comment-string "\\|" org-quote-string
5888 "\\)"))
5889 '(2 'org-special-keyword t))
5890 '("^#.*" (0 'font-lock-comment-face t))
5891 ;; Blocks and meta lines
5892 '(org-fontify-meta-lines-and-blocks)
5894 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5895 (run-hooks 'org-font-lock-set-keywords-hook)
5896 ;; Now set the full font-lock-keywords
5897 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5898 (org-set-local 'font-lock-defaults
5899 '(org-font-lock-keywords t nil nil backward-paragraph))
5900 (kill-local-variable 'font-lock-keywords) nil))
5902 (defun org-toggle-pretty-entities ()
5903 "Toggle the composition display of entities as UTF8 characters."
5904 (interactive)
5905 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5906 (org-restart-font-lock)
5907 (if org-pretty-entities
5908 (message "Entities are displayed as UTF8 characters")
5909 (save-restriction
5910 (widen)
5911 (org-decompose-region (point-min) (point-max))
5912 (message "Entities are displayed plain"))))
5914 (defun org-fontify-entities (limit)
5915 "Find an entity to fontify."
5916 (let (ee)
5917 (when org-pretty-entities
5918 (catch 'match
5919 (while (re-search-forward
5920 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5921 limit t)
5922 (if (and (not (org-in-indented-comment-line))
5923 (setq ee (org-entity-get (match-string 1)))
5924 (= (length (nth 6 ee)) 1))
5925 (let*
5926 ((end (if (equal (match-string 2) "{}")
5927 (match-end 2)
5928 (match-end 1))))
5929 (add-text-properties
5930 (match-beginning 0) end
5931 (list 'font-lock-fontified t))
5932 (compose-region (match-beginning 0) end
5933 (nth 6 ee) nil)
5934 (backward-char 1)
5935 (throw 'match t))))
5936 nil))))
5938 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5939 "Fontify string S like in Org-mode."
5940 (with-temp-buffer
5941 (insert s)
5942 (let ((org-odd-levels-only odd-levels))
5943 (org-mode)
5944 (font-lock-fontify-buffer)
5945 (buffer-string))))
5947 (defvar org-m nil)
5948 (defvar org-l nil)
5949 (defvar org-f nil)
5950 (defun org-get-level-face (n)
5951 "Get the right face for match N in font-lock matching of headlines."
5952 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5953 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5954 (if org-cycle-level-faces
5955 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5956 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5957 (cond
5958 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5959 ((eq n 2) org-f)
5960 (t (if org-level-color-stars-only nil org-f))))
5963 (defun org-get-todo-face (kwd)
5964 "Get the right face for a TODO keyword KWD.
5965 If KWD is a number, get the corresponding match group."
5966 (if (numberp kwd) (setq kwd (match-string kwd)))
5967 (or (org-face-from-face-or-color
5968 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5969 (and (member kwd org-done-keywords) 'org-done)
5970 'org-todo))
5972 (defun org-face-from-face-or-color (context inherit face-or-color)
5973 "Create a face list that inherits INHERIT, but sets the foreground color.
5974 When FACE-OR-COLOR is not a string, just return it."
5975 (if (stringp face-or-color)
5976 (list :inherit inherit
5977 (cdr (assoc context org-faces-easy-properties))
5978 face-or-color)
5979 face-or-color))
5981 (defun org-font-lock-add-tag-faces (limit)
5982 "Add the special tag faces."
5983 (when (and org-tag-faces org-tags-special-faces-re)
5984 (while (re-search-forward org-tags-special-faces-re limit t)
5985 (add-text-properties (match-beginning 1) (match-end 1)
5986 (list 'face (org-get-tag-face 1)
5987 'font-lock-fontified t))
5988 (backward-char 1))))
5990 (defun org-font-lock-add-priority-faces (limit)
5991 "Add the special priority faces."
5992 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5993 (add-text-properties
5994 (match-beginning 0) (match-end 0)
5995 (list 'face (or (org-face-from-face-or-color
5996 'priority 'org-special-keyword
5997 (cdr (assoc (char-after (match-beginning 1))
5998 org-priority-faces)))
5999 'org-special-keyword)
6000 'font-lock-fontified t))))
6002 (defun org-get-tag-face (kwd)
6003 "Get the right face for a TODO keyword KWD.
6004 If KWD is a number, get the corresponding match group."
6005 (if (numberp kwd) (setq kwd (match-string kwd)))
6006 (or (org-face-from-face-or-color
6007 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6008 'org-tag))
6010 (defun org-unfontify-region (beg end &optional maybe_loudly)
6011 "Remove fontification and activation overlays from links."
6012 (font-lock-default-unfontify-region beg end)
6013 (let* ((buffer-undo-list t)
6014 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6015 (inhibit-modification-hooks t)
6016 deactivate-mark buffer-file-name buffer-file-truename)
6017 (org-decompose-region beg end)
6018 (remove-text-properties beg end
6019 '(mouse-face t keymap t org-linked-text t
6020 invisible t intangible t
6021 org-no-flyspell t org-emphasis t))
6022 (org-remove-font-lock-display-properties beg end)))
6024 (defconst org-script-display '(((raise -0.3) (height 0.7))
6025 ((raise 0.3) (height 0.7))
6026 ((raise -0.5))
6027 ((raise 0.5)))
6028 "Display properties for showing superscripts and subscripts.")
6030 (defun org-remove-font-lock-display-properties (beg end)
6031 "Remove specific display properties that have been added by font lock.
6032 The will remove the raise properties that are used to show superscripts
6033 and subscripts."
6034 (let (next prop)
6035 (while (< beg end)
6036 (setq next (next-single-property-change beg 'display nil end)
6037 prop (get-text-property beg 'display))
6038 (if (member prop org-script-display)
6039 (put-text-property beg next 'display nil))
6040 (setq beg next))))
6042 (defun org-raise-scripts (limit)
6043 "Add raise properties to sub/superscripts."
6044 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6045 (if (re-search-forward
6046 (if (eq org-use-sub-superscripts t)
6047 org-match-substring-regexp
6048 org-match-substring-with-braces-regexp)
6049 limit t)
6050 (let* ((pos (point)) table-p comment-p
6051 (mpos (match-beginning 3))
6052 (emph-p (get-text-property mpos 'org-emphasis))
6053 (link-p (get-text-property mpos 'mouse-face))
6054 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6055 (goto-char (point-at-bol))
6056 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6057 comment-p (org-looking-at-p "[ \t]*#"))
6058 (goto-char pos)
6059 ;; FIXME: Should we go back one character here, for a_b^c
6060 ;; (goto-char (1- pos)) ;????????????????????
6061 (if (or comment-p emph-p link-p keyw-p)
6063 (put-text-property (match-beginning 3) (match-end 0)
6064 'display
6065 (if (equal (char-after (match-beginning 2)) ?^)
6066 (nth (if table-p 3 1) org-script-display)
6067 (nth (if table-p 2 0) org-script-display)))
6068 (add-text-properties (match-beginning 2) (match-end 2)
6069 (list 'invisible t
6070 'org-dwidth t 'org-dwidth-n 1))
6071 (if (and (eq (char-after (match-beginning 3)) ?{)
6072 (eq (char-before (match-end 3)) ?}))
6073 (progn
6074 (add-text-properties
6075 (match-beginning 3) (1+ (match-beginning 3))
6076 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6077 (add-text-properties
6078 (1- (match-end 3)) (match-end 3)
6079 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6080 t)))))
6082 ;;;; Visibility cycling, including org-goto and indirect buffer
6084 ;;; Cycling
6086 (defvar org-cycle-global-status nil)
6087 (make-variable-buffer-local 'org-cycle-global-status)
6088 (defvar org-cycle-subtree-status nil)
6089 (make-variable-buffer-local 'org-cycle-subtree-status)
6091 ;;;###autoload
6093 (defvar org-inlinetask-min-level)
6095 (defun org-cycle (&optional arg)
6096 "TAB-action and visibility cycling for Org-mode.
6098 This is the command invoked in Org-mode by the TAB key. Its main purpose
6099 is outline visibility cycling, but it also invokes other actions
6100 in special contexts.
6102 - When this function is called with a prefix argument, rotate the entire
6103 buffer through 3 states (global cycling)
6104 1. OVERVIEW: Show only top-level headlines.
6105 2. CONTENTS: Show all headlines of all levels, but no body text.
6106 3. SHOW ALL: Show everything.
6107 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6108 determined by the variable `org-startup-folded', and by any VISIBILITY
6109 properties in the buffer.
6110 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6111 including any drawers.
6113 - When inside a table, re-align the table and move to the next field.
6115 - When point is at the beginning of a headline, rotate the subtree started
6116 by this line through 3 different states (local cycling)
6117 1. FOLDED: Only the main headline is shown.
6118 2. CHILDREN: The main headline and the direct children are shown.
6119 From this state, you can move to one of the children
6120 and zoom in further.
6121 3. SUBTREE: Show the entire subtree, including body text.
6122 If there is no subtree, switch directly from CHILDREN to FOLDED.
6124 - When point is at the beginning of an empty headline and the variable
6125 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6126 of the headline by demoting and promoting it to likely levels. This
6127 speeds up creation document structure by pressing TAB once or several
6128 times right after creating a new headline.
6130 - When there is a numeric prefix, go up to a heading with level ARG, do
6131 a `show-subtree' and return to the previous cursor position. If ARG
6132 is negative, go up that many levels.
6134 - When point is not at the beginning of a headline, execute the global
6135 binding for TAB, which is re-indenting the line. See the option
6136 `org-cycle-emulate-tab' for details.
6138 - Special case: if point is at the beginning of the buffer and there is
6139 no headline in line 1, this function will act as if called with prefix arg
6140 (C-u TAB, same as S-TAB) also when called without prefix arg.
6141 But only if also the variable `org-cycle-global-at-bob' is t."
6142 (interactive "P")
6143 (org-load-modules-maybe)
6144 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6145 (and org-cycle-level-after-item/entry-creation
6146 (or (org-cycle-level)
6147 (org-cycle-item-indentation))))
6148 (let* ((limit-level
6149 (or org-cycle-max-level
6150 (and (boundp 'org-inlinetask-min-level)
6151 org-inlinetask-min-level
6152 (1- org-inlinetask-min-level))))
6153 (nstars (and limit-level
6154 (if org-odd-levels-only
6155 (and limit-level (1- (* limit-level 2)))
6156 limit-level)))
6157 (org-outline-regexp
6158 (if (not (eq major-mode 'org-mode))
6159 outline-regexp
6160 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6161 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6162 (not (looking-at org-outline-regexp))))
6163 (org-cycle-hook
6164 (if bob-special
6165 (delq 'org-optimize-window-after-visibility-change
6166 (copy-sequence org-cycle-hook))
6167 org-cycle-hook))
6168 (pos (point)))
6170 (if (or bob-special (equal arg '(4)))
6171 ;; special case: use global cycling
6172 (setq arg t))
6174 (cond
6176 ((equal arg '(16))
6177 (setq last-command 'dummy)
6178 (org-set-startup-visibility)
6179 (message "Startup visibility, plus VISIBILITY properties"))
6181 ((equal arg '(64))
6182 (show-all)
6183 (message "Entire buffer visible, including drawers"))
6185 ;; Table: enter it or move to the next field.
6186 ((org-at-table-p 'any)
6187 (if (org-at-table.el-p)
6188 (message "Use C-c ' to edit table.el tables")
6189 (if arg (org-table-edit-field t)
6190 (org-table-justify-field-maybe)
6191 (call-interactively 'org-table-next-field))))
6193 ((run-hook-with-args-until-success
6194 'org-tab-after-check-for-table-hook))
6196 ;; Global cycling: delegate to `org-cycle-internal-global'.
6197 ((eq arg t) (org-cycle-internal-global))
6199 ;; Drawers: delegate to `org-flag-drawer'.
6200 ((and org-drawers org-drawer-regexp
6201 (save-excursion
6202 (beginning-of-line 1)
6203 (looking-at org-drawer-regexp)))
6204 (org-flag-drawer ; toggle block visibility
6205 (not (get-char-property (match-end 0) 'invisible))))
6207 ;; Show-subtree, ARG levels up from here.
6208 ((integerp arg)
6209 (save-excursion
6210 (org-back-to-heading)
6211 (outline-up-heading (if (< arg 0) (- arg)
6212 (- (funcall outline-level) arg)))
6213 (org-show-subtree)))
6215 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6216 ((and (featurep 'org-inlinetask)
6217 (org-inlinetask-at-task-p)
6218 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6219 (org-inlinetask-toggle-visibility))
6221 ((org-try-cdlatex-tab))
6223 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6224 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6225 (save-excursion (beginning-of-line 1)
6226 (looking-at org-outline-regexp)))
6227 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6228 (org-cycle-internal-local))
6230 ;; From there: TAB emulation and template completion.
6231 (buffer-read-only (org-back-to-heading))
6233 ((run-hook-with-args-until-success
6234 'org-tab-after-check-for-cycling-hook))
6236 ((org-try-structure-completion))
6238 ((run-hook-with-args-until-success
6239 'org-tab-before-tab-emulation-hook))
6241 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6242 (or (not (bolp))
6243 (not (looking-at org-outline-regexp))))
6244 (call-interactively (global-key-binding "\t")))
6246 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6247 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6248 (or (and (eq org-cycle-emulate-tab 'white)
6249 (= (match-end 0) (point-at-eol)))
6250 (and (eq org-cycle-emulate-tab 'whitestart)
6251 (>= (match-end 0) pos))))
6253 (eq org-cycle-emulate-tab t))
6254 (call-interactively (global-key-binding "\t")))
6256 (t (save-excursion
6257 (org-back-to-heading)
6258 (org-cycle)))))))
6260 (defun org-cycle-internal-global ()
6261 "Do the global cycling action."
6262 ;; Hack to avoid display of messages for .org attachments in Gnus
6263 (let ((ga (string-match "\\*fontification" (buffer-name))))
6264 (cond
6265 ((and (eq last-command this-command)
6266 (eq org-cycle-global-status 'overview))
6267 ;; We just created the overview - now do table of contents
6268 ;; This can be slow in very large buffers, so indicate action
6269 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6270 (unless ga (message "CONTENTS..."))
6271 (org-content)
6272 (unless ga (message "CONTENTS...done"))
6273 (setq org-cycle-global-status 'contents)
6274 (run-hook-with-args 'org-cycle-hook 'contents))
6276 ((and (eq last-command this-command)
6277 (eq org-cycle-global-status 'contents))
6278 ;; We just showed the table of contents - now show everything
6279 (run-hook-with-args 'org-pre-cycle-hook 'all)
6280 (show-all)
6281 (unless ga (message "SHOW ALL"))
6282 (setq org-cycle-global-status 'all)
6283 (run-hook-with-args 'org-cycle-hook 'all))
6286 ;; Default action: go to overview
6287 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6288 (org-overview)
6289 (unless ga (message "OVERVIEW"))
6290 (setq org-cycle-global-status 'overview)
6291 (run-hook-with-args 'org-cycle-hook 'overview)))))
6293 (defun org-cycle-internal-local ()
6294 "Do the local cycling action."
6295 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6296 ;; First, determine end of headline (EOH), end of subtree or item
6297 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6298 (save-excursion
6299 (if (org-at-item-p)
6300 (progn
6301 (beginning-of-line)
6302 (setq struct (org-list-struct))
6303 (setq eoh (point-at-eol))
6304 (setq eos (org-list-get-item-end-before-blank (point) struct))
6305 (setq has-children (org-list-has-child-p (point) struct)))
6306 (org-back-to-heading)
6307 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6308 (setq eos (save-excursion
6309 (org-end-of-subtree t)
6310 (unless (eobp)
6311 (skip-chars-forward " \t\n"))
6312 (if (eobp) (point) (1- (point)))))
6313 (setq has-children
6314 (or (save-excursion
6315 (let ((level (funcall outline-level)))
6316 (outline-next-heading)
6317 (and (org-at-heading-p t)
6318 (> (funcall outline-level) level))))
6319 (save-excursion
6320 (org-list-search-forward (org-item-beginning-re) eos t)))))
6321 ;; Determine end invisible part of buffer (EOL)
6322 (beginning-of-line 2)
6323 ;; XEmacs doesn't have `next-single-char-property-change'
6324 (if (featurep 'xemacs)
6325 (while (and (not (eobp)) ;; this is like `next-line'
6326 (get-char-property (1- (point)) 'invisible))
6327 (beginning-of-line 2))
6328 (while (and (not (eobp)) ;; this is like `next-line'
6329 (get-char-property (1- (point)) 'invisible))
6330 (goto-char (next-single-char-property-change (point) 'invisible))
6331 (and (eolp) (beginning-of-line 2))))
6332 (setq eol (point)))
6333 ;; Find out what to do next and set `this-command'
6334 (cond
6335 ((= eos eoh)
6336 ;; Nothing is hidden behind this heading
6337 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6338 (message "EMPTY ENTRY")
6339 (setq org-cycle-subtree-status nil)
6340 (save-excursion
6341 (goto-char eos)
6342 (outline-next-heading)
6343 (if (outline-invisible-p) (org-flag-heading nil))))
6344 ((and (or (>= eol eos)
6345 (not (string-match "\\S-" (buffer-substring eol eos))))
6346 (or has-children
6347 (not (setq children-skipped
6348 org-cycle-skip-children-state-if-no-children))))
6349 ;; Entire subtree is hidden in one line: children view
6350 (run-hook-with-args 'org-pre-cycle-hook 'children)
6351 (if (org-at-item-p)
6352 (org-list-set-item-visibility (point-at-bol) struct 'children)
6353 (org-show-entry)
6354 (org-with-limited-levels (show-children))
6355 ;; FIXME: This slows down the func way too much.
6356 ;; How keep drawers hidden in subtree anyway?
6357 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6358 ;; (org-cycle-hide-drawers 'subtree))
6360 ;; Fold every list in subtree to top-level items.
6361 (when (eq org-cycle-include-plain-lists 'integrate)
6362 (save-excursion
6363 (org-back-to-heading)
6364 (while (org-list-search-forward (org-item-beginning-re) eos t)
6365 (beginning-of-line 1)
6366 (let* ((struct (org-list-struct))
6367 (prevs (org-list-prevs-alist struct))
6368 (end (org-list-get-bottom-point struct)))
6369 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6370 (org-list-get-all-items (point) struct prevs))
6371 (goto-char end))))))
6372 (message "CHILDREN")
6373 (save-excursion
6374 (goto-char eos)
6375 (outline-next-heading)
6376 (if (outline-invisible-p) (org-flag-heading nil)))
6377 (setq org-cycle-subtree-status 'children)
6378 (run-hook-with-args 'org-cycle-hook 'children))
6379 ((or children-skipped
6380 (and (eq last-command this-command)
6381 (eq org-cycle-subtree-status 'children)))
6382 ;; We just showed the children, or no children are there,
6383 ;; now show everything.
6384 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6385 (outline-flag-region eoh eos nil)
6386 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6387 (setq org-cycle-subtree-status 'subtree)
6388 (run-hook-with-args 'org-cycle-hook 'subtree))
6390 ;; Default action: hide the subtree.
6391 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6392 (outline-flag-region eoh eos t)
6393 (message "FOLDED")
6394 (setq org-cycle-subtree-status 'folded)
6395 (run-hook-with-args 'org-cycle-hook 'folded)))))
6397 ;;;###autoload
6398 (defun org-global-cycle (&optional arg)
6399 "Cycle the global visibility. For details see `org-cycle'.
6400 With \\[universal-argument] prefix arg, switch to startup visibility.
6401 With a numeric prefix, show all headlines up to that level."
6402 (interactive "P")
6403 (let ((org-cycle-include-plain-lists
6404 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6405 (cond
6406 ((integerp arg)
6407 (show-all)
6408 (hide-sublevels arg)
6409 (setq org-cycle-global-status 'contents))
6410 ((equal arg '(4))
6411 (org-set-startup-visibility)
6412 (message "Startup visibility, plus VISIBILITY properties."))
6414 (org-cycle '(4))))))
6416 (defun org-set-startup-visibility ()
6417 "Set the visibility required by startup options and properties."
6418 (cond
6419 ((eq org-startup-folded t)
6420 (org-cycle '(4)))
6421 ((eq org-startup-folded 'content)
6422 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6423 (org-cycle '(4)) (org-cycle '(4)))))
6424 (unless (eq org-startup-folded 'showeverything)
6425 (if org-hide-block-startup (org-hide-block-all))
6426 (org-set-visibility-according-to-property 'no-cleanup)
6427 (org-cycle-hide-archived-subtrees 'all)
6428 (org-cycle-hide-drawers 'all)
6429 (org-cycle-show-empty-lines t)))
6431 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6432 "Switch subtree visibilities according to :VISIBILITY: property."
6433 (interactive)
6434 (let (org-show-entry-below state)
6435 (save-excursion
6436 (goto-char (point-min))
6437 (while (re-search-forward
6438 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6439 nil t)
6440 (setq state (match-string 1))
6441 (save-excursion
6442 (org-back-to-heading t)
6443 (hide-subtree)
6444 (org-reveal)
6445 (cond
6446 ((equal state '("fold" "folded"))
6447 (hide-subtree))
6448 ((equal state "children")
6449 (org-show-hidden-entry)
6450 (show-children))
6451 ((equal state "content")
6452 (save-excursion
6453 (save-restriction
6454 (org-narrow-to-subtree)
6455 (org-content))))
6456 ((member state '("all" "showall"))
6457 (show-subtree)))))
6458 (unless no-cleanup
6459 (org-cycle-hide-archived-subtrees 'all)
6460 (org-cycle-hide-drawers 'all)
6461 (org-cycle-show-empty-lines 'all)))))
6463 ;; This function uses outline-regexp instead of the more fundamental
6464 ;; org-outline-regexp so that org-cycle-global works outside of Org
6465 ;; buffers, where outline-regexp is needed.
6466 (defun org-overview ()
6467 "Switch to overview mode, showing only top-level headlines.
6468 Really, this shows all headlines with level equal or greater than the level
6469 of the first headline in the buffer. This is important, because if the
6470 first headline is not level one, then (hide-sublevels 1) gives confusing
6471 results."
6472 (interactive)
6473 (let ((level (save-excursion
6474 (goto-char (point-min))
6475 (if (re-search-forward (concat "^" outline-regexp) nil t)
6476 (progn
6477 (goto-char (match-beginning 0))
6478 (funcall outline-level))))))
6479 (and level (hide-sublevels level))))
6481 (defun org-content (&optional arg)
6482 "Show all headlines in the buffer, like a table of contents.
6483 With numerical argument N, show content up to level N."
6484 (interactive "P")
6485 (save-excursion
6486 ;; Visit all headings and show their offspring
6487 (and (integerp arg) (org-overview))
6488 (goto-char (point-max))
6489 (catch 'exit
6490 (while (and (progn (condition-case nil
6491 (outline-previous-visible-heading 1)
6492 (error (goto-char (point-min))))
6494 (looking-at org-outline-regexp))
6495 (if (integerp arg)
6496 (show-children (1- arg))
6497 (show-branches))
6498 (if (bobp) (throw 'exit nil))))))
6501 (defun org-optimize-window-after-visibility-change (state)
6502 "Adjust the window after a change in outline visibility.
6503 This function is the default value of the hook `org-cycle-hook'."
6504 (when (get-buffer-window (current-buffer))
6505 (cond
6506 ((eq state 'content) nil)
6507 ((eq state 'all) nil)
6508 ((eq state 'folded) nil)
6509 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6510 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6512 (defun org-remove-empty-overlays-at (pos)
6513 "Remove outline overlays that do not contain non-white stuff."
6514 (mapc
6515 (lambda (o)
6516 (and (eq 'outline (overlay-get o 'invisible))
6517 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6518 (overlay-end o))))
6519 (delete-overlay o)))
6520 (overlays-at pos)))
6522 (defun org-clean-visibility-after-subtree-move ()
6523 "Fix visibility issues after moving a subtree."
6524 ;; First, find a reasonable region to look at:
6525 ;; Start two siblings above, end three below
6526 (let* ((beg (save-excursion
6527 (and (org-get-last-sibling)
6528 (org-get-last-sibling))
6529 (point)))
6530 (end (save-excursion
6531 (and (org-get-next-sibling)
6532 (org-get-next-sibling)
6533 (org-get-next-sibling))
6534 (if (org-at-heading-p)
6535 (point-at-eol)
6536 (point))))
6537 (level (looking-at "\\*+"))
6538 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6539 (save-excursion
6540 (save-restriction
6541 (narrow-to-region beg end)
6542 (when re
6543 ;; Properly fold already folded siblings
6544 (goto-char (point-min))
6545 (while (re-search-forward re nil t)
6546 (if (and (not (outline-invisible-p))
6547 (save-excursion
6548 (goto-char (point-at-eol)) (outline-invisible-p)))
6549 (hide-entry))))
6550 (org-cycle-show-empty-lines 'overview)
6551 (org-cycle-hide-drawers 'overview)))))
6553 (defun org-cycle-show-empty-lines (state)
6554 "Show empty lines above all visible headlines.
6555 The region to be covered depends on STATE when called through
6556 `org-cycle-hook'. Lisp program can use t for STATE to get the
6557 entire buffer covered. Note that an empty line is only shown if there
6558 are at least `org-cycle-separator-lines' empty lines before the headline."
6559 (when (not (= org-cycle-separator-lines 0))
6560 (save-excursion
6561 (let* ((n (abs org-cycle-separator-lines))
6562 (re (cond
6563 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6564 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6565 (t (let ((ns (number-to-string (- n 2))))
6566 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6567 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6568 beg end b e)
6569 (cond
6570 ((memq state '(overview contents t))
6571 (setq beg (point-min) end (point-max)))
6572 ((memq state '(children folded))
6573 (setq beg (point) end (progn (org-end-of-subtree t t)
6574 (beginning-of-line 2)
6575 (point)))))
6576 (when beg
6577 (goto-char beg)
6578 (while (re-search-forward re end t)
6579 (unless (get-char-property (match-end 1) 'invisible)
6580 (setq e (match-end 1))
6581 (if (< org-cycle-separator-lines 0)
6582 (setq b (save-excursion
6583 (goto-char (match-beginning 0))
6584 (org-back-over-empty-lines)
6585 (if (save-excursion
6586 (goto-char (max (point-min) (1- (point))))
6587 (org-at-heading-p))
6588 (1- (point))
6589 (point))))
6590 (setq b (match-beginning 1)))
6591 (outline-flag-region b e nil)))))))
6592 ;; Never hide empty lines at the end of the file.
6593 (save-excursion
6594 (goto-char (point-max))
6595 (outline-previous-heading)
6596 (outline-end-of-heading)
6597 (if (and (looking-at "[ \t\n]+")
6598 (= (match-end 0) (point-max)))
6599 (outline-flag-region (point) (match-end 0) nil))))
6601 (defun org-show-empty-lines-in-parent ()
6602 "Move to the parent and re-show empty lines before visible headlines."
6603 (save-excursion
6604 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6605 (org-cycle-show-empty-lines context))))
6607 (defun org-files-list ()
6608 "Return `org-agenda-files' list, plus all open org-mode files.
6609 This is useful for operations that need to scan all of a user's
6610 open and agenda-wise Org files."
6611 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6612 (dolist (buf (buffer-list))
6613 (with-current-buffer buf
6614 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6615 (let ((file (expand-file-name (buffer-file-name))))
6616 (unless (member file files)
6617 (push file files))))))
6618 files))
6620 (defsubst org-entry-beginning-position ()
6621 "Return the beginning position of the current entry."
6622 (save-excursion (outline-back-to-heading t) (point)))
6624 (defsubst org-entry-end-position ()
6625 "Return the end position of the current entry."
6626 (save-excursion (outline-next-heading) (point)))
6628 (defun org-cycle-hide-drawers (state)
6629 "Re-hide all drawers after a visibility state change."
6630 (when (and (eq major-mode 'org-mode)
6631 (not (memq state '(overview folded contents))))
6632 (save-excursion
6633 (let* ((globalp (memq state '(contents all)))
6634 (beg (if globalp (point-min) (point)))
6635 (end (if globalp (point-max)
6636 (if (eq state 'children)
6637 (save-excursion (outline-next-heading) (point))
6638 (org-end-of-subtree t)))))
6639 (goto-char beg)
6640 (while (re-search-forward org-drawer-regexp end t)
6641 (org-flag-drawer t))))))
6643 (defun org-flag-drawer (flag)
6644 (save-excursion
6645 (beginning-of-line 1)
6646 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6647 (let ((b (match-end 0)))
6648 (if (re-search-forward
6649 "^[ \t]*:END:"
6650 (save-excursion (outline-next-heading) (point)) t)
6651 (outline-flag-region b (point-at-eol) flag)
6652 (error ":END: line missing at position %s" b))))))
6654 (defun org-subtree-end-visible-p ()
6655 "Is the end of the current subtree visible?"
6656 (pos-visible-in-window-p
6657 (save-excursion (org-end-of-subtree t) (point))))
6659 (defun org-first-headline-recenter (&optional N)
6660 "Move cursor to the first headline and recenter the headline.
6661 Optional argument N means put the headline into the Nth line of the window."
6662 (goto-char (point-min))
6663 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6664 (beginning-of-line)
6665 (recenter (prefix-numeric-value N))))
6667 ;;; Saving and restoring visibility
6669 (defun org-outline-overlay-data (&optional use-markers)
6670 "Return a list of the locations of all outline overlays.
6671 These are overlays with the `invisible' property value `outline'.
6672 The return value is a list of cons cells, with start and stop
6673 positions for each overlay.
6674 If USE-MARKERS is set, return the positions as markers."
6675 (let (beg end)
6676 (save-excursion
6677 (save-restriction
6678 (widen)
6679 (delq nil
6680 (mapcar (lambda (o)
6681 (when (eq (overlay-get o 'invisible) 'outline)
6682 (setq beg (overlay-start o)
6683 end (overlay-end o))
6684 (and beg end (> end beg)
6685 (if use-markers
6686 (cons (move-marker (make-marker) beg)
6687 (move-marker (make-marker) end))
6688 (cons beg end)))))
6689 (overlays-in (point-min) (point-max))))))))
6691 (defun org-set-outline-overlay-data (data)
6692 "Create visibility overlays for all positions in DATA.
6693 DATA should have been made by `org-outline-overlay-data'."
6694 (let (o)
6695 (save-excursion
6696 (save-restriction
6697 (widen)
6698 (show-all)
6699 (mapc (lambda (c)
6700 (outline-flag-region (car c) (cdr c) t))
6701 data)))))
6703 ;;; Folding of blocks
6705 (defvar org-hide-block-overlays nil
6706 "Overlays hiding blocks.")
6707 (make-variable-buffer-local 'org-hide-block-overlays)
6709 (defun org-block-map (function &optional start end)
6710 "Call FUNCTION at the head of all source blocks in the current buffer.
6711 Optional arguments START and END can be used to limit the range."
6712 (let ((start (or start (point-min)))
6713 (end (or end (point-max))))
6714 (save-excursion
6715 (goto-char start)
6716 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6717 (save-excursion
6718 (save-match-data
6719 (goto-char (match-beginning 0))
6720 (funcall function)))))))
6722 (defun org-hide-block-toggle-all ()
6723 "Toggle the visibility of all blocks in the current buffer."
6724 (org-block-map #'org-hide-block-toggle))
6726 (defun org-hide-block-all ()
6727 "Fold all blocks in the current buffer."
6728 (interactive)
6729 (org-show-block-all)
6730 (org-block-map #'org-hide-block-toggle-maybe))
6732 (defun org-show-block-all ()
6733 "Unfold all blocks in the current buffer."
6734 (interactive)
6735 (mapc 'delete-overlay org-hide-block-overlays)
6736 (setq org-hide-block-overlays nil))
6738 (defun org-hide-block-toggle-maybe ()
6739 "Toggle visibility of block at point."
6740 (interactive)
6741 (let ((case-fold-search t))
6742 (if (save-excursion
6743 (beginning-of-line 1)
6744 (looking-at org-block-regexp))
6745 (progn (org-hide-block-toggle)
6746 t) ;; to signal that we took action
6747 nil))) ;; to signal that we did not
6749 (defun org-hide-block-toggle (&optional force)
6750 "Toggle the visibility of the current block."
6751 (interactive)
6752 (save-excursion
6753 (beginning-of-line)
6754 (if (re-search-forward org-block-regexp nil t)
6755 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6756 (end (match-end 0)) ;; end of entire body
6758 (if (memq t (mapcar (lambda (overlay)
6759 (eq (overlay-get overlay 'invisible)
6760 'org-hide-block))
6761 (overlays-at start)))
6762 (if (or (not force) (eq force 'off))
6763 (mapc (lambda (ov)
6764 (when (member ov org-hide-block-overlays)
6765 (setq org-hide-block-overlays
6766 (delq ov org-hide-block-overlays)))
6767 (when (eq (overlay-get ov 'invisible)
6768 'org-hide-block)
6769 (delete-overlay ov)))
6770 (overlays-at start)))
6771 (setq ov (make-overlay start end))
6772 (overlay-put ov 'invisible 'org-hide-block)
6773 ;; make the block accessible to isearch
6774 (overlay-put
6775 ov 'isearch-open-invisible
6776 (lambda (ov)
6777 (when (member ov org-hide-block-overlays)
6778 (setq org-hide-block-overlays
6779 (delq ov org-hide-block-overlays)))
6780 (when (eq (overlay-get ov 'invisible)
6781 'org-hide-block)
6782 (delete-overlay ov))))
6783 (push ov org-hide-block-overlays)))
6784 (error "Not looking at a source block"))))
6786 ;; org-tab-after-check-for-cycling-hook
6787 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6788 ;; Remove overlays when changing major mode
6789 (add-hook 'org-mode-hook
6790 (lambda () (org-add-hook 'change-major-mode-hook
6791 'org-show-block-all 'append 'local)))
6793 ;;; Org-goto
6795 (defvar org-goto-window-configuration nil)
6796 (defvar org-goto-marker nil)
6797 (defvar org-goto-map
6798 (let ((map (make-sparse-keymap)))
6799 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6800 (while (setq cmd (pop cmds))
6801 (substitute-key-definition cmd cmd map global-map)))
6802 (suppress-keymap map)
6803 (org-defkey map "\C-m" 'org-goto-ret)
6804 (org-defkey map [(return)] 'org-goto-ret)
6805 (org-defkey map [(left)] 'org-goto-left)
6806 (org-defkey map [(right)] 'org-goto-right)
6807 (org-defkey map [(control ?g)] 'org-goto-quit)
6808 (org-defkey map "\C-i" 'org-cycle)
6809 (org-defkey map [(tab)] 'org-cycle)
6810 (org-defkey map [(down)] 'outline-next-visible-heading)
6811 (org-defkey map [(up)] 'outline-previous-visible-heading)
6812 (if org-goto-auto-isearch
6813 (if (fboundp 'define-key-after)
6814 (define-key-after map [t] 'org-goto-local-auto-isearch)
6815 nil)
6816 (org-defkey map "q" 'org-goto-quit)
6817 (org-defkey map "n" 'outline-next-visible-heading)
6818 (org-defkey map "p" 'outline-previous-visible-heading)
6819 (org-defkey map "f" 'outline-forward-same-level)
6820 (org-defkey map "b" 'outline-backward-same-level)
6821 (org-defkey map "u" 'outline-up-heading))
6822 (org-defkey map "/" 'org-occur)
6823 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6824 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6825 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6826 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6827 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6828 map))
6830 (defconst org-goto-help
6831 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6832 RET=jump to location [Q]uit and return to previous location
6833 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6835 (defvar org-goto-start-pos) ; dynamically scoped parameter
6837 ;; FIXME: Docstring does not mention both interfaces
6838 (defun org-goto (&optional alternative-interface)
6839 "Look up a different location in the current file, keeping current visibility.
6841 When you want look-up or go to a different location in a document, the
6842 fastest way is often to fold the entire buffer and then dive into the tree.
6843 This method has the disadvantage, that the previous location will be folded,
6844 which may not be what you want.
6846 This command works around this by showing a copy of the current buffer
6847 in an indirect buffer, in overview mode. You can dive into the tree in
6848 that copy, use org-occur and incremental search to find a location.
6849 When pressing RET or `Q', the command returns to the original buffer in
6850 which the visibility is still unchanged. After RET it will also jump to
6851 the location selected in the indirect buffer and expose the headline
6852 hierarchy above."
6853 (interactive "P")
6854 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6855 (org-refile-use-outline-path t)
6856 (org-refile-target-verify-function nil)
6857 (interface
6858 (if (not alternative-interface)
6859 org-goto-interface
6860 (if (eq org-goto-interface 'outline)
6861 'outline-path-completion
6862 'outline)))
6863 (org-goto-start-pos (point))
6864 (selected-point
6865 (if (eq interface 'outline)
6866 (car (org-get-location (current-buffer) org-goto-help))
6867 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6868 (org-refile-check-position pa)
6869 (nth 3 pa)))))
6870 (if selected-point
6871 (progn
6872 (org-mark-ring-push org-goto-start-pos)
6873 (goto-char selected-point)
6874 (if (or (outline-invisible-p) (org-invisible-p2))
6875 (org-show-context 'org-goto)))
6876 (message "Quit"))))
6878 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6879 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6880 (defvar org-goto-local-auto-isearch-map) ; defined below
6882 (defun org-get-location (buf help)
6883 "Let the user select a location in the Org-mode buffer BUF.
6884 This function uses a recursive edit. It returns the selected position
6885 or nil."
6886 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6887 (isearch-hide-immediately nil)
6888 (isearch-search-fun-function
6889 (lambda () 'org-goto-local-search-headings))
6890 (org-goto-selected-point org-goto-exit-command)
6891 (pop-up-frames nil)
6892 (special-display-buffer-names nil)
6893 (special-display-regexps nil)
6894 (special-display-function nil))
6895 (save-excursion
6896 (save-window-excursion
6897 (delete-other-windows)
6898 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6899 (org-pop-to-buffer-same-window
6900 (condition-case nil
6901 (make-indirect-buffer (current-buffer) "*org-goto*")
6902 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6903 (with-output-to-temp-buffer "*Help*"
6904 (princ help))
6905 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6906 (setq buffer-read-only nil)
6907 (let ((org-startup-truncated t)
6908 (org-startup-folded nil)
6909 (org-startup-align-all-tables nil))
6910 (org-mode)
6911 (org-overview))
6912 (setq buffer-read-only t)
6913 (if (and (boundp 'org-goto-start-pos)
6914 (integer-or-marker-p org-goto-start-pos))
6915 (let ((org-show-hierarchy-above t)
6916 (org-show-siblings t)
6917 (org-show-following-heading t))
6918 (goto-char org-goto-start-pos)
6919 (and (outline-invisible-p) (org-show-context)))
6920 (goto-char (point-min)))
6921 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6922 (message "Select location and press RET")
6923 (use-local-map org-goto-map)
6924 (recursive-edit)
6926 (kill-buffer "*org-goto*")
6927 (cons org-goto-selected-point org-goto-exit-command)))
6929 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6930 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6931 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6932 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6934 (defun org-goto-local-search-headings (string bound noerror)
6935 "Search and make sure that any matches are in headlines."
6936 (catch 'return
6937 (while (if isearch-forward
6938 (search-forward string bound noerror)
6939 (search-backward string bound noerror))
6940 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6941 (and (member :headline context)
6942 (not (member :tags context))))
6943 (throw 'return (point))))))
6945 (defun org-goto-local-auto-isearch ()
6946 "Start isearch."
6947 (interactive)
6948 (goto-char (point-min))
6949 (let ((keys (this-command-keys)))
6950 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6951 (isearch-mode t)
6952 (isearch-process-search-char (string-to-char keys)))))
6954 (defun org-goto-ret (&optional arg)
6955 "Finish `org-goto' by going to the new location."
6956 (interactive "P")
6957 (setq org-goto-selected-point (point)
6958 org-goto-exit-command 'return)
6959 (throw 'exit nil))
6961 (defun org-goto-left ()
6962 "Finish `org-goto' by going to the new location."
6963 (interactive)
6964 (if (org-at-heading-p)
6965 (progn
6966 (beginning-of-line 1)
6967 (setq org-goto-selected-point (point)
6968 org-goto-exit-command 'left)
6969 (throw 'exit nil))
6970 (error "Not on a heading")))
6972 (defun org-goto-right ()
6973 "Finish `org-goto' by going to the new location."
6974 (interactive)
6975 (if (org-at-heading-p)
6976 (progn
6977 (setq org-goto-selected-point (point)
6978 org-goto-exit-command 'right)
6979 (throw 'exit nil))
6980 (error "Not on a heading")))
6982 (defun org-goto-quit ()
6983 "Finish `org-goto' without cursor motion."
6984 (interactive)
6985 (setq org-goto-selected-point nil)
6986 (setq org-goto-exit-command 'quit)
6987 (throw 'exit nil))
6989 ;;; Indirect buffer display of subtrees
6991 (defvar org-indirect-dedicated-frame nil
6992 "This is the frame being used for indirect tree display.")
6993 (defvar org-last-indirect-buffer nil)
6995 (defun org-tree-to-indirect-buffer (&optional arg)
6996 "Create indirect buffer and narrow it to current subtree.
6997 With numerical prefix ARG, go up to this level and then take that tree.
6998 If ARG is negative, go up that many levels.
6999 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7000 indirect buffer previously made with this command, to avoid proliferation of
7001 indirect buffers. However, when you call the command with a \
7002 \\[universal-argument] prefix, or
7003 when `org-indirect-buffer-display' is `new-frame', the last buffer
7004 is kept so that you can work with several indirect buffers at the same time.
7005 If `org-indirect-buffer-display' is `dedicated-frame', the \
7006 \\[universal-argument] prefix also
7007 requests that a new frame be made for the new buffer, so that the dedicated
7008 frame is not changed."
7009 (interactive "P")
7010 (let ((cbuf (current-buffer))
7011 (cwin (selected-window))
7012 (pos (point))
7013 beg end level heading ibuf)
7014 (save-excursion
7015 (org-back-to-heading t)
7016 (when (numberp arg)
7017 (setq level (org-outline-level))
7018 (if (< arg 0) (setq arg (+ level arg)))
7019 (while (> (setq level (org-outline-level)) arg)
7020 (outline-up-heading 1 t)))
7021 (setq beg (point)
7022 heading (org-get-heading))
7023 (org-end-of-subtree t t)
7024 (if (org-at-heading-p) (backward-char 1))
7025 (setq end (point)))
7026 (if (and (buffer-live-p org-last-indirect-buffer)
7027 (not (eq org-indirect-buffer-display 'new-frame))
7028 (not arg))
7029 (kill-buffer org-last-indirect-buffer))
7030 (setq ibuf (org-get-indirect-buffer cbuf)
7031 org-last-indirect-buffer ibuf)
7032 (cond
7033 ((or (eq org-indirect-buffer-display 'new-frame)
7034 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7035 (select-frame (make-frame))
7036 (delete-other-windows)
7037 (org-pop-to-buffer-same-window ibuf)
7038 (org-set-frame-title heading))
7039 ((eq org-indirect-buffer-display 'dedicated-frame)
7040 (raise-frame
7041 (select-frame (or (and org-indirect-dedicated-frame
7042 (frame-live-p org-indirect-dedicated-frame)
7043 org-indirect-dedicated-frame)
7044 (setq org-indirect-dedicated-frame (make-frame)))))
7045 (delete-other-windows)
7046 (org-pop-to-buffer-same-window ibuf)
7047 (org-set-frame-title (concat "Indirect: " heading)))
7048 ((eq org-indirect-buffer-display 'current-window)
7049 (org-pop-to-buffer-same-window ibuf))
7050 ((eq org-indirect-buffer-display 'other-window)
7051 (pop-to-buffer ibuf))
7052 (t (error "Invalid value")))
7053 (if (featurep 'xemacs)
7054 (save-excursion (org-mode) (turn-on-font-lock)))
7055 (narrow-to-region beg end)
7056 (show-all)
7057 (goto-char pos)
7058 (run-hook-with-args 'org-cycle-hook 'all)
7059 (and (window-live-p cwin) (select-window cwin))))
7061 (defun org-get-indirect-buffer (&optional buffer)
7062 (setq buffer (or buffer (current-buffer)))
7063 (let ((n 1) (base (buffer-name buffer)) bname)
7064 (while (buffer-live-p
7065 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7066 (setq n (1+ n)))
7067 (condition-case nil
7068 (make-indirect-buffer buffer bname 'clone)
7069 (error (make-indirect-buffer buffer bname)))))
7071 (defun org-set-frame-title (title)
7072 "Set the title of the current frame to the string TITLE."
7073 ;; FIXME: how to name a single frame in XEmacs???
7074 (unless (featurep 'xemacs)
7075 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7077 ;;;; Structure editing
7079 ;;; Inserting headlines
7081 (defun org-previous-line-empty-p ()
7082 (save-excursion
7083 (and (not (bobp))
7084 (or (beginning-of-line 0) t)
7085 (save-match-data
7086 (looking-at "[ \t]*$")))))
7088 (defun org-insert-heading (&optional force-heading invisible-ok)
7089 "Insert a new heading or item with same depth at point.
7090 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7091 If point is at the beginning of a headline, insert a sibling before the
7092 current headline. If point is not at the beginning, split the line,
7093 create the new headline with the text in the current line after point
7094 \(but see also the variable `org-M-RET-may-split-line').
7096 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7097 This is important for non-interactive uses of the command."
7098 (interactive "P")
7099 (if (or (= (buffer-size) 0)
7100 (and (not (save-excursion
7101 (and (ignore-errors (org-back-to-heading invisible-ok))
7102 (org-at-heading-p))))
7103 (or force-heading (not (org-in-item-p)))))
7104 (progn
7105 (insert "\n* ")
7106 (run-hooks 'org-insert-heading-hook))
7107 (when (or force-heading (not (org-insert-item)))
7108 (let* ((empty-line-p nil)
7109 (level nil)
7110 (on-heading (org-at-heading-p))
7111 (head (save-excursion
7112 (condition-case nil
7113 (progn
7114 (org-back-to-heading invisible-ok)
7115 (when (and (not on-heading)
7116 (featurep 'org-inlinetask)
7117 (integerp org-inlinetask-min-level)
7118 (>= (length (match-string 0))
7119 org-inlinetask-min-level))
7120 ;; Find a heading level before the inline task
7121 (while (and (setq level (org-up-heading-safe))
7122 (>= level org-inlinetask-min-level)))
7123 (if (org-at-heading-p)
7124 (org-back-to-heading invisible-ok)
7125 (error "This should not happen")))
7126 (setq empty-line-p (org-previous-line-empty-p))
7127 (match-string 0))
7128 (error "*"))))
7129 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7130 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7131 pos hide-previous previous-pos)
7132 (cond
7133 ((and (org-at-heading-p) (bolp)
7134 (or (bobp)
7135 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7136 ;; insert before the current line
7137 (open-line (if blank 2 1)))
7138 ((and (bolp)
7139 (not org-insert-heading-respect-content)
7140 (or (bobp)
7141 (save-excursion
7142 (backward-char 1) (not (outline-invisible-p)))))
7143 ;; insert right here
7144 nil)
7146 ;; somewhere in the line
7147 (save-excursion
7148 (setq previous-pos (point-at-bol))
7149 (end-of-line)
7150 (setq hide-previous (outline-invisible-p)))
7151 (and org-insert-heading-respect-content (org-show-subtree))
7152 (let ((split
7153 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7154 (save-excursion
7155 (let ((p (point)))
7156 (goto-char (point-at-bol))
7157 (and (looking-at org-complex-heading-regexp)
7158 (match-beginning 4)
7159 (> p (match-beginning 4)))))))
7160 tags pos)
7161 (cond
7162 (org-insert-heading-respect-content
7163 (org-end-of-subtree nil t)
7164 (when (featurep 'org-inlinetask)
7165 (while (and (not (eobp))
7166 (looking-at "\\(\\*+\\)[ \t]+")
7167 (>= (length (match-string 1))
7168 org-inlinetask-min-level))
7169 (org-end-of-subtree nil t)))
7170 (or (bolp) (newline))
7171 (or (org-previous-line-empty-p)
7172 (and blank (newline)))
7173 (open-line 1))
7174 ((org-at-heading-p)
7175 (when hide-previous
7176 (show-children)
7177 (org-show-entry))
7178 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7179 (setq tags (and (match-end 2) (match-string 2)))
7180 (and (match-end 1)
7181 (delete-region (match-beginning 1) (match-end 1)))
7182 (setq pos (point-at-bol))
7183 (or split (end-of-line 1))
7184 (delete-horizontal-space)
7185 (if (string-match "\\`\\*+\\'"
7186 (buffer-substring (point-at-bol) (point)))
7187 (insert " "))
7188 (newline (if blank 2 1))
7189 (when tags
7190 (save-excursion
7191 (goto-char pos)
7192 (end-of-line 1)
7193 (insert " " tags)
7194 (org-set-tags nil 'align))))
7196 (or split (end-of-line 1))
7197 (newline (if blank 2 1)))))))
7198 (insert head) (just-one-space)
7199 (setq pos (point))
7200 (end-of-line 1)
7201 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7202 (when (and org-insert-heading-respect-content hide-previous)
7203 (save-excursion
7204 (goto-char previous-pos)
7205 (hide-subtree)))
7206 (run-hooks 'org-insert-heading-hook)))))
7208 (defun org-get-heading (&optional no-tags no-todo)
7209 "Return the heading of the current entry, without the stars.
7210 When NO-TAGS is non-nil, don't include tags.
7211 When NO-TODO is non-nil, don't include TODO keywords."
7212 (save-excursion
7213 (org-back-to-heading t)
7214 (cond
7215 ((and no-tags no-todo)
7216 (looking-at org-complex-heading-regexp)
7217 (match-string 4))
7218 (no-tags
7219 (looking-at (concat org-outline-regexp
7220 "\\(.*?\\)"
7221 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7222 (match-string 1))
7223 (no-todo
7224 (looking-at org-todo-line-regexp)
7225 (match-string 3))
7226 (t (looking-at org-heading-regexp)
7227 (match-string 2)))))
7229 (defun org-heading-components ()
7230 "Return the components of the current heading.
7231 This is a list with the following elements:
7232 - the level as an integer
7233 - the reduced level, different if `org-odd-levels-only' is set.
7234 - the TODO keyword, or nil
7235 - the priority character, like ?A, or nil if no priority is given
7236 - the headline text itself, or the tags string if no headline text
7237 - the tags string, or nil."
7238 (save-excursion
7239 (org-back-to-heading t)
7240 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7241 (list (length (match-string 1))
7242 (org-reduced-level (length (match-string 1)))
7243 (org-match-string-no-properties 2)
7244 (and (match-end 3) (aref (match-string 3) 2))
7245 (org-match-string-no-properties 4)
7246 (org-match-string-no-properties 5)))))
7248 (defun org-get-entry ()
7249 "Get the entry text, after heading, entire subtree."
7250 (save-excursion
7251 (org-back-to-heading t)
7252 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7254 (defun org-insert-heading-after-current ()
7255 "Insert a new heading with same level as current, after current subtree."
7256 (interactive)
7257 (org-back-to-heading)
7258 (org-insert-heading)
7259 (org-move-subtree-down)
7260 (end-of-line 1))
7262 (defun org-insert-heading-respect-content ()
7263 (interactive)
7264 (let ((org-insert-heading-respect-content t))
7265 (org-insert-heading t)))
7267 (defun org-insert-todo-heading-respect-content (&optional force-state)
7268 (interactive "P")
7269 (let ((org-insert-heading-respect-content t))
7270 (org-insert-todo-heading force-state t)))
7272 (defun org-insert-todo-heading (arg &optional force-heading)
7273 "Insert a new heading with the same level and TODO state as current heading.
7274 If the heading has no TODO state, or if the state is DONE, use the first
7275 state (TODO by default). Also with prefix arg, force first state."
7276 (interactive "P")
7277 (when (or force-heading (not (org-insert-item 'checkbox)))
7278 (org-insert-heading force-heading)
7279 (save-excursion
7280 (org-back-to-heading)
7281 (outline-previous-heading)
7282 (looking-at org-todo-line-regexp))
7283 (let*
7284 ((new-mark-x
7285 (if (or arg
7286 (not (match-beginning 2))
7287 (member (match-string 2) org-done-keywords))
7288 (car org-todo-keywords-1)
7289 (match-string 2)))
7290 (new-mark
7292 (run-hook-with-args-until-success
7293 'org-todo-get-default-hook new-mark-x nil)
7294 new-mark-x)))
7295 (beginning-of-line 1)
7296 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7297 (if org-treat-insert-todo-heading-as-state-change
7298 (org-todo new-mark)
7299 (insert new-mark " "))))
7300 (when org-provide-todo-statistics
7301 (org-update-parent-todo-statistics))))
7303 (defun org-insert-subheading (arg)
7304 "Insert a new subheading and demote it.
7305 Works for outline headings and for plain lists alike."
7306 (interactive "P")
7307 (org-insert-heading arg)
7308 (cond
7309 ((org-at-heading-p) (org-do-demote))
7310 ((org-at-item-p) (org-indent-item))))
7312 (defun org-insert-todo-subheading (arg)
7313 "Insert a new subheading with TODO keyword or checkbox and demote it.
7314 Works for outline headings and for plain lists alike."
7315 (interactive "P")
7316 (org-insert-todo-heading arg)
7317 (cond
7318 ((org-at-heading-p) (org-do-demote))
7319 ((org-at-item-p) (org-indent-item))))
7321 ;;; Promotion and Demotion
7323 (defvar org-after-demote-entry-hook nil
7324 "Hook run after an entry has been demoted.
7325 The cursor will be at the beginning of the entry.
7326 When a subtree is being demoted, the hook will be called for each node.")
7328 (defvar org-after-promote-entry-hook nil
7329 "Hook run after an entry has been promoted.
7330 The cursor will be at the beginning of the entry.
7331 When a subtree is being promoted, the hook will be called for each node.")
7333 (defun org-promote-subtree ()
7334 "Promote the entire subtree.
7335 See also `org-promote'."
7336 (interactive)
7337 (save-excursion
7338 (org-with-limited-levels (org-map-tree 'org-promote)))
7339 (org-fix-position-after-promote))
7341 (defun org-demote-subtree ()
7342 "Demote the entire subtree. See `org-demote'.
7343 See also `org-promote'."
7344 (interactive)
7345 (save-excursion
7346 (org-with-limited-levels (org-map-tree 'org-demote)))
7347 (org-fix-position-after-promote))
7350 (defun org-do-promote ()
7351 "Promote the current heading higher up the tree.
7352 If the region is active in `transient-mark-mode', promote all headings
7353 in the region."
7354 (interactive)
7355 (save-excursion
7356 (if (org-region-active-p)
7357 (org-map-region 'org-promote (region-beginning) (region-end))
7358 (org-promote)))
7359 (org-fix-position-after-promote))
7361 (defun org-do-demote ()
7362 "Demote the current heading lower down the tree.
7363 If the region is active in `transient-mark-mode', demote all headings
7364 in the region."
7365 (interactive)
7366 (save-excursion
7367 (if (org-region-active-p)
7368 (org-map-region 'org-demote (region-beginning) (region-end))
7369 (org-demote)))
7370 (org-fix-position-after-promote))
7372 (defun org-fix-position-after-promote ()
7373 "Make sure that after pro/demotion cursor position is right."
7374 (let ((pos (point)))
7375 (when (save-excursion
7376 (beginning-of-line 1)
7377 (looking-at org-todo-line-regexp)
7378 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7379 (cond ((eobp) (insert " "))
7380 ((eolp) (insert " "))
7381 ((equal (char-after) ?\ ) (forward-char 1))))))
7383 (defun org-current-level ()
7384 "Return the level of the current entry, or nil if before the first headline.
7385 The level is the number of stars at the beginning of the headline."
7386 (save-excursion
7387 (org-with-limited-levels
7388 (if (ignore-errors (org-back-to-heading t))
7389 (funcall outline-level)))))
7391 (defun org-get-previous-line-level ()
7392 "Return the outline depth of the last headline before the current line.
7393 Returns 0 for the first headline in the buffer, and nil if before the
7394 first headline."
7395 (let ((current-level (org-current-level))
7396 (prev-level (when (> (line-number-at-pos) 1)
7397 (save-excursion
7398 (beginning-of-line 0)
7399 (org-current-level)))))
7400 (cond ((null current-level) nil) ; Before first headline
7401 ((null prev-level) 0) ; At first headline
7402 (prev-level))))
7404 (defun org-reduced-level (l)
7405 "Compute the effective level of a heading.
7406 This takes into account the setting of `org-odd-levels-only'."
7407 (cond
7408 ((zerop l) 0)
7409 (org-odd-levels-only (1+ (floor (/ l 2))))
7410 (t l)))
7412 (defun org-level-increment ()
7413 "Return the number of stars that will be added or removed at a
7414 time to headlines when structure editing, based on the value of
7415 `org-odd-levels-only'."
7416 (if org-odd-levels-only 2 1))
7418 (defun org-get-valid-level (level &optional change)
7419 "Rectify a level change under the influence of `org-odd-levels-only'
7420 LEVEL is a current level, CHANGE is by how much the level should be
7421 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7422 even level numbers will become the next higher odd number."
7423 (if org-odd-levels-only
7424 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7425 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7426 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7427 (max 1 (+ level (or change 0)))))
7429 (if (boundp 'define-obsolete-function-alias)
7430 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7431 (define-obsolete-function-alias 'org-get-legal-level
7432 'org-get-valid-level)
7433 (define-obsolete-function-alias 'org-get-legal-level
7434 'org-get-valid-level "23.1")))
7436 (defun org-promote ()
7437 "Promote the current heading higher up the tree.
7438 If the region is active in `transient-mark-mode', promote all headings
7439 in the region."
7440 (org-back-to-heading t)
7441 (let* ((level (save-match-data (funcall outline-level)))
7442 (after-change-functions (remove 'flyspell-after-change-function
7443 after-change-functions))
7444 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7445 (diff (abs (- level (length up-head) -1))))
7446 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7447 (replace-match up-head nil t)
7448 ;; Fixup tag positioning
7449 (and org-auto-align-tags (org-set-tags nil t))
7450 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7451 (run-hooks 'org-after-promote-entry-hook)))
7453 (defun org-demote ()
7454 "Demote the current heading lower down the tree.
7455 If the region is active in `transient-mark-mode', demote all headings
7456 in the region."
7457 (org-back-to-heading t)
7458 (let* ((level (save-match-data (funcall outline-level)))
7459 (after-change-functions (remove 'flyspell-after-change-function
7460 after-change-functions))
7461 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7462 (diff (abs (- level (length down-head) -1))))
7463 (replace-match down-head nil t)
7464 ;; Fixup tag positioning
7465 (and org-auto-align-tags (org-set-tags nil t))
7466 (if org-adapt-indentation (org-fixup-indentation diff))
7467 (run-hooks 'org-after-demote-entry-hook)))
7469 (defun org-cycle-level ()
7470 "Cycle the level of an empty headline through possible states.
7471 This goes first to child, then to parent, level, then up the hierarchy.
7472 After top level, it switches back to sibling level."
7473 (interactive)
7474 (let ((org-adapt-indentation nil))
7475 (when (org-point-at-end-of-empty-headline)
7476 (setq this-command 'org-cycle-level) ; Only needed for caching
7477 (let ((cur-level (org-current-level))
7478 (prev-level (org-get-previous-line-level)))
7479 (cond
7480 ;; If first headline in file, promote to top-level.
7481 ((= prev-level 0)
7482 (loop repeat (/ (- cur-level 1) (org-level-increment))
7483 do (org-do-promote)))
7484 ;; If same level as prev, demote one.
7485 ((= prev-level cur-level)
7486 (org-do-demote))
7487 ;; If parent is top-level, promote to top level if not already.
7488 ((= prev-level 1)
7489 (loop repeat (/ (- cur-level 1) (org-level-increment))
7490 do (org-do-promote)))
7491 ;; If top-level, return to prev-level.
7492 ((= cur-level 1)
7493 (loop repeat (/ (- prev-level 1) (org-level-increment))
7494 do (org-do-demote)))
7495 ;; If less than prev-level, promote one.
7496 ((< cur-level prev-level)
7497 (org-do-promote))
7498 ;; If deeper than prev-level, promote until higher than
7499 ;; prev-level.
7500 ((> cur-level prev-level)
7501 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7502 do (org-do-promote))))
7503 t))))
7505 (defun org-map-tree (fun)
7506 "Call FUN for every heading underneath the current one."
7507 (org-back-to-heading)
7508 (let ((level (funcall outline-level)))
7509 (save-excursion
7510 (funcall fun)
7511 (while (and (progn
7512 (outline-next-heading)
7513 (> (funcall outline-level) level))
7514 (not (eobp)))
7515 (funcall fun)))))
7517 (defun org-map-region (fun beg end)
7518 "Call FUN for every heading between BEG and END."
7519 (let ((org-ignore-region t))
7520 (save-excursion
7521 (setq end (copy-marker end))
7522 (goto-char beg)
7523 (if (and (re-search-forward org-outline-regexp-bol nil t)
7524 (< (point) end))
7525 (funcall fun))
7526 (while (and (progn
7527 (outline-next-heading)
7528 (< (point) end))
7529 (not (eobp)))
7530 (funcall fun)))))
7532 (defvar org-property-end-re) ; silence byte-compiler
7533 (defun org-fixup-indentation (diff)
7534 "Change the indentation in the current entry by DIFF.
7535 However, if any line in the current entry has no indentation, or if it
7536 would end up with no indentation after the change, nothing at all is done."
7537 (save-excursion
7538 (let ((end (save-excursion (outline-next-heading)
7539 (point-marker)))
7540 (prohibit (if (> diff 0)
7541 "^\\S-"
7542 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7543 col)
7544 (unless (save-excursion (end-of-line 1)
7545 (re-search-forward prohibit end t))
7546 (while (and (< (point) end)
7547 (re-search-forward "^[ \t]+" end t))
7548 (goto-char (match-end 0))
7549 (setq col (current-column))
7550 (if (< diff 0) (replace-match ""))
7551 (org-indent-to-column (+ diff col))))
7552 (move-marker end nil))))
7554 (defun org-convert-to-odd-levels ()
7555 "Convert an org-mode file with all levels allowed to one with odd levels.
7556 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7557 level 5 etc."
7558 (interactive)
7559 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7560 (let ((outline-level 'org-outline-level)
7561 (org-odd-levels-only nil) n)
7562 (save-excursion
7563 (goto-char (point-min))
7564 (while (re-search-forward "^\\*\\*+ " nil t)
7565 (setq n (- (length (match-string 0)) 2))
7566 (while (>= (setq n (1- n)) 0)
7567 (org-demote))
7568 (end-of-line 1))))))
7570 (defun org-convert-to-oddeven-levels ()
7571 "Convert an org-mode file with only odd levels to one with odd/even levels.
7572 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7573 file contains a section with an even level, conversion would
7574 destroy the structure of the file. An error is signaled in this
7575 case."
7576 (interactive)
7577 (goto-char (point-min))
7578 ;; First check if there are no even levels
7579 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7580 (org-show-context t)
7581 (error "Not all levels are odd in this file. Conversion not possible"))
7582 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7583 (let ((outline-regexp org-outline-regexp)
7584 (outline-level 'org-outline-level)
7585 (org-odd-levels-only nil) n)
7586 (save-excursion
7587 (goto-char (point-min))
7588 (while (re-search-forward "^\\*\\*+ " nil t)
7589 (setq n (/ (1- (length (match-string 0))) 2))
7590 (while (>= (setq n (1- n)) 0)
7591 (org-promote))
7592 (end-of-line 1))))))
7594 (defun org-tr-level (n)
7595 "Make N odd if required."
7596 (if org-odd-levels-only (1+ (/ n 2)) n))
7598 ;;; Vertical tree motion, cutting and pasting of subtrees
7600 (defun org-move-subtree-up (&optional arg)
7601 "Move the current subtree up past ARG headlines of the same level."
7602 (interactive "p")
7603 (org-move-subtree-down (- (prefix-numeric-value arg))))
7605 (defun org-move-subtree-down (&optional arg)
7606 "Move the current subtree down past ARG headlines of the same level."
7607 (interactive "p")
7608 (setq arg (prefix-numeric-value arg))
7609 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7610 'org-get-last-sibling))
7611 (ins-point (make-marker))
7612 (cnt (abs arg))
7613 (col (current-column))
7614 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7615 ;; Select the tree
7616 (org-back-to-heading)
7617 (setq beg0 (point))
7618 (save-excursion
7619 (setq ne-beg (org-back-over-empty-lines))
7620 (setq beg (point)))
7621 (save-match-data
7622 (save-excursion (outline-end-of-heading)
7623 (setq folded (outline-invisible-p)))
7624 (outline-end-of-subtree))
7625 (outline-next-heading)
7626 (setq ne-end (org-back-over-empty-lines))
7627 (setq end (point))
7628 (goto-char beg0)
7629 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7630 ;; include less whitespace
7631 (save-excursion
7632 (goto-char beg)
7633 (forward-line (- ne-beg ne-end))
7634 (setq beg (point))))
7635 ;; Find insertion point, with error handling
7636 (while (> cnt 0)
7637 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7638 (progn (goto-char beg0)
7639 (error "Cannot move past superior level or buffer limit")))
7640 (setq cnt (1- cnt)))
7641 (if (> arg 0)
7642 ;; Moving forward - still need to move over subtree
7643 (progn (org-end-of-subtree t t)
7644 (save-excursion
7645 (org-back-over-empty-lines)
7646 (or (bolp) (newline)))))
7647 (setq ne-ins (org-back-over-empty-lines))
7648 (move-marker ins-point (point))
7649 (setq txt (buffer-substring beg end))
7650 (org-save-markers-in-region beg end)
7651 (delete-region beg end)
7652 (org-remove-empty-overlays-at beg)
7653 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7654 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7655 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7656 (let ((bbb (point)))
7657 (insert-before-markers txt)
7658 (org-reinstall-markers-in-region bbb)
7659 (move-marker ins-point bbb))
7660 (or (bolp) (insert "\n"))
7661 (setq ins-end (point))
7662 (goto-char ins-point)
7663 (org-skip-whitespace)
7664 (when (and (< arg 0)
7665 (org-first-sibling-p)
7666 (> ne-ins ne-beg))
7667 ;; Move whitespace back to beginning
7668 (save-excursion
7669 (goto-char ins-end)
7670 (let ((kill-whole-line t))
7671 (kill-line (- ne-ins ne-beg)) (point)))
7672 (insert (make-string (- ne-ins ne-beg) ?\n)))
7673 (move-marker ins-point nil)
7674 (if folded
7675 (hide-subtree)
7676 (org-show-entry)
7677 (show-children)
7678 (org-cycle-hide-drawers 'children))
7679 (org-clean-visibility-after-subtree-move)
7680 ;; move back to the initial column we were at
7681 (move-to-column col)))
7683 (defvar org-subtree-clip ""
7684 "Clipboard for cut and paste of subtrees.
7685 This is actually only a copy of the kill, because we use the normal kill
7686 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7688 (defvar org-subtree-clip-folded nil
7689 "Was the last copied subtree folded?
7690 This is used to fold the tree back after pasting.")
7692 (defun org-cut-subtree (&optional n)
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 cutting it."
7696 (interactive "p")
7697 (org-copy-subtree n 'cut))
7699 (defun org-copy-subtree (&optional n cut force-store-markers)
7700 "Cut the current subtree into the clipboard.
7701 With prefix arg N, cut this many sequential subtrees.
7702 This is a short-hand for marking the subtree and then copying it.
7703 If CUT is non-nil, actually cut the subtree.
7704 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7705 of some markers in the region, even if CUT is non-nil. This is
7706 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7707 (interactive "p")
7708 (let (beg end folded (beg0 (point)))
7709 (if (org-called-interactively-p 'any)
7710 (org-back-to-heading nil) ; take what looks like a subtree
7711 (org-back-to-heading t)) ; take what is really there
7712 (org-back-over-empty-lines)
7713 (setq beg (point))
7714 (skip-chars-forward " \t\r\n")
7715 (save-match-data
7716 (save-excursion (outline-end-of-heading)
7717 (setq folded (outline-invisible-p)))
7718 (condition-case nil
7719 (org-forward-same-level (1- n) t)
7720 (error nil))
7721 (org-end-of-subtree t t))
7722 (org-back-over-empty-lines)
7723 (setq end (point))
7724 (goto-char beg0)
7725 (when (> end beg)
7726 (setq org-subtree-clip-folded folded)
7727 (when (or cut force-store-markers)
7728 (org-save-markers-in-region beg end))
7729 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7730 (setq org-subtree-clip (current-kill 0))
7731 (message "%s: Subtree(s) with %d characters"
7732 (if cut "Cut" "Copied")
7733 (length org-subtree-clip)))))
7735 (defun org-paste-subtree (&optional level tree for-yank)
7736 "Paste the clipboard as a subtree, with modification of headline level.
7737 The entire subtree is promoted or demoted in order to match a new headline
7738 level.
7740 If the cursor is at the beginning of a headline, the same level as
7741 that headline is used to paste the tree
7743 If not, the new level is derived from the *visible* headings
7744 before and after the insertion point, and taken to be the inferior headline
7745 level of the two. So if the previous visible heading is level 3 and the
7746 next is level 4 (or vice versa), level 4 will be used for insertion.
7747 This makes sure that the subtree remains an independent subtree and does
7748 not swallow low level entries.
7750 You can also force a different level, either by using a numeric prefix
7751 argument, or by inserting the heading marker by hand. For example, if the
7752 cursor is after \"*****\", then the tree will be shifted to level 5.
7754 If optional TREE is given, use this text instead of the kill ring.
7756 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7757 move back over whitespace before inserting, and move point to the end of
7758 the inserted text when done."
7759 (interactive "P")
7760 (setq tree (or tree (and kill-ring (current-kill 0))))
7761 (unless (org-kill-is-subtree-p tree)
7762 (error "%s"
7763 (substitute-command-keys
7764 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7765 (org-with-limited-levels
7766 (let* ((visp (not (outline-invisible-p)))
7767 (txt tree)
7768 (^re_ "\\(\\*+\\)[ \t]*")
7769 (old-level (if (string-match org-outline-regexp-bol txt)
7770 (- (match-end 0) (match-beginning 0) 1)
7771 -1))
7772 (force-level (cond (level (prefix-numeric-value level))
7773 ((and (looking-at "[ \t]*$")
7774 (string-match
7775 "^\\*+$" (buffer-substring
7776 (point-at-bol) (point))))
7777 (- (match-end 1) (match-beginning 1)))
7778 ((and (bolp)
7779 (looking-at org-outline-regexp))
7780 (- (match-end 0) (point) 1))
7781 (t nil)))
7782 (previous-level (save-excursion
7783 (condition-case nil
7784 (progn
7785 (outline-previous-visible-heading 1)
7786 (if (looking-at ^re_)
7787 (- (match-end 0) (match-beginning 0) 1)
7789 (error 1))))
7790 (next-level (save-excursion
7791 (condition-case nil
7792 (progn
7793 (or (looking-at org-outline-regexp)
7794 (outline-next-visible-heading 1))
7795 (if (looking-at ^re_)
7796 (- (match-end 0) (match-beginning 0) 1)
7798 (error 1))))
7799 (new-level (or force-level (max previous-level next-level)))
7800 (shift (if (or (= old-level -1)
7801 (= new-level -1)
7802 (= old-level new-level))
7804 (- new-level old-level)))
7805 (delta (if (> shift 0) -1 1))
7806 (func (if (> shift 0) 'org-demote 'org-promote))
7807 (org-odd-levels-only nil)
7808 beg end newend)
7809 ;; Remove the forced level indicator
7810 (if force-level
7811 (delete-region (point-at-bol) (point)))
7812 ;; Paste
7813 (beginning-of-line (if (bolp) 1 2))
7814 (unless for-yank (org-back-over-empty-lines))
7815 (setq beg (point))
7816 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7817 (insert-before-markers txt)
7818 (unless (string-match "\n\\'" txt) (insert "\n"))
7819 (setq newend (point))
7820 (org-reinstall-markers-in-region beg)
7821 (setq end (point))
7822 (goto-char beg)
7823 (skip-chars-forward " \t\n\r")
7824 (setq beg (point))
7825 (if (and (outline-invisible-p) visp)
7826 (save-excursion (outline-show-heading)))
7827 ;; Shift if necessary
7828 (unless (= shift 0)
7829 (save-restriction
7830 (narrow-to-region beg end)
7831 (while (not (= shift 0))
7832 (org-map-region func (point-min) (point-max))
7833 (setq shift (+ delta shift)))
7834 (goto-char (point-min))
7835 (setq newend (point-max))))
7836 (when (or (org-called-interactively-p 'interactive) for-yank)
7837 (message "Clipboard pasted as level %d subtree" new-level))
7838 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7839 kill-ring
7840 (eq org-subtree-clip (current-kill 0))
7841 org-subtree-clip-folded)
7842 ;; The tree was folded before it was killed/copied
7843 (hide-subtree))
7844 (and for-yank (goto-char newend)))))
7846 (defun org-kill-is-subtree-p (&optional txt)
7847 "Check if the current kill is an outline subtree, or a set of trees.
7848 Returns nil if kill does not start with a headline, or if the first
7849 headline level is not the largest headline level in the tree.
7850 So this will actually accept several entries of equal levels as well,
7851 which is OK for `org-paste-subtree'.
7852 If optional TXT is given, check this string instead of the current kill."
7853 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7854 (re (org-get-limited-outline-regexp))
7855 (^re (concat "^" re))
7856 (start-level (and kill
7857 (string-match
7858 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7859 kill)
7860 (- (match-end 2) (match-beginning 2) 1)))
7861 (start (1+ (or (match-beginning 2) -1))))
7862 (if (not start-level)
7863 (progn
7864 nil) ;; does not even start with a heading
7865 (catch 'exit
7866 (while (setq start (string-match ^re kill (1+ start)))
7867 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7868 (throw 'exit nil)))
7869 t))))
7871 (defvar org-markers-to-move nil
7872 "Markers that should be moved with a cut-and-paste operation.
7873 Those markers are stored together with their positions relative to
7874 the start of the region.")
7876 (defun org-save-markers-in-region (beg end)
7877 "Check markers in region.
7878 If these markers are between BEG and END, record their position relative
7879 to BEG, so that after moving the block of text, we can put the markers back
7880 into place.
7881 This function gets called just before an entry or tree gets cut from the
7882 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7883 called immediately, to move the markers with the entries."
7884 (setq org-markers-to-move nil)
7885 (when (featurep 'org-clock)
7886 (org-clock-save-markers-for-cut-and-paste beg end))
7887 (when (featurep 'org-agenda)
7888 (org-agenda-save-markers-for-cut-and-paste beg end)))
7890 (defun org-check-and-save-marker (marker beg end)
7891 "Check if MARKER is between BEG and END.
7892 If yes, remember the marker and the distance to BEG."
7893 (when (and (marker-buffer marker)
7894 (equal (marker-buffer marker) (current-buffer)))
7895 (if (and (>= marker beg) (< marker end))
7896 (push (cons marker (- marker beg)) org-markers-to-move))))
7898 (defun org-reinstall-markers-in-region (beg)
7899 "Move all remembered markers to their position relative to BEG."
7900 (mapc (lambda (x)
7901 (move-marker (car x) (+ beg (cdr x))))
7902 org-markers-to-move)
7903 (setq org-markers-to-move nil))
7905 (defun org-narrow-to-subtree ()
7906 "Narrow buffer to the current subtree."
7907 (interactive)
7908 (save-excursion
7909 (save-match-data
7910 (org-with-limited-levels
7911 (narrow-to-region
7912 (progn (org-back-to-heading t) (point))
7913 (progn (org-end-of-subtree t t)
7914 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7915 (point)))))))
7917 (defun org-narrow-to-block ()
7918 "Narrow buffer to the current block."
7919 (interactive)
7920 (let* ((case-fold-search t)
7921 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7922 "^[ \t]*#\\+end_.*")))
7923 (if blockp
7924 (narrow-to-region (car blockp) (cdr blockp))
7925 (error "Not in a block"))))
7927 (eval-when-compile
7928 (defvar org-property-drawer-re))
7930 (defvar org-property-start-re) ;; defined below
7931 (defun org-clone-subtree-with-time-shift (n &optional shift)
7932 "Clone the task (subtree) at point N times.
7933 The clones will be inserted as siblings.
7935 In interactive use, the user will be prompted for the number of
7936 clones to be produced, and for a time SHIFT, which may be a
7937 repeater as used in time stamps, for example `+3d'.
7939 When a valid repeater is given and the entry contains any time
7940 stamps, the clones will become a sequence in time, with time
7941 stamps in the subtree shifted for each clone produced. If SHIFT
7942 is nil or the empty string, time stamps will be left alone. The
7943 ID property of the original subtree is removed.
7945 If the original subtree did contain time stamps with a repeater,
7946 the following will happen:
7947 - the repeater will be removed in each clone
7948 - an additional clone will be produced, with the current, unshifted
7949 date(s) in the entry.
7950 - the original entry will be placed *after* all the clones, with
7951 repeater intact.
7952 - the start days in the repeater in the original entry will be shifted
7953 to past the last clone.
7954 In this way you can spell out a number of instances of a repeating task,
7955 and still retain the repeater to cover future instances of the task."
7956 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7957 (let (beg end template task idprop
7958 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7959 (drawer-re org-drawer-regexp))
7960 (if (not (and (integerp n) (> n 0)))
7961 (error "Invalid number of replications %s" n))
7962 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7963 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7964 shift)))
7965 (error "Invalid shift specification %s" shift))
7966 (when doshift
7967 (setq shift-n (string-to-number (match-string 1 shift))
7968 shift-what (cdr (assoc (match-string 2 shift)
7969 '(("d" . day) ("w" . week)
7970 ("m" . month) ("y" . year))))))
7971 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7972 (setq nmin 1 nmax n)
7973 (org-back-to-heading t)
7974 (setq beg (point))
7975 (setq idprop (org-entry-get nil "ID"))
7976 (org-end-of-subtree t t)
7977 (or (bolp) (insert "\n"))
7978 (setq end (point))
7979 (setq template (buffer-substring beg end))
7980 (when (and doshift
7981 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7982 (delete-region beg end)
7983 (setq end beg)
7984 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7985 (goto-char end)
7986 (loop for n from nmin to nmax do
7987 ;; prepare clone
7988 (with-temp-buffer
7989 (insert template)
7990 (org-mode)
7991 (goto-char (point-min))
7992 (org-show-subtree)
7993 (and idprop (if org-clone-delete-id
7994 (org-entry-delete nil "ID")
7995 (org-id-get-create t)))
7996 (unless (= n 0)
7997 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7998 (kill-whole-line))
7999 (goto-char (point-min))
8000 (while (re-search-forward drawer-re nil t)
8001 (mapc (lambda (d)
8002 (org-remove-empty-drawer-at d (point))) org-drawers)))
8003 (goto-char (point-min))
8004 (when doshift
8005 (while (re-search-forward org-ts-regexp-both nil t)
8006 (org-timestamp-change (* n shift-n) shift-what))
8007 (unless (= n n-no-remove)
8008 (goto-char (point-min))
8009 (while (re-search-forward org-ts-regexp nil t)
8010 (save-excursion
8011 (goto-char (match-beginning 0))
8012 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8013 (delete-region (match-beginning 1) (match-end 1)))))))
8014 (setq task (buffer-string)))
8015 (insert task))
8016 (goto-char beg)))
8018 ;;; Outline Sorting
8020 (defun org-sort (with-case)
8021 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8022 Optional argument WITH-CASE means sort case-sensitively."
8023 (interactive "P")
8024 (cond
8025 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8026 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8028 (org-call-with-arg 'org-sort-entries with-case))))
8030 (defun org-sort-remove-invisible (s)
8031 (remove-text-properties 0 (length s) org-rm-props s)
8032 (while (string-match org-bracket-link-regexp s)
8033 (setq s (replace-match (if (match-end 2)
8034 (match-string 3 s)
8035 (match-string 1 s)) t t s)))
8038 (defvar org-priority-regexp) ; defined later in the file
8040 (defvar org-after-sorting-entries-or-items-hook nil
8041 "Hook that is run after a bunch of entries or items have been sorted.
8042 When children are sorted, the cursor is in the parent line when this
8043 hook gets called. When a region or a plain list is sorted, the cursor
8044 will be in the first entry of the sorted region/list.")
8046 (defun org-sort-entries
8047 (&optional with-case sorting-type getkey-func compare-func property)
8048 "Sort entries on a certain level of an outline tree.
8049 If there is an active region, the entries in the region are sorted.
8050 Else, if the cursor is before the first entry, sort the top-level items.
8051 Else, the children of the entry at point are sorted.
8053 Sorting can be alphabetically, numerically, by date/time as given by
8054 a time stamp, by a property or by priority.
8056 The command prompts for the sorting type unless it has been given to the
8057 function through the SORTING-TYPE argument, which needs to be a character,
8058 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8059 precise meaning of each character:
8061 n Numerically, by converting the beginning of the entry/item to a number.
8062 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8063 t By date/time, either the first active time stamp in the entry, or, if
8064 none exist, by the first inactive one.
8065 s By the scheduled date/time.
8066 d By deadline date/time.
8067 c By creation time, which is assumed to be the first inactive time stamp
8068 at the beginning of a line.
8069 p By priority according to the cookie.
8070 r By the value of a property.
8072 Capital letters will reverse the sort order.
8074 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8075 called with point at the beginning of the record. It must return either
8076 a string or a number that should serve as the sorting key for that record.
8078 Comparing entries ignores case by default. However, with an optional argument
8079 WITH-CASE, the sorting considers case as well."
8080 (interactive "P")
8081 (let ((case-func (if with-case 'identity 'downcase))
8082 start beg end stars re re2
8083 txt what tmp)
8084 ;; Find beginning and end of region to sort
8085 (cond
8086 ((org-region-active-p)
8087 ;; we will sort the region
8088 (setq end (region-end)
8089 what "region")
8090 (goto-char (region-beginning))
8091 (if (not (org-at-heading-p)) (outline-next-heading))
8092 (setq start (point)))
8093 ((or (org-at-heading-p)
8094 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8095 ;; we will sort the children of the current headline
8096 (org-back-to-heading)
8097 (setq start (point)
8098 end (progn (org-end-of-subtree t t)
8099 (or (bolp) (insert "\n"))
8100 (org-back-over-empty-lines)
8101 (point))
8102 what "children")
8103 (goto-char start)
8104 (show-subtree)
8105 (outline-next-heading))
8107 ;; we will sort the top-level entries in this file
8108 (goto-char (point-min))
8109 (or (org-at-heading-p) (outline-next-heading))
8110 (setq start (point))
8111 (goto-char (point-max))
8112 (beginning-of-line 1)
8113 (when (looking-at ".*?\\S-")
8114 ;; File ends in a non-white line
8115 (end-of-line 1)
8116 (insert "\n"))
8117 (setq end (point-max))
8118 (setq what "top-level")
8119 (goto-char start)
8120 (show-all)))
8122 (setq beg (point))
8123 (if (>= beg end) (error "Nothing to sort"))
8125 (looking-at "\\(\\*+\\)")
8126 (setq stars (match-string 1)
8127 re (concat "^" (regexp-quote stars) " +")
8128 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8129 txt (buffer-substring beg end))
8130 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8131 (if (and (not (equal stars "*")) (string-match re2 txt))
8132 (error "Region to sort contains a level above the first entry"))
8134 (unless sorting-type
8135 (message
8136 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8137 [t]ime [s]cheduled [d]eadline [c]reated
8138 A/N/T/S/D/C/P/O/F means reversed:"
8139 what)
8140 (setq sorting-type (read-char-exclusive))
8142 (and (= (downcase sorting-type) ?f)
8143 (setq getkey-func
8144 (org-icompleting-read "Sort using function: "
8145 obarray 'fboundp t nil nil))
8146 (setq getkey-func (intern getkey-func)))
8148 (and (= (downcase sorting-type) ?r)
8149 (setq property
8150 (org-icompleting-read "Property: "
8151 (mapcar 'list (org-buffer-property-keys t))
8152 nil t))))
8154 (message "Sorting entries...")
8156 (save-restriction
8157 (narrow-to-region start end)
8158 (let ((dcst (downcase sorting-type))
8159 (case-fold-search nil)
8160 (now (current-time)))
8161 (sort-subr
8162 (/= dcst sorting-type)
8163 ;; This function moves to the beginning character of the "record" to
8164 ;; be sorted.
8165 (lambda nil
8166 (if (re-search-forward re nil t)
8167 (goto-char (match-beginning 0))
8168 (goto-char (point-max))))
8169 ;; This function moves to the last character of the "record" being
8170 ;; sorted.
8171 (lambda nil
8172 (save-match-data
8173 (condition-case nil
8174 (outline-forward-same-level 1)
8175 (error
8176 (goto-char (point-max))))))
8177 ;; This function returns the value that gets sorted against.
8178 (lambda nil
8179 (cond
8180 ((= dcst ?n)
8181 (if (looking-at org-complex-heading-regexp)
8182 (string-to-number (match-string 4))
8183 nil))
8184 ((= dcst ?a)
8185 (if (looking-at org-complex-heading-regexp)
8186 (funcall case-func (match-string 4))
8187 nil))
8188 ((= dcst ?t)
8189 (let ((end (save-excursion (outline-next-heading) (point))))
8190 (if (or (re-search-forward org-ts-regexp end t)
8191 (re-search-forward org-ts-regexp-both end t))
8192 (org-time-string-to-seconds (match-string 0))
8193 (org-float-time now))))
8194 ((= dcst ?c)
8195 (let ((end (save-excursion (outline-next-heading) (point))))
8196 (if (re-search-forward
8197 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8198 end t)
8199 (org-time-string-to-seconds (match-string 0))
8200 (org-float-time now))))
8201 ((= dcst ?s)
8202 (let ((end (save-excursion (outline-next-heading) (point))))
8203 (if (re-search-forward org-scheduled-time-regexp end t)
8204 (org-time-string-to-seconds (match-string 1))
8205 (org-float-time now))))
8206 ((= dcst ?d)
8207 (let ((end (save-excursion (outline-next-heading) (point))))
8208 (if (re-search-forward org-deadline-time-regexp end t)
8209 (org-time-string-to-seconds (match-string 1))
8210 (org-float-time now))))
8211 ((= dcst ?p)
8212 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8213 (string-to-char (match-string 2))
8214 org-default-priority))
8215 ((= dcst ?r)
8216 (or (org-entry-get nil property) ""))
8217 ((= dcst ?o)
8218 (if (looking-at org-complex-heading-regexp)
8219 (- 9999 (length (member (match-string 2)
8220 org-todo-keywords-1)))))
8221 ((= dcst ?f)
8222 (if getkey-func
8223 (progn
8224 (setq tmp (funcall getkey-func))
8225 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8226 tmp)
8227 (error "Invalid key function `%s'" getkey-func)))
8228 (t (error "Invalid sorting type `%c'" sorting-type))))
8230 (cond
8231 ((= dcst ?a) 'string<)
8232 ((= dcst ?f) compare-func)
8233 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8234 (t nil)))))
8235 (run-hooks 'org-after-sorting-entries-or-items-hook)
8236 (message "Sorting entries...done")))
8238 (defun org-do-sort (table what &optional with-case sorting-type)
8239 "Sort TABLE of WHAT according to SORTING-TYPE.
8240 The user will be prompted for the SORTING-TYPE if the call to this
8241 function does not specify it. WHAT is only for the prompt, to indicate
8242 what is being sorted. The sorting key will be extracted from
8243 the car of the elements of the table.
8244 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8245 (unless sorting-type
8246 (message
8247 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8248 what)
8249 (setq sorting-type (read-char-exclusive)))
8250 (let ((dcst (downcase sorting-type))
8251 extractfun comparefun)
8252 ;; Define the appropriate functions
8253 (cond
8254 ((= dcst ?n)
8255 (setq extractfun 'string-to-number
8256 comparefun (if (= dcst sorting-type) '< '>)))
8257 ((= dcst ?a)
8258 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8259 (lambda(x) (downcase (org-sort-remove-invisible x))))
8260 comparefun (if (= dcst sorting-type)
8261 'string<
8262 (lambda (a b) (and (not (string< a b))
8263 (not (string= a b)))))))
8264 ((= dcst ?t)
8265 (setq extractfun
8266 (lambda (x)
8267 (if (or (string-match org-ts-regexp x)
8268 (string-match org-ts-regexp-both x))
8269 (org-float-time
8270 (org-time-string-to-time (match-string 0 x)))
8272 comparefun (if (= dcst sorting-type) '< '>)))
8273 (t (error "Invalid sorting type `%c'" sorting-type)))
8275 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8276 table)
8277 (lambda (a b) (funcall comparefun (car a) (car b))))))
8280 ;;; The orgstruct minor mode
8282 ;; Define a minor mode which can be used in other modes in order to
8283 ;; integrate the org-mode structure editing commands.
8285 ;; This is really a hack, because the org-mode structure commands use
8286 ;; keys which normally belong to the major mode. Here is how it
8287 ;; works: The minor mode defines all the keys necessary to operate the
8288 ;; structure commands, but wraps the commands into a function which
8289 ;; tests if the cursor is currently at a headline or a plain list
8290 ;; item. If that is the case, the structure command is used,
8291 ;; temporarily setting many Org-mode variables like regular
8292 ;; expressions for filling etc. However, when any of those keys is
8293 ;; used at a different location, function uses `key-binding' to look
8294 ;; up if the key has an associated command in another currently active
8295 ;; keymap (minor modes, major mode, global), and executes that
8296 ;; command. There might be problems if any of the keys is otherwise
8297 ;; used as a prefix key.
8299 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8300 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8301 ;; addresses this by checking explicitly for both bindings.
8303 (defvar orgstruct-mode-map (make-sparse-keymap)
8304 "Keymap for the minor `orgstruct-mode'.")
8306 (defvar org-local-vars nil
8307 "List of local variables, for use by `orgstruct-mode'.")
8309 ;;;###autoload
8310 (define-minor-mode orgstruct-mode
8311 "Toggle the minor mode `orgstruct-mode'.
8312 This mode is for using Org-mode structure commands in other
8313 modes. The following keys behave as if Org-mode were active, if
8314 the cursor is on a headline, or on a plain list item (both as
8315 defined by Org-mode).
8317 M-up Move entry/item up
8318 M-down Move entry/item down
8319 M-left Promote
8320 M-right Demote
8321 M-S-up Move entry/item up
8322 M-S-down Move entry/item down
8323 M-S-left Promote subtree
8324 M-S-right Demote subtree
8325 M-q Fill paragraph and items like in Org-mode
8326 C-c ^ Sort entries
8327 C-c - Cycle list bullet
8328 TAB Cycle item visibility
8329 M-RET Insert new heading/item
8330 S-M-RET Insert new TODO heading / Checkbox item
8331 C-c C-c Set tags / toggle checkbox"
8332 nil " OrgStruct" nil
8333 (org-load-modules-maybe)
8334 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8336 ;;;###autoload
8337 (defun turn-on-orgstruct ()
8338 "Unconditionally turn on `orgstruct-mode'."
8339 (orgstruct-mode 1))
8341 (defun orgstruct++-mode (&optional arg)
8342 "Toggle `orgstruct-mode', the enhanced version of it.
8343 In addition to setting orgstruct-mode, this also exports all indentation
8344 and autofilling variables from org-mode into the buffer. It will also
8345 recognize item context in multiline items.
8346 Note that turning off orgstruct-mode will *not* remove the
8347 indentation/paragraph settings. This can only be done by refreshing the
8348 major mode, for example with \\[normal-mode]."
8349 (interactive "P")
8350 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8351 (if (< arg 1)
8352 (orgstruct-mode -1)
8353 (orgstruct-mode 1)
8354 (let (var val)
8355 (mapc
8356 (lambda (x)
8357 (when (string-match
8358 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8359 (symbol-name (car x)))
8360 (setq var (car x) val (nth 1 x))
8361 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8362 org-local-vars)
8363 (org-set-local 'orgstruct-is-++ t))))
8365 (defvar orgstruct-is-++ nil
8366 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8367 (make-variable-buffer-local 'orgstruct-is-++)
8369 ;;;###autoload
8370 (defun turn-on-orgstruct++ ()
8371 "Unconditionally turn on `orgstruct++-mode'."
8372 (orgstruct++-mode 1))
8374 (defun orgstruct-error ()
8375 "Error when there is no default binding for a structure key."
8376 (interactive)
8377 (error "This key has no function outside structure elements"))
8379 (defun orgstruct-setup ()
8380 "Setup orgstruct keymaps."
8381 (let ((nfunc 0)
8382 (bindings
8383 (list
8384 '([(meta up)] org-metaup)
8385 '([(meta down)] org-metadown)
8386 '([(meta left)] org-metaleft)
8387 '([(meta right)] org-metaright)
8388 '([(meta shift up)] org-shiftmetaup)
8389 '([(meta shift down)] org-shiftmetadown)
8390 '([(meta shift left)] org-shiftmetaleft)
8391 '([(meta shift right)] org-shiftmetaright)
8392 '([?\e (up)] org-metaup)
8393 '([?\e (down)] org-metadown)
8394 '([?\e (left)] org-metaleft)
8395 '([?\e (right)] org-metaright)
8396 '([?\e (shift up)] org-shiftmetaup)
8397 '([?\e (shift down)] org-shiftmetadown)
8398 '([?\e (shift left)] org-shiftmetaleft)
8399 '([?\e (shift right)] org-shiftmetaright)
8400 '([(shift up)] org-shiftup)
8401 '([(shift down)] org-shiftdown)
8402 '([(shift left)] org-shiftleft)
8403 '([(shift right)] org-shiftright)
8404 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8405 '("\M-q" fill-paragraph)
8406 '("\C-c^" org-sort)
8407 '("\C-c-" org-cycle-list-bullet)))
8408 elt key fun cmd)
8409 (while (setq elt (pop bindings))
8410 (setq nfunc (1+ nfunc))
8411 (setq key (org-key (car elt))
8412 fun (nth 1 elt)
8413 cmd (orgstruct-make-binding fun nfunc key))
8414 (org-defkey orgstruct-mode-map key cmd))
8416 ;; Special treatment needed for TAB and RET
8417 (org-defkey orgstruct-mode-map [(tab)]
8418 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8419 (org-defkey orgstruct-mode-map "\C-i"
8420 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8422 (org-defkey orgstruct-mode-map "\M-\C-m"
8423 (orgstruct-make-binding 'org-insert-heading 105
8424 "\M-\C-m" [(meta return)]))
8425 (org-defkey orgstruct-mode-map [(meta return)]
8426 (orgstruct-make-binding 'org-insert-heading 106
8427 [(meta return)] "\M-\C-m"))
8429 (org-defkey orgstruct-mode-map [(shift meta return)]
8430 (orgstruct-make-binding 'org-insert-todo-heading 107
8431 [(meta return)] "\M-\C-m"))
8433 (org-defkey orgstruct-mode-map "\e\C-m"
8434 (orgstruct-make-binding 'org-insert-heading 108
8435 "\e\C-m" [?\e (return)]))
8436 (org-defkey orgstruct-mode-map [?\e (return)]
8437 (orgstruct-make-binding 'org-insert-heading 109
8438 [?\e (return)] "\e\C-m"))
8439 (org-defkey orgstruct-mode-map [?\e (shift return)]
8440 (orgstruct-make-binding 'org-insert-todo-heading 110
8441 [?\e (return)] "\e\C-m"))
8443 (unless org-local-vars
8444 (setq org-local-vars (org-get-local-variables)))
8448 (defun orgstruct-make-binding (fun n &rest keys)
8449 "Create a function for binding in the structure minor mode.
8450 FUN is the command to call inside a table. N is used to create a unique
8451 command name. KEYS are keys that should be checked in for a command
8452 to execute outside of tables."
8453 (eval
8454 (list 'defun
8455 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8456 '(arg)
8457 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8458 "Outside of structure, run the binding of `"
8459 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8460 "'.")
8461 '(interactive "p")
8462 (list 'if
8463 `(org-context-p 'headline 'item
8464 (and orgstruct-is-++
8465 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8466 'item-body))
8467 (list 'org-run-like-in-org-mode (list 'quote fun))
8468 (list 'let '(orgstruct-mode)
8469 (list 'call-interactively
8470 (append '(or)
8471 (mapcar (lambda (k)
8472 (list 'key-binding k))
8473 keys)
8474 '('orgstruct-error))))))))
8476 (defun org-context-p (&rest contexts)
8477 "Check if local context is any of CONTEXTS.
8478 Possible values in the list of contexts are `table', `headline', and `item'."
8479 (let ((pos (point)))
8480 (goto-char (point-at-bol))
8481 (prog1 (or (and (memq 'table contexts)
8482 (looking-at "[ \t]*|"))
8483 (and (memq 'headline contexts)
8484 (looking-at org-outline-regexp))
8485 (and (memq 'item contexts)
8486 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8487 (and (memq 'item-body contexts)
8488 (org-in-item-p)))
8489 (goto-char pos))))
8491 (defun org-get-local-variables ()
8492 "Return a list of all local variables in an org-mode buffer."
8493 (let (varlist)
8494 (with-current-buffer (get-buffer-create "*Org tmp*")
8495 (erase-buffer)
8496 (org-mode)
8497 (setq varlist (buffer-local-variables)))
8498 (kill-buffer "*Org tmp*")
8499 (delq nil
8500 (mapcar
8501 (lambda (x)
8502 (setq x
8503 (if (symbolp x)
8504 (list x)
8505 (list (car x) (list 'quote (cdr x)))))
8506 (if (string-match
8507 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8508 (symbol-name (car x)))
8509 x nil))
8510 varlist))))
8512 (defun org-clone-local-variables (from-buffer &optional regexp)
8513 "Clone local variables from FROM-BUFFER.
8514 Optional argument REGEXP selects variables to clone."
8515 (mapc
8516 (lambda (pair)
8517 (and (symbolp (car pair))
8518 (or (null regexp)
8519 (string-match regexp (symbol-name (car pair))))
8520 (set (make-local-variable (car pair))
8521 (cdr pair))))
8522 (buffer-local-variables from-buffer)))
8524 ;;;###autoload
8525 (defun org-run-like-in-org-mode (cmd)
8526 "Run a command, pretending that the current buffer is in Org-mode.
8527 This will temporarily bind local variables that are typically bound in
8528 Org-mode to the values they have in Org-mode, and then interactively
8529 call CMD."
8530 (org-load-modules-maybe)
8531 (unless org-local-vars
8532 (setq org-local-vars (org-get-local-variables)))
8533 (eval (list 'let org-local-vars
8534 (list 'call-interactively (list 'quote cmd)))))
8536 ;;;; Archiving
8538 (defun org-get-category (&optional pos force-refresh)
8539 "Get the category applying to position POS."
8540 (save-match-data
8541 (if force-refresh (org-refresh-category-properties))
8542 (let ((pos (or pos (point))))
8543 (or (get-text-property pos 'org-category)
8544 (progn (org-refresh-category-properties)
8545 (get-text-property pos 'org-category))))))
8547 (defun org-refresh-category-properties ()
8548 "Refresh category text properties in the buffer."
8549 (let ((def-cat (cond
8550 ((null org-category)
8551 (if buffer-file-name
8552 (file-name-sans-extension
8553 (file-name-nondirectory buffer-file-name))
8554 "???"))
8555 ((symbolp org-category) (symbol-name org-category))
8556 (t org-category)))
8557 beg end cat pos optionp)
8558 (org-unmodified
8559 (save-excursion
8560 (save-restriction
8561 (widen)
8562 (goto-char (point-min))
8563 (put-text-property (point) (point-max) 'org-category def-cat)
8564 (while (re-search-forward
8565 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8566 (setq pos (match-end 0)
8567 optionp (equal (char-after (match-beginning 0)) ?#)
8568 cat (org-trim (match-string 2)))
8569 (if optionp
8570 (setq beg (point-at-bol) end (point-max))
8571 (org-back-to-heading t)
8572 (setq beg (point) end (org-end-of-subtree t t)))
8573 (put-text-property beg end 'org-category cat)
8574 (put-text-property beg end 'org-category-position beg)
8575 (goto-char pos)))))))
8578 ;;;; Link Stuff
8580 ;;; Link abbreviations
8582 (defun org-link-expand-abbrev (link)
8583 "Apply replacements as defined in `org-link-abbrev-alist'."
8584 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8585 (let* ((key (match-string 1 link))
8586 (as (or (assoc key org-link-abbrev-alist-local)
8587 (assoc key org-link-abbrev-alist)))
8588 (tag (and (match-end 2) (match-string 3 link)))
8589 rpl)
8590 (if (not as)
8591 link
8592 (setq rpl (cdr as))
8593 (cond
8594 ((symbolp rpl) (funcall rpl tag))
8595 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8596 ((string-match "%h" rpl)
8597 (replace-match (url-hexify-string (or tag "")) t t rpl))
8598 (t (concat rpl tag)))))
8599 link))
8601 ;;; Storing and inserting links
8603 (defvar org-insert-link-history nil
8604 "Minibuffer history for links inserted with `org-insert-link'.")
8606 (defvar org-stored-links nil
8607 "Contains the links stored with `org-store-link'.")
8609 (defvar org-store-link-plist nil
8610 "Plist with info about the most recently link created with `org-store-link'.")
8612 (defvar org-link-protocols nil
8613 "Link protocols added to Org-mode using `org-add-link-type'.")
8615 (defvar org-store-link-functions nil
8616 "List of functions that are called to create and store a link.
8617 Each function will be called in turn until one returns a non-nil
8618 value. Each function should check if it is responsible for creating
8619 this link (for example by looking at the major mode).
8620 If not, it must exit and return nil.
8621 If yes, it should return a non-nil value after a calling
8622 `org-store-link-props' with a list of properties and values.
8623 Special properties are:
8625 :type The link prefix, like \"http\". This must be given.
8626 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8627 This is obligatory as well.
8628 :description Optional default description for the second pair
8629 of brackets in an Org-mode link. The user can still change
8630 this when inserting this link into an Org-mode buffer.
8632 In addition to these, any additional properties can be specified
8633 and then used in remember templates.")
8635 (defun org-add-link-type (type &optional follow export)
8636 "Add TYPE to the list of `org-link-types'.
8637 Re-compute all regular expressions depending on `org-link-types'
8639 FOLLOW and EXPORT are two functions.
8641 FOLLOW should take the link path as the single argument and do whatever
8642 is necessary to follow the link, for example find a file or display
8643 a mail message.
8645 EXPORT should format the link path for export to one of the export formats.
8646 It should be a function accepting three arguments:
8648 path the path of the link, the text after the prefix (like \"http:\")
8649 desc the description of the link, if any, or a description added by
8650 org-export-normalize-links if there is none
8651 format the export format, a symbol like `html' or `latex' or `ascii'..
8653 The function may use the FORMAT information to return different values
8654 depending on the format. The return value will be put literally into
8655 the exported file. If the return value is nil, this means Org should
8656 do what it normally does with links which do not have EXPORT defined.
8658 Org-mode has a built-in default for exporting links. If you are happy with
8659 this default, there is no need to define an export function for the link
8660 type. For a simple example of an export function, see `org-bbdb.el'."
8661 (add-to-list 'org-link-types type t)
8662 (org-make-link-regexps)
8663 (if (assoc type org-link-protocols)
8664 (setcdr (assoc type org-link-protocols) (list follow export))
8665 (push (list type follow export) org-link-protocols)))
8667 (defvar org-agenda-buffer-name)
8669 ;;;###autoload
8670 (defun org-store-link (arg)
8671 "\\<org-mode-map>Store an org-link to the current location.
8672 This link is added to `org-stored-links' and can later be inserted
8673 into an org-buffer with \\[org-insert-link].
8675 For some link types, a prefix arg is interpreted:
8676 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8677 For file links, arg negates `org-context-in-file-links'."
8678 (interactive "P")
8679 (org-load-modules-maybe)
8680 (setq org-store-link-plist nil) ; reset
8681 (org-with-limited-levels
8682 (let (link cpltxt desc description search txt custom-id agenda-link)
8683 (cond
8685 ((run-hook-with-args-until-success 'org-store-link-functions)
8686 (setq link (plist-get org-store-link-plist :link)
8687 desc (or (plist-get org-store-link-plist :description) link)))
8689 ((org-src-edit-buffer-p)
8690 (let (label gc)
8691 (while (or (not label)
8692 (save-excursion
8693 (save-restriction
8694 (widen)
8695 (goto-char (point-min))
8696 (re-search-forward
8697 (regexp-quote (format org-coderef-label-format label))
8698 nil t))))
8699 (when label (message "Label exists already") (sit-for 2))
8700 (setq label (read-string "Code line label: " label)))
8701 (end-of-line 1)
8702 (setq link (format org-coderef-label-format label))
8703 (setq gc (- 79 (length link)))
8704 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8705 (insert link)
8706 (setq link (concat "(" label ")") desc nil)))
8708 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8709 ;; We are in the agenda, link to referenced location
8710 (let ((m (or (get-text-property (point) 'org-hd-marker)
8711 (get-text-property (point) 'org-marker))))
8712 (when m
8713 (org-with-point-at m
8714 (setq agenda-link
8715 (if (org-called-interactively-p 'any)
8716 (call-interactively 'org-store-link)
8717 (org-store-link nil)))))))
8719 ((eq major-mode 'calendar-mode)
8720 (let ((cd (calendar-cursor-to-date)))
8721 (setq link
8722 (format-time-string
8723 (car org-time-stamp-formats)
8724 (apply 'encode-time
8725 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8726 nil nil nil))))
8727 (org-store-link-props :type "calendar" :date cd)))
8729 ((eq major-mode 'w3-mode)
8730 (setq cpltxt (if (and (buffer-name)
8731 (not (string-match "Untitled" (buffer-name))))
8732 (buffer-name)
8733 (url-view-url t))
8734 link (org-make-link (url-view-url t)))
8735 (org-store-link-props :type "w3" :url (url-view-url t)))
8737 ((eq major-mode 'w3m-mode)
8738 (setq cpltxt (or w3m-current-title w3m-current-url)
8739 link (org-make-link w3m-current-url))
8740 (org-store-link-props :type "w3m" :url (url-view-url t)))
8742 ((setq search (run-hook-with-args-until-success
8743 'org-create-file-search-functions))
8744 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8745 "::" search))
8746 (setq cpltxt (or description link)))
8748 ((eq major-mode 'image-mode)
8749 (setq cpltxt (concat "file:"
8750 (abbreviate-file-name buffer-file-name))
8751 link (org-make-link cpltxt))
8752 (org-store-link-props :type "image" :file buffer-file-name))
8754 ((eq major-mode 'dired-mode)
8755 ;; link to the file in the current line
8756 (let ((file (dired-get-filename nil t)))
8757 (setq file (if file
8758 (abbreviate-file-name
8759 (expand-file-name (dired-get-filename nil t)))
8760 ;; otherwise, no file so use current directory.
8761 default-directory))
8762 (setq cpltxt (concat "file:" file)
8763 link (org-make-link cpltxt))))
8765 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8766 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8767 (cond
8768 ((org-in-regexp "<<\\(.*?\\)>>")
8769 (setq cpltxt
8770 (concat "file:"
8771 (abbreviate-file-name
8772 (buffer-file-name (buffer-base-buffer)))
8773 "::" (match-string 1))
8774 link (org-make-link cpltxt)))
8775 ((and (featurep 'org-id)
8776 (or (eq org-link-to-org-use-id t)
8777 (and (eq org-link-to-org-use-id 'create-if-interactive)
8778 (org-called-interactively-p 'any))
8779 (and (eq org-link-to-org-use-id
8780 'create-if-interactive-and-no-custom-id)
8781 (org-called-interactively-p 'any)
8782 (not custom-id))
8783 (and org-link-to-org-use-id
8784 (org-entry-get nil "ID"))))
8785 ;; We can make a link using the ID.
8786 (setq link (condition-case nil
8787 (prog1 (org-id-store-link)
8788 (setq desc (plist-get org-store-link-plist
8789 :description)))
8790 (error
8791 ;; probably before first headline, link to file only
8792 (concat "file:"
8793 (abbreviate-file-name
8794 (buffer-file-name (buffer-base-buffer))))))))
8796 ;; Just link to current headline
8797 (setq cpltxt (concat "file:"
8798 (abbreviate-file-name
8799 (buffer-file-name (buffer-base-buffer)))))
8800 ;; Add a context search string
8801 (when (org-xor org-context-in-file-links arg)
8802 (setq txt (cond
8803 ((org-at-heading-p) nil)
8804 ((org-region-active-p)
8805 (buffer-substring (region-beginning) (region-end)))
8806 (t nil)))
8807 (when (or (null txt) (string-match "\\S-" txt))
8808 (setq cpltxt
8809 (concat cpltxt "::"
8810 (condition-case nil
8811 (org-make-org-heading-search-string txt)
8812 (error "")))
8813 desc (or (nth 4 (ignore-errors
8814 (org-heading-components))) "NONE"))))
8815 (if (string-match "::\\'" cpltxt)
8816 (setq cpltxt (substring cpltxt 0 -2)))
8817 (setq link (org-make-link cpltxt)))))
8819 ((buffer-file-name (buffer-base-buffer))
8820 ;; Just link to this file here.
8821 (setq cpltxt (concat "file:"
8822 (abbreviate-file-name
8823 (buffer-file-name (buffer-base-buffer)))))
8824 ;; Add a context string
8825 (when (org-xor org-context-in-file-links arg)
8826 (setq txt (if (org-region-active-p)
8827 (buffer-substring (region-beginning) (region-end))
8828 (buffer-substring (point-at-bol) (point-at-eol))))
8829 ;; Only use search option if there is some text.
8830 (when (string-match "\\S-" txt)
8831 (setq cpltxt
8832 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8833 desc "NONE")))
8834 (setq link (org-make-link cpltxt)))
8836 ((org-called-interactively-p 'interactive)
8837 (error "Cannot link to a buffer which is not visiting a file"))
8839 (t (setq link nil)))
8841 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8842 (setq link (or link cpltxt)
8843 desc (or desc cpltxt))
8844 (if (equal desc "NONE") (setq desc nil))
8846 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8847 (progn
8848 (setq org-stored-links
8849 (cons (list link desc) org-stored-links))
8850 (message "Stored: %s" (or desc link))
8851 (when custom-id
8852 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8853 "::#" custom-id))
8854 (setq org-stored-links
8855 (cons (list link desc) org-stored-links))))
8856 (or agenda-link (and link (org-make-link-string link desc)))))))
8858 (defun org-store-link-props (&rest plist)
8859 "Store link properties, extract names and addresses."
8860 (let (x adr)
8861 (when (setq x (plist-get plist :from))
8862 (setq adr (mail-extract-address-components x))
8863 (setq plist (plist-put plist :fromname (car adr)))
8864 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8865 (when (setq x (plist-get plist :to))
8866 (setq adr (mail-extract-address-components x))
8867 (setq plist (plist-put plist :toname (car adr)))
8868 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8869 (let ((from (plist-get plist :from))
8870 (to (plist-get plist :to)))
8871 (when (and from to org-from-is-user-regexp)
8872 (setq plist
8873 (plist-put plist :fromto
8874 (if (string-match org-from-is-user-regexp from)
8875 (concat "to %t")
8876 (concat "from %f"))))))
8877 (setq org-store-link-plist plist))
8879 (defun org-add-link-props (&rest plist)
8880 "Add these properties to the link property list."
8881 (let (key value)
8882 (while plist
8883 (setq key (pop plist) value (pop plist))
8884 (setq org-store-link-plist
8885 (plist-put org-store-link-plist key value)))))
8887 (defun org-email-link-description (&optional fmt)
8888 "Return the description part of an email link.
8889 This takes information from `org-store-link-plist' and formats it
8890 according to FMT (default from `org-email-link-description-format')."
8891 (setq fmt (or fmt org-email-link-description-format))
8892 (let* ((p org-store-link-plist)
8893 (to (plist-get p :toaddress))
8894 (from (plist-get p :fromaddress))
8895 (table
8896 (list
8897 (cons "%c" (plist-get p :fromto))
8898 (cons "%F" (plist-get p :from))
8899 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8900 (cons "%T" (plist-get p :to))
8901 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8902 (cons "%s" (plist-get p :subject))
8903 (cons "%d" (plist-get p :date))
8904 (cons "%m" (plist-get p :message-id)))))
8905 (when (string-match "%c" fmt)
8906 ;; Check if the user wrote this message
8907 (if (and org-from-is-user-regexp from to
8908 (save-match-data (string-match org-from-is-user-regexp from)))
8909 (setq fmt (replace-match "to %t" t t fmt))
8910 (setq fmt (replace-match "from %f" t t fmt))))
8911 (org-replace-escapes fmt table)))
8913 (defun org-make-org-heading-search-string (&optional string heading)
8914 "Make search string for STRING or current headline."
8915 (interactive)
8916 (let ((s (or string (org-get-heading)))
8917 (lines org-context-in-file-links))
8918 (unless (and string (not heading))
8919 ;; We are using a headline, clean up garbage in there.
8920 (if (string-match org-todo-regexp s)
8921 (setq s (replace-match "" t t s)))
8922 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8923 (setq s (replace-match "" t t s)))
8924 (setq s (org-trim s))
8925 (if (string-match (concat "^\\(" org-quote-string "\\|"
8926 org-comment-string "\\)") s)
8927 (setq s (replace-match "" t t s)))
8928 (while (string-match org-ts-regexp s)
8929 (setq s (replace-match "" t t s))))
8930 (or string (setq s (concat "*" s))) ; Add * for headlines
8931 (when (and string (integerp lines) (> lines 0))
8932 (let ((slines (org-split-string s "\n")))
8933 (when (< lines (length slines))
8934 (setq s (mapconcat
8935 'identity
8936 (reverse (nthcdr (- (length slines) lines)
8937 (reverse slines))) "\n")))))
8938 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8940 (defun org-make-link (&rest strings)
8941 "Concatenate STRINGS."
8942 (apply 'concat strings))
8944 (defun org-make-link-string (link &optional description)
8945 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8946 (unless (string-match "\\S-" link)
8947 (error "Empty link"))
8948 (when (and description
8949 (stringp description)
8950 (not (string-match "\\S-" description)))
8951 (setq description nil))
8952 (when (stringp description)
8953 ;; Remove brackets from the description, they are fatal.
8954 (while (string-match "\\[" description)
8955 (setq description (replace-match "{" t t description)))
8956 (while (string-match "\\]" description)
8957 (setq description (replace-match "}" t t description))))
8958 (when (equal link description)
8959 ;; No description needed, it is identical
8960 (setq description nil))
8961 (when (and (not description)
8962 (not (string-match (org-image-file-name-regexp) link))
8963 (not (equal link (org-link-escape link))))
8964 (setq description (org-extract-attributes link)))
8965 (setq link
8966 (cond ((string-match (org-image-file-name-regexp) link) link)
8967 ((string-match org-link-types-re link)
8968 (concat (match-string 1 link)
8969 (org-link-escape (substring link (match-end 1)))))
8970 (t (org-link-escape link))))
8971 (concat "[[" link "]"
8972 (if description (concat "[" description "]") "")
8973 "]"))
8975 (defconst org-link-escape-chars
8976 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8977 "List of characters that should be escaped in link.
8978 This is the list that is used for internal purposes.")
8980 (defvar org-url-encoding-use-url-hexify nil)
8982 (defconst org-link-escape-chars-browser
8983 '(?\ )
8984 "List of escapes for characters that are problematic in links.
8985 This is the list that is used before handing over to the browser.")
8987 (defun org-link-escape (text &optional table merge)
8988 "Return percent escaped representation of TEXT.
8989 TEXT is a string with the text to escape.
8990 Optional argument TABLE is a list with characters that should be
8991 escaped. When nil, `org-link-escape-chars' is used.
8992 If optional argument MERGE is set, merge TABLE into
8993 `org-link-escape-chars'."
8994 (if (and org-url-encoding-use-url-hexify (not table))
8995 (url-hexify-string text)
8996 (cond
8997 ((and table merge)
8998 (mapc (lambda (defchr)
8999 (unless (member defchr table)
9000 (setq table (cons defchr table)))) org-link-escape-chars))
9001 ((null table)
9002 (setq table org-link-escape-chars)))
9003 (mapconcat
9004 (lambda (char)
9005 (if (or (member char table)
9006 (< char 32) (= char 37) (> char 126))
9007 (mapconcat (lambda (sequence-element)
9008 (format "%%%.2X" sequence-element))
9009 (or (encode-coding-char char 'utf-8)
9010 (error "Unable to percent escape character: %s"
9011 (char-to-string char))) "")
9012 (char-to-string char))) text "")))
9014 (defun org-link-unescape (str)
9015 "Unhex hexified Unicode strings as returned from the JavaScript function
9016 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9017 (unless (and (null str) (string= "" str))
9018 (let ((pos 0) (case-fold-search t) unhexed)
9019 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9020 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9021 (setq str (replace-match unhexed t t str))
9022 (setq pos (+ pos (length unhexed))))))
9023 str)
9025 (defun org-link-unescape-compound (hex)
9026 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9027 Note: this function also decodes single byte encodings like
9028 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9029 (save-match-data
9030 (let* ((bytes (cdr (split-string hex "%")))
9031 (ret "")
9032 (eat 0)
9033 (sum 0))
9034 (while bytes
9035 (let* ((val (string-to-number (pop bytes) 16))
9036 (shift-xor
9037 (if (= 0 eat)
9038 (cond
9039 ((>= val 252) (cons 6 252))
9040 ((>= val 248) (cons 5 248))
9041 ((>= val 240) (cons 4 240))
9042 ((>= val 224) (cons 3 224))
9043 ((>= val 192) (cons 2 192))
9044 (t (cons 0 0)))
9045 (cons 6 128))))
9046 (if (>= val 192) (setq eat (car shift-xor)))
9047 (setq val (logxor val (cdr shift-xor)))
9048 (setq sum (+ (lsh sum (car shift-xor)) val))
9049 (if (> eat 0) (setq eat (- eat 1)))
9050 (cond
9051 ((= 0 eat) ;multi byte
9052 (setq ret (concat ret (org-char-to-string sum)))
9053 (setq sum 0))
9054 ((not bytes) ; single byte(s)
9055 (setq ret (org-link-unescape-single-byte-sequence hex))))
9056 )) ;; end (while bytes
9057 ret )))
9059 (defun org-link-unescape-single-byte-sequence (hex)
9060 "Unhexify hex-encoded single byte character sequences."
9061 (mapconcat (lambda (byte)
9062 (char-to-string (string-to-number byte 16)))
9063 (cdr (split-string hex "%")) ""))
9065 (defun org-xor (a b)
9066 "Exclusive or."
9067 (if a (not b) b))
9069 (defun org-fixup-message-id-for-http (s)
9070 "Replace special characters in a message id, so it can be used in an http query."
9071 (when (string-match "%" s)
9072 (setq s (mapconcat (lambda (c)
9073 (if (eq c ?%)
9074 "%25"
9075 (char-to-string c)))
9076 s "")))
9077 (while (string-match "<" s)
9078 (setq s (replace-match "%3C" t t s)))
9079 (while (string-match ">" s)
9080 (setq s (replace-match "%3E" t t s)))
9081 (while (string-match "@" s)
9082 (setq s (replace-match "%40" t t s)))
9085 ;;;###autoload
9086 (defun org-insert-link-global ()
9087 "Insert a link like Org-mode does.
9088 This command can be called in any mode to insert a link in Org-mode syntax."
9089 (interactive)
9090 (org-load-modules-maybe)
9091 (org-run-like-in-org-mode 'org-insert-link))
9093 (defun org-insert-link (&optional complete-file link-location default-description)
9094 "Insert a link. At the prompt, enter the link.
9096 Completion can be used to insert any of the link protocol prefixes like
9097 http or ftp in use.
9099 The history can be used to select a link previously stored with
9100 `org-store-link'. When the empty string is entered (i.e. if you just
9101 press RET at the prompt), the link defaults to the most recently
9102 stored link. As SPC triggers completion in the minibuffer, you need to
9103 use M-SPC or C-q SPC to force the insertion of a space character.
9105 You will also be prompted for a description, and if one is given, it will
9106 be displayed in the buffer instead of the link.
9108 If there is already a link at point, this command will allow you to edit link
9109 and description parts.
9111 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9112 be selected using completion. The path to the file will be relative to the
9113 current directory if the file is in the current directory or a subdirectory.
9114 Otherwise, the link will be the absolute path as completed in the minibuffer
9115 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9116 option `org-link-file-path-type'.
9118 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9119 the current directory or below.
9121 With three \\[universal-argument] prefixes, negate the meaning of
9122 `org-keep-stored-link-after-insertion'.
9124 If `org-make-link-description-function' is non-nil, this function will be
9125 called with the link target, and the result will be the default
9126 link description.
9128 If the LINK-LOCATION parameter is non-nil, this value will be
9129 used as the link location instead of reading one interactively.
9131 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9132 be used as the default description."
9133 (interactive "P")
9134 (let* ((wcf (current-window-configuration))
9135 (region (if (org-region-active-p)
9136 (buffer-substring (region-beginning) (region-end))))
9137 (remove (and region (list (region-beginning) (region-end))))
9138 (desc region)
9139 tmphist ; byte-compile incorrectly complains about this
9140 (link link-location)
9141 entry file all-prefixes)
9142 (cond
9143 (link-location) ; specified by arg, just use it.
9144 ((org-in-regexp org-bracket-link-regexp 1)
9145 ;; We do have a link at point, and we are going to edit it.
9146 (setq remove (list (match-beginning 0) (match-end 0)))
9147 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9148 (setq link (read-string "Link: "
9149 (org-link-unescape
9150 (org-match-string-no-properties 1)))))
9151 ((or (org-in-regexp org-angle-link-re)
9152 (org-in-regexp org-plain-link-re))
9153 ;; Convert to bracket link
9154 (setq remove (list (match-beginning 0) (match-end 0))
9155 link (read-string "Link: "
9156 (org-remove-angle-brackets (match-string 0)))))
9157 ((member complete-file '((4) (16)))
9158 ;; Completing read for file names.
9159 (setq link (org-file-complete-link complete-file)))
9161 ;; Read link, with completion for stored links.
9162 (with-output-to-temp-buffer "*Org Links*"
9163 (princ "Insert a link.
9164 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9165 (when org-stored-links
9166 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9167 (princ (mapconcat
9168 (lambda (x)
9169 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9170 (reverse org-stored-links) "\n"))))
9171 (let ((cw (selected-window)))
9172 (select-window (get-buffer-window "*Org Links*" 'visible))
9173 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9174 (unless (pos-visible-in-window-p (point-max))
9175 (org-fit-window-to-buffer))
9176 (and (window-live-p cw) (select-window cw)))
9177 ;; Fake a link history, containing the stored links.
9178 (setq tmphist (append (mapcar 'car org-stored-links)
9179 org-insert-link-history))
9180 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9181 (mapcar 'car org-link-abbrev-alist)
9182 org-link-types))
9183 (unwind-protect
9184 (progn
9185 (setq link
9186 (let ((org-completion-use-ido nil)
9187 (org-completion-use-iswitchb nil))
9188 (org-completing-read
9189 "Link: "
9190 (append
9191 (mapcar (lambda (x) (list (concat x ":")))
9192 all-prefixes)
9193 (mapcar 'car org-stored-links))
9194 nil nil nil
9195 'tmphist
9196 (car (car org-stored-links)))))
9197 (if (not (string-match "\\S-" link))
9198 (error "No link selected"))
9199 (if (or (member link all-prefixes)
9200 (and (equal ":" (substring link -1))
9201 (member (substring link 0 -1) all-prefixes)
9202 (setq link (substring link 0 -1))))
9203 (setq link (org-link-try-special-completion link))))
9204 (set-window-configuration wcf)
9205 (kill-buffer "*Org Links*"))
9206 (setq entry (assoc link org-stored-links))
9207 (or entry (push link org-insert-link-history))
9208 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9209 (not org-keep-stored-link-after-insertion))
9210 (setq org-stored-links (delq (assoc link org-stored-links)
9211 org-stored-links)))
9212 (setq desc (or desc (nth 1 entry)))))
9214 (if (string-match org-plain-link-re link)
9215 ;; URL-like link, normalize the use of angular brackets.
9216 (setq link (org-make-link (org-remove-angle-brackets link))))
9218 ;; Check if we are linking to the current file with a search option
9219 ;; If yes, simplify the link by using only the search option.
9220 (when (and buffer-file-name
9221 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9222 (let* ((path (match-string 1 link))
9223 (case-fold-search nil)
9224 (search (match-string 2 link)))
9225 (save-match-data
9226 (if (equal (file-truename buffer-file-name) (file-truename path))
9227 ;; We are linking to this same file, with a search option
9228 (setq link search)))))
9230 ;; Check if we can/should use a relative path. If yes, simplify the link
9231 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9232 (let* ((type (match-string 1 link))
9233 (path (match-string 2 link))
9234 (origpath path)
9235 (case-fold-search nil))
9236 (cond
9237 ((or (eq org-link-file-path-type 'absolute)
9238 (equal complete-file '(16)))
9239 (setq path (abbreviate-file-name (expand-file-name path))))
9240 ((eq org-link-file-path-type 'noabbrev)
9241 (setq path (expand-file-name path)))
9242 ((eq org-link-file-path-type 'relative)
9243 (setq path (file-relative-name path)))
9245 (save-match-data
9246 (if (string-match (concat "^" (regexp-quote
9247 (expand-file-name
9248 (file-name-as-directory
9249 default-directory))))
9250 (expand-file-name path))
9251 ;; We are linking a file with relative path name.
9252 (setq path (substring (expand-file-name path)
9253 (match-end 0)))
9254 (setq path (abbreviate-file-name (expand-file-name path)))))))
9255 (setq link (concat type path))
9256 (if (equal desc origpath)
9257 (setq desc path))))
9259 (if org-make-link-description-function
9260 (setq desc (funcall org-make-link-description-function link desc))
9261 (if default-description (setq desc default-description)))
9263 (setq desc (read-string "Description: " desc))
9264 (unless (string-match "\\S-" desc) (setq desc nil))
9265 (if remove (apply 'delete-region remove))
9266 (insert (org-make-link-string link desc))))
9268 (defun org-link-try-special-completion (type)
9269 "If there is completion support for link type TYPE, offer it."
9270 (let ((fun (intern (concat "org-" type "-complete-link"))))
9271 (if (functionp fun)
9272 (funcall fun)
9273 (read-string "Link (no completion support): " (concat type ":")))))
9275 (defun org-file-complete-link (&optional arg)
9276 "Create a file link using completion."
9277 (let (file link)
9278 (setq file (read-file-name "File: "))
9279 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9280 (pwd1 (file-name-as-directory (abbreviate-file-name
9281 (expand-file-name ".")))))
9282 (cond
9283 ((equal arg '(16))
9284 (setq link (org-make-link
9285 "file:"
9286 (abbreviate-file-name (expand-file-name file)))))
9287 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9288 (setq link (org-make-link "file:" (match-string 1 file))))
9289 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9290 (expand-file-name file))
9291 (setq link (org-make-link
9292 "file:" (match-string 1 (expand-file-name file)))))
9293 (t (setq link (org-make-link "file:" file)))))
9294 link))
9296 (defun org-completing-read (&rest args)
9297 "Completing-read with SPACE being a normal character."
9298 (let ((enable-recursive-minibuffers t)
9299 (minibuffer-local-completion-map
9300 (copy-keymap minibuffer-local-completion-map)))
9301 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9302 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9303 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9304 (apply 'org-icompleting-read args)))
9306 (defun org-completing-read-no-i (&rest args)
9307 (let (org-completion-use-ido org-completion-use-iswitchb)
9308 (apply 'org-completing-read args)))
9310 (defun org-iswitchb-completing-read (prompt choices &rest args)
9311 "Use iswitch as a completing-read replacement to choose from choices.
9312 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9313 from."
9314 (let* ((iswitchb-use-virtual-buffers nil)
9315 (iswitchb-make-buflist-hook
9316 (lambda ()
9317 (setq iswitchb-temp-buflist choices))))
9318 (iswitchb-read-buffer prompt)))
9320 (defun org-icompleting-read (&rest args)
9321 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9322 (org-without-partial-completion
9323 (if (and org-completion-use-ido
9324 (fboundp 'ido-completing-read)
9325 (boundp 'ido-mode) ido-mode
9326 (listp (second args)))
9327 (let ((ido-enter-matching-directory nil))
9328 (apply 'ido-completing-read (concat (car args))
9329 (if (consp (car (nth 1 args)))
9330 (mapcar 'car (nth 1 args))
9331 (nth 1 args))
9332 (cddr args)))
9333 (if (and org-completion-use-iswitchb
9334 (boundp 'iswitchb-mode) iswitchb-mode
9335 (listp (second args)))
9336 (apply 'org-iswitchb-completing-read (concat (car args))
9337 (if (consp (car (nth 1 args)))
9338 (mapcar 'car (nth 1 args))
9339 (nth 1 args))
9340 (cddr args))
9341 (apply 'completing-read args)))))
9343 (defun org-extract-attributes (s)
9344 "Extract the attributes cookie from a string and set as text property."
9345 (let (a attr (start 0) key value)
9346 (save-match-data
9347 (when (string-match "{{\\([^}]+\\)}}$" s)
9348 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9349 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9350 (setq key (match-string 1 a) value (match-string 2 a)
9351 start (match-end 0)
9352 attr (plist-put attr (intern key) value))))
9353 (org-add-props s nil 'org-attr attr))
9356 (defun org-extract-attributes-from-string (tag)
9357 (let (key value attr)
9358 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9359 (setq key (match-string 1 tag) value (match-string 2 tag)
9360 tag (replace-match "" t t tag)
9361 attr (plist-put attr (intern key) value)))
9362 (cons tag attr)))
9364 (defun org-attributes-to-string (plist)
9365 "Format a property list into an HTML attribute list."
9366 (let ((s "") key value)
9367 (while plist
9368 (setq key (pop plist) value (pop plist))
9369 (and value
9370 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9373 ;;; Opening/following a link
9375 (defvar org-link-search-failed nil)
9377 (defvar org-open-link-functions nil
9378 "Hook for functions finding a plain text link.
9379 These functions must take a single argument, the link content.
9380 They will be called for links that look like [[link text][description]]
9381 when LINK TEXT does not have a protocol like \"http:\" and does not look
9382 like a filename (e.g. \"./blue.png\").
9384 These functions will be called *before* Org attempts to resolve the
9385 link by doing text searches in the current buffer - so if you want a
9386 link \"[[target]]\" to still find \"<<target>>\", your function should
9387 handle this as a special case.
9389 When the function does handle the link, it must return a non-nil value.
9390 If it decides that it is not responsible for this link, it must return
9391 nil to indicate that that Org-mode can continue with other options
9392 like exact and fuzzy text search.")
9394 (defun org-next-link ()
9395 "Move forward to the next link.
9396 If the link is in hidden text, expose it."
9397 (interactive)
9398 (when (and org-link-search-failed (eq this-command last-command))
9399 (goto-char (point-min))
9400 (message "Link search wrapped back to beginning of buffer"))
9401 (setq org-link-search-failed nil)
9402 (let* ((pos (point))
9403 (ct (org-context))
9404 (a (assoc :link ct)))
9405 (if a (goto-char (nth 2 a)))
9406 (if (re-search-forward org-any-link-re nil t)
9407 (progn
9408 (goto-char (match-beginning 0))
9409 (if (outline-invisible-p) (org-show-context)))
9410 (goto-char pos)
9411 (setq org-link-search-failed t)
9412 (error "No further link found"))))
9414 (defun org-previous-link ()
9415 "Move backward to the previous link.
9416 If the link is in hidden text, expose it."
9417 (interactive)
9418 (when (and org-link-search-failed (eq this-command last-command))
9419 (goto-char (point-max))
9420 (message "Link search wrapped back to end of buffer"))
9421 (setq org-link-search-failed nil)
9422 (let* ((pos (point))
9423 (ct (org-context))
9424 (a (assoc :link ct)))
9425 (if a (goto-char (nth 1 a)))
9426 (if (re-search-backward org-any-link-re nil t)
9427 (progn
9428 (goto-char (match-beginning 0))
9429 (if (outline-invisible-p) (org-show-context)))
9430 (goto-char pos)
9431 (setq org-link-search-failed t)
9432 (error "No further link found"))))
9434 (defun org-translate-link (s)
9435 "Translate a link string if a translation function has been defined."
9436 (if (and org-link-translation-function
9437 (fboundp org-link-translation-function)
9438 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9439 (progn
9440 (setq s (funcall org-link-translation-function
9441 (match-string 1 s) (match-string 2 s)))
9442 (concat (car s) ":" (cdr s)))
9445 (defun org-translate-link-from-planner (type path)
9446 "Translate a link from Emacs Planner syntax so that Org can follow it.
9447 This is still an experimental function, your mileage may vary."
9448 (cond
9449 ((member type '("http" "https" "news" "ftp"))
9450 ;; standard Internet links are the same.
9451 nil)
9452 ((and (equal type "irc") (string-match "^//" path))
9453 ;; Planner has two / at the beginning of an irc link, we have 1.
9454 ;; We should have zero, actually....
9455 (setq path (substring path 1)))
9456 ((and (equal type "lisp") (string-match "^/" path))
9457 ;; Planner has a slash, we do not.
9458 (setq type "elisp" path (substring path 1)))
9459 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9460 ;; A typical message link. Planner has the id after the final slash,
9461 ;; we separate it with a hash mark
9462 (setq path (concat (match-string 1 path) "#"
9463 (org-remove-angle-brackets (match-string 2 path)))))
9465 (cons type path))
9467 (defun org-find-file-at-mouse (ev)
9468 "Open file link or URL at mouse."
9469 (interactive "e")
9470 (mouse-set-point ev)
9471 (org-open-at-point 'in-emacs))
9473 (defun org-open-at-mouse (ev)
9474 "Open file link or URL at mouse.
9475 See the docstring of `org-open-file' for details."
9476 (interactive "e")
9477 (mouse-set-point ev)
9478 (if (eq major-mode 'org-agenda-mode)
9479 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9480 (org-open-at-point))
9482 (defvar org-window-config-before-follow-link nil
9483 "The window configuration before following a link.
9484 This is saved in case the need arises to restore it.")
9486 (defvar org-open-link-marker (make-marker)
9487 "Marker pointing to the location where `org-open-at-point; was called.")
9489 ;;;###autoload
9490 (defun org-open-at-point-global ()
9491 "Follow a link like Org-mode does.
9492 This command can be called in any mode to follow a link that has
9493 Org-mode syntax."
9494 (interactive)
9495 (org-run-like-in-org-mode 'org-open-at-point))
9497 ;;;###autoload
9498 (defun org-open-link-from-string (s &optional arg reference-buffer)
9499 "Open a link in the string S, as if it was in Org-mode."
9500 (interactive "sLink: \nP")
9501 (let ((reference-buffer (or reference-buffer (current-buffer))))
9502 (with-temp-buffer
9503 (let ((org-inhibit-startup (not reference-buffer)))
9504 (org-mode)
9505 (insert s)
9506 (goto-char (point-min))
9507 (when reference-buffer
9508 (setq org-link-abbrev-alist-local
9509 (with-current-buffer reference-buffer
9510 org-link-abbrev-alist-local)))
9511 (org-open-at-point arg reference-buffer)))))
9513 (defvar org-open-at-point-functions nil
9514 "Hook that is run when following a link at point.
9516 Functions in this hook must return t if they identify and follow
9517 a link at point. If they don't find anything interesting at point,
9518 they must return nil.")
9520 (defun org-open-at-point (&optional arg reference-buffer)
9521 "Open link at or after point.
9522 If there is no link at point, this function will search forward up to
9523 the end of the current line.
9524 Normally, files will be opened by an appropriate application. If the
9525 optional prefix argument ARG is non-nil, Emacs will visit the file.
9526 With a double prefix argument, try to open outside of Emacs, in the
9527 application the system uses for this file type."
9528 (interactive "P")
9529 ;; if in a code block, then open the block's results
9530 (unless (call-interactively #'org-babel-open-src-block-result)
9531 (org-load-modules-maybe)
9532 (move-marker org-open-link-marker (point))
9533 (setq org-window-config-before-follow-link (current-window-configuration))
9534 (org-remove-occur-highlights nil nil t)
9535 (cond
9536 ((and (org-at-heading-p)
9537 (not (org-in-regexp
9538 (concat org-plain-link-re "\\|"
9539 org-bracket-link-regexp "\\|"
9540 org-angle-link-re "\\|"
9541 "[ \t]:[^ \t\n]+:[ \t]*$")))
9542 (not (get-text-property (point) 'org-linked-text)))
9543 (or (org-offer-links-in-entry arg)
9544 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9545 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9546 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9547 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9548 (not (org-in-regexp org-bracket-link-regexp)))
9549 (org-footnote-action))
9551 (let (type path link line search (pos (point)))
9552 (catch 'match
9553 (save-excursion
9554 (skip-chars-forward "^]\n\r")
9555 (when (org-in-regexp org-bracket-link-regexp 1)
9556 (setq link (org-extract-attributes
9557 (org-link-unescape (org-match-string-no-properties 1))))
9558 (while (string-match " *\n *" link)
9559 (setq link (replace-match " " t t link)))
9560 (setq link (org-link-expand-abbrev link))
9561 (cond
9562 ((or (file-name-absolute-p link)
9563 (string-match "^\\.\\.?/" link))
9564 (setq type "file" path link))
9565 ((string-match org-link-re-with-space3 link)
9566 (setq type (match-string 1 link) path (match-string 2 link)))
9567 (t (setq type "thisfile" path link)))
9568 (throw 'match t)))
9570 (when (get-text-property (point) 'org-linked-text)
9571 (setq type "thisfile"
9572 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9573 (1+ (point)) (point))
9574 path (buffer-substring
9575 (or (previous-single-property-change pos 'org-linked-text)
9576 (point-min))
9577 (or (next-single-property-change pos 'org-linked-text)
9578 (point-max))))
9579 (throw 'match t))
9581 (save-excursion
9582 (when (or (org-in-regexp org-angle-link-re)
9583 (org-in-regexp org-plain-link-re))
9584 (setq type (match-string 1)
9585 path (org-link-unescape (match-string 2)))
9586 (throw 'match t)))
9587 (save-excursion
9588 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9589 (setq type "tags"
9590 path (match-string 1))
9591 (while (string-match ":" path)
9592 (setq path (replace-match "+" t t path)))
9593 (throw 'match t)))
9594 (when (org-in-regexp "<\\([^><\n]+\\)>")
9595 (setq type "tree-match"
9596 path (match-string 1))
9597 (throw 'match t)))
9598 (unless path
9599 (error "No link found"))
9601 ;; switch back to reference buffer
9602 ;; needed when if called in a temporary buffer through
9603 ;; org-open-link-from-string
9604 (with-current-buffer (or reference-buffer (current-buffer))
9606 ;; Remove any trailing spaces in path
9607 (if (string-match " +\\'" path)
9608 (setq path (replace-match "" t t path)))
9609 (if (and org-link-translation-function
9610 (fboundp org-link-translation-function))
9611 ;; Check if we need to translate the link
9612 (let ((tmp (funcall org-link-translation-function type path)))
9613 (setq type (car tmp) path (cdr tmp))))
9615 (cond
9617 ((assoc type org-link-protocols)
9618 (funcall (nth 1 (assoc type org-link-protocols)) path))
9620 ((equal type "mailto")
9621 (let ((cmd (car org-link-mailto-program))
9622 (args (cdr org-link-mailto-program)) args1
9623 (address path) (subject "") a)
9624 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9625 (setq address (match-string 1 path)
9626 subject (org-link-escape (match-string 2 path))))
9627 (while args
9628 (cond
9629 ((not (stringp (car args))) (push (pop args) args1))
9630 (t (setq a (pop args))
9631 (if (string-match "%a" a)
9632 (setq a (replace-match address t t a)))
9633 (if (string-match "%s" a)
9634 (setq a (replace-match subject t t a)))
9635 (push a args1))))
9636 (apply cmd (nreverse args1))))
9638 ((member type '("http" "https" "ftp" "news"))
9639 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9640 (org-link-escape
9641 path org-link-escape-chars-browser)
9642 path))))
9644 ((string= type "doi")
9645 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9646 (org-link-escape
9647 path org-link-escape-chars-browser)
9648 path))))
9650 ((member type '("message"))
9651 (browse-url (concat type ":" path)))
9653 ((string= type "tags")
9654 (org-tags-view arg path))
9656 ((string= type "tree-match")
9657 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9659 ((string= type "file")
9660 (if (string-match "::\\([0-9]+\\)\\'" path)
9661 (setq line (string-to-number (match-string 1 path))
9662 path (substring path 0 (match-beginning 0)))
9663 (if (string-match "::\\(.+\\)\\'" path)
9664 (setq search (match-string 1 path)
9665 path (substring path 0 (match-beginning 0)))))
9666 (if (string-match "[*?{]" (file-name-nondirectory path))
9667 (dired path)
9668 (org-open-file path arg line search)))
9670 ((string= type "shell")
9671 (let ((cmd path))
9672 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9673 (string-match org-confirm-shell-link-not-regexp cmd))
9674 (not org-confirm-shell-link-function)
9675 (funcall org-confirm-shell-link-function
9676 (format "Execute \"%s\" in shell? "
9677 (org-add-props cmd nil
9678 'face 'org-warning))))
9679 (progn
9680 (message "Executing %s" cmd)
9681 (shell-command cmd))
9682 (error "Abort"))))
9684 ((string= type "elisp")
9685 (let ((cmd path))
9686 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9687 (string-match org-confirm-elisp-link-not-regexp cmd))
9688 (not org-confirm-elisp-link-function)
9689 (funcall org-confirm-elisp-link-function
9690 (format "Execute \"%s\" as elisp? "
9691 (org-add-props cmd nil
9692 'face 'org-warning))))
9693 (message "%s => %s" cmd
9694 (if (equal (string-to-char cmd) ?\()
9695 (eval (read cmd))
9696 (call-interactively (read cmd))))
9697 (error "Abort"))))
9699 ((and (string= type "thisfile")
9700 (run-hook-with-args-until-success
9701 'org-open-link-functions path)))
9703 ((string= type "thisfile")
9704 (if arg
9705 (switch-to-buffer-other-window
9706 (org-get-buffer-for-internal-link (current-buffer)))
9707 (org-mark-ring-push))
9708 (let ((cmd `(org-link-search
9709 ,path
9710 ,(cond ((equal arg '(4)) ''occur)
9711 ((equal arg '(16)) ''org-occur)
9712 (t nil))
9713 ,pos)))
9714 (condition-case nil (let ((org-link-search-inhibit-query t))
9715 (eval cmd))
9716 (error (progn (widen) (eval cmd))))))
9719 (browse-url-at-point)))))))
9720 (move-marker org-open-link-marker nil)
9721 (run-hook-with-args 'org-follow-link-hook)))
9723 (defun org-offer-links-in-entry (&optional nth zero)
9724 "Offer links in the current entry and follow the selected link.
9725 If there is only one link, follow it immediately as well.
9726 If NTH is an integer, immediately pick the NTH link found.
9727 If ZERO is a string, check also this string for a link, and if
9728 there is one, offer it as link number zero."
9729 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9730 "\\(" org-angle-link-re "\\)\\|"
9731 "\\(" org-plain-link-re "\\)"))
9732 (cnt ?0)
9733 (in-emacs (if (integerp nth) nil nth))
9734 have-zero end links link c)
9735 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9736 (push (match-string 0 zero) links)
9737 (setq cnt (1- cnt) have-zero t))
9738 (save-excursion
9739 (org-back-to-heading t)
9740 (setq end (save-excursion (outline-next-heading) (point)))
9741 (while (re-search-forward re end t)
9742 (push (match-string 0) links))
9743 (setq links (org-uniquify (reverse links))))
9745 (cond
9746 ((null links)
9747 (message "No links"))
9748 ((equal (length links) 1)
9749 (setq link (list (car links))))
9750 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9751 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9752 (t ; we have to select a link
9753 (save-excursion
9754 (save-window-excursion
9755 (delete-other-windows)
9756 (with-output-to-temp-buffer "*Select Link*"
9757 (mapc (lambda (l)
9758 (if (not (string-match org-bracket-link-regexp l))
9759 (princ (format "[%c] %s\n" (incf cnt)
9760 (org-remove-angle-brackets l)))
9761 (if (match-end 3)
9762 (princ (format "[%c] %s (%s)\n" (incf cnt)
9763 (match-string 3 l) (match-string 1 l)))
9764 (princ (format "[%c] %s\n" (incf cnt)
9765 (match-string 1 l))))))
9766 links))
9767 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9768 (message "Select link to open, RET to open all:")
9769 (setq c (read-char-exclusive))
9770 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9771 (when (equal c ?q) (error "Abort"))
9772 (if (equal c ?\C-m)
9773 (setq link links)
9774 (setq nth (- c ?0))
9775 (if have-zero (setq nth (1+ nth)))
9776 (unless (and (integerp nth) (>= (length links) nth))
9777 (error "Invalid link selection"))
9778 (setq link (list (nth (1- nth) links))))))
9779 (if link
9780 (let ((buf (current-buffer)))
9781 (dolist (l link)
9782 (org-open-link-from-string l in-emacs buf))
9784 nil)))
9786 ;; Add special file links that specify the way of opening
9788 (org-add-link-type "file+sys" 'org-open-file-with-system)
9789 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9790 (defun org-open-file-with-system (path)
9791 "Open file at PATH using the system way of opening it."
9792 (org-open-file path 'system))
9793 (defun org-open-file-with-emacs (path)
9794 "Open file at PATH in Emacs."
9795 (org-open-file path 'emacs))
9796 (defun org-remove-file-link-modifiers ()
9797 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9798 (goto-char (point-min))
9799 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9800 (org-if-unprotected
9801 (replace-match "file:" t t))))
9802 (eval-after-load "org-exp"
9803 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9804 'org-remove-file-link-modifiers))
9806 ;;;; Time estimates
9808 (defun org-get-effort (&optional pom)
9809 "Get the effort estimate for the current entry."
9810 (org-entry-get pom org-effort-property))
9812 ;;; File search
9814 (defvar org-create-file-search-functions nil
9815 "List of functions to construct the right search string for a file link.
9816 These functions are called in turn with point at the location to
9817 which the link should point.
9819 A function in the hook should first test if it would like to
9820 handle this file type, for example by checking the `major-mode'
9821 or the file extension. If it decides not to handle this file, it
9822 should just return nil to give other functions a chance. If it
9823 does handle the file, it must return the search string to be used
9824 when following the link. The search string will be part of the
9825 file link, given after a double colon, and `org-open-at-point'
9826 will automatically search for it. If special measures must be
9827 taken to make the search successful, another function should be
9828 added to the companion hook `org-execute-file-search-functions',
9829 which see.
9831 A function in this hook may also use `setq' to set the variable
9832 `description' to provide a suggestion for the descriptive text to
9833 be used for this link when it gets inserted into an Org-mode
9834 buffer with \\[org-insert-link].")
9836 (defvar org-execute-file-search-functions nil
9837 "List of functions to execute a file search triggered by a link.
9839 Functions added to this hook must accept a single argument, the
9840 search string that was part of the file link, the part after the
9841 double colon. The function must first check if it would like to
9842 handle this search, for example by checking the `major-mode' or
9843 the file extension. If it decides not to handle this search, it
9844 should just return nil to give other functions a chance. If it
9845 does handle the search, it must return a non-nil value to keep
9846 other functions from trying.
9848 Each function can access the current prefix argument through the
9849 variable `current-prefix-argument'. Note that a single prefix is
9850 used to force opening a link in Emacs, so it may be good to only
9851 use a numeric or double prefix to guide the search function.
9853 In case this is needed, a function in this hook can also restore
9854 the window configuration before `org-open-at-point' was called using:
9856 (set-window-configuration org-window-config-before-follow-link)")
9858 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9859 (defun org-link-search (s &optional type avoid-pos stealth)
9860 "Search for a link search option.
9861 If S is surrounded by forward slashes, it is interpreted as a
9862 regular expression. In org-mode files, this will create an `org-occur'
9863 sparse tree. In ordinary files, `occur' will be used to list matches.
9864 If the current buffer is in `dired-mode', grep will be used to search
9865 in all files. If AVOID-POS is given, ignore matches near that position.
9867 When optional argument STEALTH is non-nil, do not modify
9868 visibility around point, thus ignoring
9869 `org-show-hierarchy-above', `org-show-following-heading' and
9870 `org-show-siblings' variables."
9871 (let ((case-fold-search t)
9872 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9873 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9874 (append '(("") (" ") ("\t") ("\n"))
9875 org-emphasis-alist)
9876 "\\|") "\\)"))
9877 (pos (point))
9878 (pre nil) (post nil)
9879 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9880 (cond
9881 ;; First check if there are any special search functions
9882 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9883 ;; Now try the builtin stuff
9884 ((and (equal (string-to-char s0) ?#)
9885 (> (length s0) 1)
9886 (save-excursion
9887 (goto-char (point-min))
9888 (and
9889 (re-search-forward
9890 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9891 (setq type 'dedicated
9892 pos (match-beginning 0))))
9893 ;; There is an exact target for this
9894 (goto-char pos)
9895 (org-back-to-heading t)))
9896 ((save-excursion
9897 (goto-char (point-min))
9898 (and
9899 (re-search-forward
9900 (concat "<<" (regexp-quote s0) ">>") nil t)
9901 (setq type 'dedicated
9902 pos (match-beginning 0))))
9903 ;; There is an exact target for this
9904 (goto-char pos))
9905 ((and (string-match "^(\\(.*\\))$" s0)
9906 (save-excursion
9907 (goto-char (point-min))
9908 (and
9909 (re-search-forward
9910 (concat "[^[]" (regexp-quote
9911 (format org-coderef-label-format
9912 (match-string 1 s0))))
9913 nil t)
9914 (setq type 'dedicated
9915 pos (1+ (match-beginning 0))))))
9916 ;; There is a coderef target for this
9917 (goto-char pos))
9918 ((string-match "^/\\(.*\\)/$" s)
9919 ;; A regular expression
9920 (cond
9921 ((eq major-mode 'org-mode)
9922 (org-occur (match-string 1 s)))
9923 ;;((eq major-mode 'dired-mode)
9924 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9925 (t (org-do-occur (match-string 1 s)))))
9926 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9927 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9928 (goto-char (point-min))
9929 (cond
9930 ((let (case-fold-search)
9931 (re-search-forward (format org-complex-heading-regexp-format
9932 (regexp-quote s))
9933 nil t))
9934 ;; OK, found a match
9935 (setq type 'dedicated)
9936 (goto-char (match-beginning 0)))
9937 ((and (not org-link-search-inhibit-query)
9938 (eq org-link-search-must-match-exact-headline 'query-to-create)
9939 (y-or-n-p "No match - create this as a new heading? "))
9940 (goto-char (point-max))
9941 (or (bolp) (newline))
9942 (insert "* " s "\n")
9943 (beginning-of-line 0))
9945 (goto-char pos)
9946 (error "No match"))))
9948 ;; A normal search string
9949 (when (equal (string-to-char s) ?*)
9950 ;; Anchor on headlines, post may include tags.
9951 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9952 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9953 s (substring s 1)))
9954 (remove-text-properties
9955 0 (length s)
9956 '(face nil mouse-face nil keymap nil fontified nil) s)
9957 ;; Make a series of regular expressions to find a match
9958 (setq words (org-split-string s "[ \n\r\t]+")
9960 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9961 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9962 "\\)" markers)
9963 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9964 re2a (concat "[ \t\r\n]" re2a_)
9965 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9966 re4 (concat "[^a-zA-Z_]" re4_)
9968 re1 (concat pre re2 post)
9969 re3 (concat pre (if pre re4_ re4) post)
9970 re5 (concat pre ".*" re4)
9971 re2 (concat pre re2)
9972 re2a (concat pre (if pre re2a_ re2a))
9973 re4 (concat pre (if pre re4_ re4))
9974 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9975 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9976 re5 "\\)"
9978 (cond
9979 ((eq type 'org-occur) (org-occur reall))
9980 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9981 (t (goto-char (point-min))
9982 (setq type 'fuzzy)
9983 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9984 (org-search-not-self 1 re1 nil t)
9985 (org-search-not-self 1 re2 nil t)
9986 (org-search-not-self 1 re2a nil t)
9987 (org-search-not-self 1 re3 nil t)
9988 (org-search-not-self 1 re4 nil t)
9989 (org-search-not-self 1 re5 nil t)
9991 (goto-char (match-beginning 1))
9992 (goto-char pos)
9993 (error "No match"))))))
9994 (and (eq major-mode 'org-mode)
9995 (not stealth)
9996 (org-show-context 'link-search))
9997 type))
9999 (defun org-search-not-self (group &rest args)
10000 "Execute `re-search-forward', but only accept matches that do not
10001 enclose the position of `org-open-link-marker'."
10002 (let ((m org-open-link-marker))
10003 (catch 'exit
10004 (while (apply 're-search-forward args)
10005 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10006 (goto-char (match-end group))
10007 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10008 (> (match-beginning 0) (marker-position m))
10009 (< (match-end 0) (marker-position m)))
10010 (save-match-data
10011 (or (not (org-in-regexp
10012 org-bracket-link-analytic-regexp 1))
10013 (not (match-end 4)) ; no description
10014 (and (<= (match-beginning 4) (point))
10015 (>= (match-end 4) (point))))))
10016 (throw 'exit (point))))))))
10018 (defun org-get-buffer-for-internal-link (buffer)
10019 "Return a buffer to be used for displaying the link target of internal links."
10020 (cond
10021 ((not org-display-internal-link-with-indirect-buffer)
10022 buffer)
10023 ((string-match "(Clone)$" (buffer-name buffer))
10024 (message "Buffer is already a clone, not making another one")
10025 ;; we also do not modify visibility in this case
10026 buffer)
10027 (t ; make a new indirect buffer for displaying the link
10028 (let* ((bn (buffer-name buffer))
10029 (ibn (concat bn "(Clone)"))
10030 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10031 (with-current-buffer ib (org-overview))
10032 ib))))
10034 (defun org-do-occur (regexp &optional cleanup)
10035 "Call the Emacs command `occur'.
10036 If CLEANUP is non-nil, remove the printout of the regular expression
10037 in the *Occur* buffer. This is useful if the regex is long and not useful
10038 to read."
10039 (occur regexp)
10040 (when cleanup
10041 (let ((cwin (selected-window)) win beg end)
10042 (when (setq win (get-buffer-window "*Occur*"))
10043 (select-window win))
10044 (goto-char (point-min))
10045 (when (re-search-forward "match[a-z]+" nil t)
10046 (setq beg (match-end 0))
10047 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10048 (setq end (1- (match-beginning 0)))))
10049 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10050 (goto-char (point-min))
10051 (select-window cwin))))
10053 ;;; The mark ring for links jumps
10055 (defvar org-mark-ring nil
10056 "Mark ring for positions before jumps in Org-mode.")
10057 (defvar org-mark-ring-last-goto nil
10058 "Last position in the mark ring used to go back.")
10059 ;; Fill and close the ring
10060 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10061 (loop for i from 1 to org-mark-ring-length do
10062 (push (make-marker) org-mark-ring))
10063 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10064 org-mark-ring)
10066 (defun org-mark-ring-push (&optional pos buffer)
10067 "Put the current position or POS into the mark ring and rotate it."
10068 (interactive)
10069 (setq pos (or pos (point)))
10070 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10071 (move-marker (car org-mark-ring)
10072 (or pos (point))
10073 (or buffer (current-buffer)))
10074 (message "%s"
10075 (substitute-command-keys
10076 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10078 (defun org-mark-ring-goto (&optional n)
10079 "Jump to the previous position in the mark ring.
10080 With prefix arg N, jump back that many stored positions. When
10081 called several times in succession, walk through the entire ring.
10082 Org-mode commands jumping to a different position in the current file,
10083 or to another Org-mode file, automatically push the old position
10084 onto the ring."
10085 (interactive "p")
10086 (let (p m)
10087 (if (eq last-command this-command)
10088 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10089 (setq p org-mark-ring))
10090 (setq org-mark-ring-last-goto p)
10091 (setq m (car p))
10092 (org-pop-to-buffer-same-window (marker-buffer m))
10093 (goto-char m)
10094 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10096 (defun org-remove-angle-brackets (s)
10097 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10098 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10100 (defun org-add-angle-brackets (s)
10101 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10102 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10104 (defun org-remove-double-quotes (s)
10105 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10106 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10109 ;;; Following specific links
10111 (defun org-follow-timestamp-link ()
10112 (cond
10113 ((org-at-date-range-p t)
10114 (let ((org-agenda-start-on-weekday)
10115 (t1 (match-string 1))
10116 (t2 (match-string 2)))
10117 (setq t1 (time-to-days (org-time-string-to-time t1))
10118 t2 (time-to-days (org-time-string-to-time t2)))
10119 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10120 ((org-at-timestamp-p t)
10121 (org-agenda-list nil (time-to-days (org-time-string-to-time
10122 (substring (match-string 1) 0 10)))
10124 (t (error "This should not happen"))))
10127 ;;; Following file links
10128 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10129 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10130 (declare-function mailcap-mime-info
10131 "mailcap" (string &optional request no-decode))
10132 (defvar org-wait nil)
10133 (defun org-open-file (path &optional in-emacs line search)
10134 "Open the file at PATH.
10135 First, this expands any special file name abbreviations. Then the
10136 configuration variable `org-file-apps' is checked if it contains an
10137 entry for this file type, and if yes, the corresponding command is launched.
10139 If no application is found, Emacs simply visits the file.
10141 With optional prefix argument IN-EMACS, Emacs will visit the file.
10142 With a double \\[universal-argument] \\[universal-argument] \
10143 prefix arg, Org tries to avoid opening in Emacs
10144 and to use an external application to visit the file.
10146 Optional LINE specifies a line to go to, optional SEARCH a string
10147 to search for. If LINE or SEARCH is given, the file will be
10148 opened in Emacs, unless an entry from org-file-apps that makes
10149 use of groups in a regexp matches.
10151 If you want to change the way frames are used when following a
10152 link, please customize `org-link-frame-setup'.
10154 If the file does not exist, an error is thrown."
10155 (let* ((file (if (equal path "")
10156 buffer-file-name
10157 (substitute-in-file-name (expand-file-name path))))
10158 (file-apps (append org-file-apps (org-default-apps)))
10159 (apps (org-remove-if
10160 'org-file-apps-entry-match-against-dlink-p file-apps))
10161 (apps-dlink (org-remove-if-not
10162 'org-file-apps-entry-match-against-dlink-p file-apps))
10163 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10164 (dirp (if remp nil (file-directory-p file)))
10165 (file (if (and dirp org-open-directory-means-index-dot-org)
10166 (concat (file-name-as-directory file) "index.org")
10167 file))
10168 (a-m-a-p (assq 'auto-mode apps))
10169 (dfile (downcase file))
10170 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10171 (link (cond ((and (eq line nil)
10172 (eq search nil))
10173 file)
10174 (line
10175 (concat file "::" (number-to-string line)))
10176 (search
10177 (concat file "::" search))))
10178 (dlink (downcase link))
10179 (old-buffer (current-buffer))
10180 (old-pos (point))
10181 (old-mode major-mode)
10182 ext cmd link-match-data)
10183 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10184 (setq ext (match-string 1 dfile))
10185 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10186 (setq ext (match-string 1 dfile))))
10187 (cond
10188 ((member in-emacs '((16) system))
10189 (setq cmd (cdr (assoc 'system apps))))
10190 (in-emacs (setq cmd 'emacs))
10192 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10193 (and dirp (cdr (assoc 'directory apps)))
10194 ; first, try matching against apps-dlink
10195 ; if we get a match here, store the match data for later
10196 (let ((match (assoc-default dlink apps-dlink
10197 'string-match)))
10198 (if match
10199 (progn (setq link-match-data (match-data))
10200 match)
10201 (progn (setq in-emacs (or in-emacs line search))
10202 nil))) ; if we have no match in apps-dlink,
10203 ; always open the file in emacs if line or search
10204 ; is given (for backwards compatibility)
10205 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10206 'string-match)
10207 (cdr (assoc ext apps))
10208 (cdr (assoc t apps))))))
10209 (when (eq cmd 'system)
10210 (setq cmd (cdr (assoc 'system apps))))
10211 (when (eq cmd 'default)
10212 (setq cmd (cdr (assoc t apps))))
10213 (when (eq cmd 'mailcap)
10214 (require 'mailcap)
10215 (mailcap-parse-mailcaps)
10216 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10217 (command (mailcap-mime-info mime-type)))
10218 (if (stringp command)
10219 (setq cmd command)
10220 (setq cmd 'emacs))))
10221 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10222 (not (file-exists-p file))
10223 (not org-open-non-existing-files))
10224 (error "No such file: %s" file))
10225 (cond
10226 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10227 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10228 (while (string-match "['\"]%s['\"]" cmd)
10229 (setq cmd (replace-match "%s" t t cmd)))
10230 (while (string-match "%s" cmd)
10231 (setq cmd (replace-match
10232 (save-match-data
10233 (shell-quote-argument
10234 (convert-standard-filename file)))
10235 t t cmd)))
10237 ;; Replace "%1", "%2" etc. in command with group matches from regex
10238 (save-match-data
10239 (let ((match-index 1)
10240 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10241 (set-match-data link-match-data)
10242 (while (<= match-index number-of-groups)
10243 (let ((regex (concat "%" (number-to-string match-index)))
10244 (replace-with (match-string match-index dlink)))
10245 (while (string-match regex cmd)
10246 (setq cmd (replace-match replace-with t t cmd))))
10247 (setq match-index (+ match-index 1)))))
10249 (save-window-excursion
10250 (start-process-shell-command cmd nil cmd)
10251 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10253 ((or (stringp cmd)
10254 (eq cmd 'emacs))
10255 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10256 (widen)
10257 (if line (org-goto-line line)
10258 (if search (org-link-search search))))
10259 ((consp cmd)
10260 (let ((file (convert-standard-filename file)))
10261 (save-match-data
10262 (set-match-data link-match-data)
10263 (eval cmd))))
10264 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10265 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10266 (or (not (equal old-buffer (current-buffer)))
10267 (not (equal old-pos (point))))
10268 (org-mark-ring-push old-pos old-buffer))))
10270 (defun org-file-apps-entry-match-against-dlink-p (entry)
10271 "This function returns non-nil if `entry' uses a regular
10272 expression which should be matched against the whole link by
10273 org-open-file.
10275 It assumes that is the case when the entry uses a regular
10276 expression which has at least one grouping construct and the
10277 action is either a lisp form or a command string containing
10278 '%1', i.e. using at least one subexpression match as a
10279 parameter."
10280 (let ((selector (car entry))
10281 (action (cdr entry)))
10282 (if (stringp selector)
10283 (and (> (regexp-opt-depth selector) 0)
10284 (or (and (stringp action)
10285 (string-match "%[0-9]" action))
10286 (consp action)))
10287 nil)))
10289 (defun org-default-apps ()
10290 "Return the default applications for this operating system."
10291 (cond
10292 ((eq system-type 'darwin)
10293 org-file-apps-defaults-macosx)
10294 ((eq system-type 'windows-nt)
10295 org-file-apps-defaults-windowsnt)
10296 (t org-file-apps-defaults-gnu)))
10298 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10299 "Convert extensions to regular expressions in the cars of LIST.
10300 Also, weed out any non-string entries, because the return value is used
10301 only for regexp matching.
10302 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10303 point to the symbol `emacs', indicating that the file should
10304 be opened in Emacs."
10305 (append
10306 (delq nil
10307 (mapcar (lambda (x)
10308 (if (not (stringp (car x)))
10310 (if (string-match "\\W" (car x))
10312 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10313 list))
10314 (if add-auto-mode
10315 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10317 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10318 (defun org-file-remote-p (file)
10319 "Test whether FILE specifies a location on a remote system.
10320 Return non-nil if the location is indeed remote.
10322 For example, the filename \"/user@host:/foo\" specifies a location
10323 on the system \"/user@host:\"."
10324 (cond ((fboundp 'file-remote-p)
10325 (file-remote-p file))
10326 ((fboundp 'tramp-handle-file-remote-p)
10327 (tramp-handle-file-remote-p file))
10328 ((and (boundp 'ange-ftp-name-format)
10329 (string-match (car ange-ftp-name-format) file))
10331 (t nil)))
10334 ;;;; Refiling
10336 (defun org-get-org-file ()
10337 "Read a filename, with default directory `org-directory'."
10338 (let ((default (or org-default-notes-file remember-data-file)))
10339 (read-file-name (format "File name [%s]: " default)
10340 (file-name-as-directory org-directory)
10341 default)))
10343 (defun org-notes-order-reversed-p ()
10344 "Check if the current file should receive notes in reversed order."
10345 (cond
10346 ((not org-reverse-note-order) nil)
10347 ((eq t org-reverse-note-order) t)
10348 ((not (listp org-reverse-note-order)) nil)
10349 (t (catch 'exit
10350 (let ((all org-reverse-note-order)
10351 entry)
10352 (while (setq entry (pop all))
10353 (if (string-match (car entry) buffer-file-name)
10354 (throw 'exit (cdr entry))))
10355 nil)))))
10357 (defvar org-refile-target-table nil
10358 "The list of refile targets, created by `org-refile'.")
10360 (defvar org-agenda-new-buffers nil
10361 "Buffers created to visit agenda files.")
10363 (defvar org-refile-cache nil
10364 "Cache for refile targets.")
10366 (defvar org-refile-markers nil
10367 "All the markers used for caching refile locations.")
10369 (defun org-refile-marker (pos)
10370 "Get a new refile marker, but only if caching is in use."
10371 (if (not org-refile-use-cache)
10373 (let ((m (make-marker)))
10374 (move-marker m pos)
10375 (push m org-refile-markers)
10376 m)))
10378 (defun org-refile-cache-clear ()
10379 "Clear the refile cache and disable all the markers."
10380 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10381 (setq org-refile-markers nil)
10382 (setq org-refile-cache nil)
10383 (message "Refile cache has been cleared"))
10385 (defun org-refile-cache-check-set (set)
10386 "Check if all the markers in the cache still have live buffers."
10387 (let (marker)
10388 (catch 'exit
10389 (while (and set (setq marker (nth 3 (pop set))))
10390 ;; if org-refile-use-outline-path is 'file, marker may be nil
10391 (when (and marker (null (marker-buffer marker)))
10392 (message "not found") (sit-for 3)
10393 (throw 'exit nil)))
10394 t)))
10396 (defun org-refile-cache-put (set &rest identifiers)
10397 "Push the refile targets SET into the cache, under IDENTIFIERS."
10398 (let* ((key (sha1 (prin1-to-string identifiers)))
10399 (entry (assoc key org-refile-cache)))
10400 (if entry
10401 (setcdr entry set)
10402 (push (cons key set) org-refile-cache))))
10404 (defun org-refile-cache-get (&rest identifiers)
10405 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10406 (cond
10407 ((not org-refile-cache) nil)
10408 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10410 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10411 org-refile-cache))))
10412 (and set (org-refile-cache-check-set set) set)))))
10414 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10415 "Produce a table with refile targets."
10416 (let ((case-fold-search nil)
10417 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10418 (entries (or org-refile-targets '((nil . (:level . 1)))))
10419 targets tgs txt re files f desc descre fast-path-p level pos0)
10420 (message "Getting targets...")
10421 (with-current-buffer (or default-buffer (current-buffer))
10422 (while (setq entry (pop entries))
10423 (setq files (car entry) desc (cdr entry))
10424 (setq fast-path-p nil)
10425 (cond
10426 ((null files) (setq files (list (current-buffer))))
10427 ((eq files 'org-agenda-files)
10428 (setq files (org-agenda-files 'unrestricted)))
10429 ((and (symbolp files) (fboundp files))
10430 (setq files (funcall files)))
10431 ((and (symbolp files) (boundp files))
10432 (setq files (symbol-value files))))
10433 (if (stringp files) (setq files (list files)))
10434 (cond
10435 ((eq (car desc) :tag)
10436 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10437 ((eq (car desc) :todo)
10438 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10439 ((eq (car desc) :regexp)
10440 (setq descre (cdr desc)))
10441 ((eq (car desc) :level)
10442 (setq descre (concat "^\\*\\{" (number-to-string
10443 (if org-odd-levels-only
10444 (1- (* 2 (cdr desc)))
10445 (cdr desc)))
10446 "\\}[ \t]")))
10447 ((eq (car desc) :maxlevel)
10448 (setq fast-path-p t)
10449 (setq descre (concat "^\\*\\{1," (number-to-string
10450 (if org-odd-levels-only
10451 (1- (* 2 (cdr desc)))
10452 (cdr desc)))
10453 "\\}[ \t]")))
10454 (t (error "Bad refiling target description %s" desc)))
10455 (while (setq f (pop files))
10456 (with-current-buffer
10457 (if (bufferp f) f (org-get-agenda-file-buffer f))
10459 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10460 (progn
10461 (if (bufferp f) (setq f (buffer-file-name
10462 (buffer-base-buffer f))))
10463 (setq f (and f (expand-file-name f)))
10464 (if (eq org-refile-use-outline-path 'file)
10465 (push (list (file-name-nondirectory f) f nil nil) tgs))
10466 (save-excursion
10467 (save-restriction
10468 (widen)
10469 (goto-char (point-min))
10470 (while (re-search-forward descre nil t)
10471 (goto-char (setq pos0 (point-at-bol)))
10472 (catch 'next
10473 (when org-refile-target-verify-function
10474 (save-match-data
10475 (or (funcall org-refile-target-verify-function)
10476 (throw 'next t))))
10477 (when (and (looking-at org-complex-heading-regexp)
10478 (not (member (match-string 4) excluded-entries))
10479 (match-string 4))
10480 (setq level (org-reduced-level
10481 (- (match-end 1) (match-beginning 1)))
10482 txt (org-link-display-format (match-string 4))
10483 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10484 re (format org-complex-heading-regexp-format
10485 (regexp-quote (match-string 4))))
10486 (when org-refile-use-outline-path
10487 (setq txt (mapconcat
10488 'org-protect-slash
10489 (append
10490 (if (eq org-refile-use-outline-path
10491 'file)
10492 (list (file-name-nondirectory
10493 (buffer-file-name
10494 (buffer-base-buffer))))
10495 (if (eq org-refile-use-outline-path
10496 'full-file-path)
10497 (list (buffer-file-name
10498 (buffer-base-buffer)))))
10499 (org-get-outline-path fast-path-p
10500 level txt)
10501 (list txt))
10502 "/")))
10503 (push (list txt f re (org-refile-marker (point)))
10504 tgs)))
10505 (when (= (point) pos0)
10506 ;; verification function has not moved point
10507 (goto-char (point-at-eol))))))))
10508 (when org-refile-use-cache
10509 (org-refile-cache-put tgs (buffer-file-name) descre))
10510 (setq targets (append tgs targets))
10511 ))))
10512 (message "Getting targets...done")
10513 (nreverse targets)))
10515 (defun org-protect-slash (s)
10516 (while (string-match "/" s)
10517 (setq s (replace-match "\\" t t s)))
10520 (defvar org-olpa (make-vector 20 nil))
10522 (defun org-get-outline-path (&optional fastp level heading)
10523 "Return the outline path to the current entry, as a list.
10525 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10526 routine which makes outline path derivations for an entire file,
10527 avoiding backtracing. Refile target collection makes use of that."
10528 (if fastp
10529 (progn
10530 (if (> level 19)
10531 (error "Outline path failure, more than 19 levels"))
10532 (loop for i from level upto 19 do
10533 (aset org-olpa i nil))
10534 (prog1
10535 (delq nil (append org-olpa nil))
10536 (aset org-olpa level heading)))
10537 (let (rtn case-fold-search)
10538 (save-excursion
10539 (save-restriction
10540 (widen)
10541 (while (org-up-heading-safe)
10542 (when (looking-at org-complex-heading-regexp)
10543 (push (org-match-string-no-properties 4) rtn)))
10544 rtn)))))
10546 (defun org-format-outline-path (path &optional width prefix)
10547 "Format the outline path PATH for display.
10548 Width is the maximum number of characters that is available.
10549 Prefix is a prefix to be included in the returned string,
10550 such as the file name."
10551 (setq width (or width 79))
10552 (if prefix (setq width (- width (length prefix))))
10553 (if (not path)
10554 (or prefix "")
10555 (let* ((nsteps (length path))
10556 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10557 (maxwidth (if (<= total-width width)
10558 10000 ;; everything fits
10559 ;; we need to shorten the level headings
10560 (/ (- width nsteps) nsteps)))
10561 (org-odd-levels-only nil)
10562 (n 0)
10563 (total (1+ (length prefix))))
10564 (setq maxwidth (max maxwidth 10))
10565 (concat prefix
10566 (mapconcat
10567 (lambda (h)
10568 (setq n (1+ n))
10569 (if (and (= n nsteps) (< maxwidth 10000))
10570 (setq maxwidth (- total-width total)))
10571 (if (< (length h) maxwidth)
10572 (progn (setq total (+ total (length h) 1)) h)
10573 (setq h (substring h 0 (- maxwidth 2))
10574 total (+ total maxwidth 1))
10575 (if (string-match "[ \t]+\\'" h)
10576 (setq h (substring h 0 (match-beginning 0))))
10577 (setq h (concat h "..")))
10578 (org-add-props h nil 'face
10579 (nth (% (1- n) org-n-level-faces)
10580 org-level-faces))
10582 path "/")))))
10584 (defun org-display-outline-path (&optional file current)
10585 "Display the current outline path in the echo area."
10586 (interactive "P")
10587 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10588 (case-fold-search nil)
10589 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10590 (if current (setq path (append path
10591 (save-excursion
10592 (org-back-to-heading t)
10593 (if (looking-at org-complex-heading-regexp)
10594 (list (match-string 4)))))))
10595 (message "%s"
10596 (org-format-outline-path
10597 path
10598 (1- (frame-width))
10599 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10601 (defvar org-refile-history nil
10602 "History for refiling operations.")
10604 (defvar org-after-refile-insert-hook nil
10605 "Hook run after `org-refile' has inserted its stuff at the new location.
10606 Note that this is still *before* the stuff will be removed from
10607 the *old* location.")
10609 (defvar org-capture-last-stored-marker)
10610 (defun org-refile (&optional goto default-buffer rfloc)
10611 "Move the entry or entries at point to another heading.
10612 The list of target headings is compiled using the information in
10613 `org-refile-targets', which see.
10615 At the target location, the entry is filed as a subitem of the target
10616 heading. Depending on `org-reverse-note-order', the new subitem will
10617 either be the first or the last subitem.
10619 If there is an active region, all entries in that region will be moved.
10620 However, the region must fulfill the requirement that the first heading
10621 is the first one sets the top-level of the moved text - at most siblings
10622 below it are allowed.
10624 With prefix arg GOTO, the command will only visit the target location
10625 and not actually move anything.
10627 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10628 go to the location where the last refiling operation has put the subtree.
10629 With a prefix argument of `2', refile to the running clock.
10631 RFLOC can be a refile location obtained in a different way.
10633 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10635 If you are using target caching (see `org-refile-use-cache'),
10636 You have to clear the target cache in order to find new targets.
10637 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10638 prefix argument (`C-u C-u C-u C-c C-w')."
10640 (interactive "P")
10641 (if (member goto '(0 (64)))
10642 (org-refile-cache-clear)
10643 (let* ((cbuf (current-buffer))
10644 (regionp (org-region-active-p))
10645 (region-start (and regionp (region-beginning)))
10646 (region-end (and regionp (region-end)))
10647 (region-length (and regionp (- region-end region-start)))
10648 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10649 pos it nbuf file re level reversed)
10650 (setq last-command nil)
10651 (when regionp
10652 (goto-char region-start)
10653 (or (bolp) (goto-char (point-at-bol)))
10654 (setq region-start (point))
10655 (unless (or (org-kill-is-subtree-p
10656 (buffer-substring region-start region-end))
10657 (prog1 org-refile-active-region-within-subtree
10658 (org-toggle-heading)))
10659 (error "The region is not a (sequence of) subtree(s)")))
10660 (if (equal goto '(16))
10661 (org-refile-goto-last-stored)
10662 (when (or
10663 (and (equal goto 2)
10664 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10665 (prog1
10666 (setq it (list (or org-clock-heading "running clock")
10667 (buffer-file-name
10668 (marker-buffer org-clock-hd-marker))
10670 (marker-position org-clock-hd-marker)))
10671 (setq goto nil)))
10672 (setq it (or rfloc
10673 (let (heading-text)
10674 (save-excursion
10675 (unless goto
10676 (org-back-to-heading t)
10677 (setq heading-text
10678 (nth 4 (org-heading-components))))
10679 (org-refile-get-location
10680 (cond (goto "Goto")
10681 (regionp "Refile region to")
10682 (t (concat "Refile subtree \""
10683 heading-text "\" to")))
10684 default-buffer
10685 (and (not (equal '(4) goto))
10686 org-refile-allow-creating-parent-nodes)
10687 goto))))))
10688 (setq file (nth 1 it)
10689 re (nth 2 it)
10690 pos (nth 3 it))
10691 (if (and (not goto)
10693 (equal (buffer-file-name) file)
10694 (if regionp
10695 (and (>= pos region-start)
10696 (<= pos region-end))
10697 (and (>= pos (point))
10698 (< pos (save-excursion
10699 (org-end-of-subtree t t))))))
10700 (error "Cannot refile to position inside the tree or region"))
10702 (setq nbuf (or (find-buffer-visiting file)
10703 (find-file-noselect file)))
10704 (if goto
10705 (progn
10706 (org-pop-to-buffer-same-window nbuf)
10707 (goto-char pos)
10708 (org-show-context 'org-goto))
10709 (if regionp
10710 (progn
10711 (org-kill-new (buffer-substring region-start region-end))
10712 (org-save-markers-in-region region-start region-end))
10713 (org-copy-subtree 1 nil t))
10714 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10715 (find-file-noselect file)))
10716 (setq reversed (org-notes-order-reversed-p))
10717 (save-excursion
10718 (save-restriction
10719 (widen)
10720 (if pos
10721 (progn
10722 (goto-char pos)
10723 (looking-at org-outline-regexp)
10724 (setq level (org-get-valid-level (funcall outline-level) 1))
10725 (goto-char
10726 (if reversed
10727 (or (outline-next-heading) (point-max))
10728 (or (save-excursion (org-get-next-sibling))
10729 (org-end-of-subtree t t)
10730 (point-max)))))
10731 (setq level 1)
10732 (if (not reversed)
10733 (goto-char (point-max))
10734 (goto-char (point-min))
10735 (or (outline-next-heading) (goto-char (point-max)))))
10736 (if (not (bolp)) (newline))
10737 (org-paste-subtree level)
10738 (when org-log-refile
10739 (org-add-log-setup 'refile nil nil 'findpos
10740 org-log-refile)
10741 (unless (eq org-log-refile 'note)
10742 (save-excursion (org-add-log-note))))
10743 (and org-auto-align-tags (org-set-tags nil t))
10744 (bookmark-set "org-refile-last-stored")
10745 ;; If we are refiling for capture, make sure that the
10746 ;; last-capture pointers point here
10747 (when (org-bound-and-true-p org-refile-for-capture)
10748 (bookmark-set "org-capture-last-stored-marker")
10749 (move-marker org-capture-last-stored-marker (point)))
10750 (if (fboundp 'deactivate-mark) (deactivate-mark))
10751 (run-hooks 'org-after-refile-insert-hook))))
10752 (if regionp
10753 (delete-region (point) (+ (point) region-length))
10754 (org-cut-subtree))
10755 (when (featurep 'org-inlinetask)
10756 (org-inlinetask-remove-END-maybe))
10757 (setq org-markers-to-move nil)
10758 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10760 (defun org-refile-goto-last-stored ()
10761 "Go to the location where the last refile was stored."
10762 (interactive)
10763 (bookmark-jump "org-refile-last-stored")
10764 (message "This is the location of the last refile"))
10766 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10767 no-exclude)
10768 "Prompt the user for a refile location, using PROMPT.
10769 PROMPT should not be suffixed with a colon and a space, because
10770 this function appends the default value from
10771 `org-refile-history' automatically, if that is not empty.
10772 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10773 this is used for the GOTO interface."
10774 (let ((org-refile-targets org-refile-targets)
10775 (org-refile-use-outline-path org-refile-use-outline-path)
10776 excluded-entries)
10777 (when (and (eq major-mode 'org-mode)
10778 (not org-refile-use-cache)
10779 (not no-exclude))
10780 (org-map-tree
10781 (lambda()
10782 (setq excluded-entries
10783 (append excluded-entries (list (org-get-heading t t)))))))
10784 (setq org-refile-target-table
10785 (org-refile-get-targets default-buffer excluded-entries)))
10786 (unless org-refile-target-table
10787 (error "No refile targets"))
10788 (let* ((prompt (concat prompt
10789 (and (car org-refile-history)
10790 (concat " (default " (car org-refile-history) ")"))
10791 ": "))
10792 (cbuf (current-buffer))
10793 (partial-completion-mode nil)
10794 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10795 (cfunc (if (and org-refile-use-outline-path
10796 org-outline-path-complete-in-steps)
10797 'org-olpath-completing-read
10798 'org-icompleting-read))
10799 (extra (if org-refile-use-outline-path "/" ""))
10800 (filename (and cfn (expand-file-name cfn)))
10801 (tbl (mapcar
10802 (lambda (x)
10803 (if (and (not (member org-refile-use-outline-path
10804 '(file full-file-path)))
10805 (not (equal filename (nth 1 x))))
10806 (cons (concat (car x) extra " ("
10807 (file-name-nondirectory (nth 1 x)) ")")
10808 (cdr x))
10809 (cons (concat (car x) extra) (cdr x))))
10810 org-refile-target-table))
10811 (completion-ignore-case t)
10812 pa answ parent-target child parent old-hist)
10813 (setq old-hist org-refile-history)
10814 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10815 nil 'org-refile-history (car org-refile-history)))
10816 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10817 (org-refile-check-position pa)
10818 (if pa
10819 (progn
10820 (when (or (not org-refile-history)
10821 (not (eq old-hist org-refile-history))
10822 (not (equal (car pa) (car org-refile-history))))
10823 (setq org-refile-history
10824 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10825 org-refile-history
10826 (cdr org-refile-history))))
10827 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10828 (pop org-refile-history)))
10830 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10831 (progn
10832 (setq parent (match-string 1 answ)
10833 child (match-string 2 answ))
10834 (setq parent-target (or (assoc parent tbl)
10835 (assoc (concat parent "/") tbl)))
10836 (when (and parent-target
10837 (or (eq new-nodes t)
10838 (and (eq new-nodes 'confirm)
10839 (y-or-n-p (format "Create new node \"%s\"? "
10840 child)))))
10841 (org-refile-new-child parent-target child)))
10842 (error "Invalid target location")))))
10844 (defun org-refile-check-position (refile-pointer)
10845 "Check if the refile pointer matches the readline to which it points."
10846 (let* ((file (nth 1 refile-pointer))
10847 (re (nth 2 refile-pointer))
10848 (pos (nth 3 refile-pointer))
10849 buffer)
10850 (when (org-string-nw-p re)
10851 (setq buffer (if (markerp pos)
10852 (marker-buffer pos)
10853 (or (find-buffer-visiting file)
10854 (find-file-noselect file))))
10855 (with-current-buffer buffer
10856 (save-excursion
10857 (save-restriction
10858 (widen)
10859 (goto-char pos)
10860 (beginning-of-line 1)
10861 (unless (org-looking-at-p re)
10862 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10864 (defun org-refile-new-child (parent-target child)
10865 "Use refile target PARENT-TARGET to add new CHILD below it."
10866 (unless parent-target
10867 (error "Cannot find parent for new node"))
10868 (let ((file (nth 1 parent-target))
10869 (pos (nth 3 parent-target))
10870 level)
10871 (with-current-buffer (or (find-buffer-visiting file)
10872 (find-file-noselect file))
10873 (save-excursion
10874 (save-restriction
10875 (widen)
10876 (if pos
10877 (goto-char pos)
10878 (goto-char (point-max))
10879 (if (not (bolp)) (newline)))
10880 (when (looking-at org-outline-regexp)
10881 (setq level (funcall outline-level))
10882 (org-end-of-subtree t t))
10883 (org-back-over-empty-lines)
10884 (insert "\n" (make-string
10885 (if pos (org-get-valid-level level 1) 1) ?*)
10886 " " child "\n")
10887 (beginning-of-line 0)
10888 (list (concat (car parent-target) "/" child) file "" (point)))))))
10890 (defun org-olpath-completing-read (prompt collection &rest args)
10891 "Read an outline path like a file name."
10892 (let ((thetable collection)
10893 (org-completion-use-ido nil) ; does not work with ido.
10894 (org-completion-use-iswitchb nil)) ; or iswitchb
10895 (apply
10896 'org-icompleting-read prompt
10897 (lambda (string predicate &optional flag)
10898 (let (rtn r f (l (length string)))
10899 (cond
10900 ((eq flag nil)
10901 ;; try completion
10902 (try-completion string thetable))
10903 ((eq flag t)
10904 ;; all-completions
10905 (setq rtn (all-completions string thetable predicate))
10906 (mapcar
10907 (lambda (x)
10908 (setq r (substring x l))
10909 (if (string-match " ([^)]*)$" x)
10910 (setq f (match-string 0 x))
10911 (setq f ""))
10912 (if (string-match "/" r)
10913 (concat string (substring r 0 (match-end 0)) f)
10915 rtn))
10916 ((eq flag 'lambda)
10917 ;; exact match?
10918 (assoc string thetable)))
10920 args)))
10922 ;;;; Dynamic blocks
10924 (defun org-find-dblock (name)
10925 "Find the first dynamic block with name NAME in the buffer.
10926 If not found, stay at current position and return nil."
10927 (let (pos)
10928 (save-excursion
10929 (goto-char (point-min))
10930 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10931 nil t)
10932 (match-beginning 0))))
10933 (if pos (goto-char pos))
10934 pos))
10936 (defconst org-dblock-start-re
10937 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10938 "Matches the start line of a dynamic block, with parameters.")
10940 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10941 "Matches the end of a dynamic block.")
10943 (defun org-create-dblock (plist)
10944 "Create a dynamic block section, with parameters taken from PLIST.
10945 PLIST must contain a :name entry which is used as name of the block."
10946 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10947 (end-of-line 1)
10948 (newline))
10949 (let ((col (current-column))
10950 (name (plist-get plist :name)))
10951 (insert "#+BEGIN: " name)
10952 (while plist
10953 (if (eq (car plist) :name)
10954 (setq plist (cddr plist))
10955 (insert " " (prin1-to-string (pop plist)))))
10956 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10957 (beginning-of-line -2)))
10959 (defun org-prepare-dblock ()
10960 "Prepare dynamic block for refresh.
10961 This empties the block, puts the cursor at the insert position and returns
10962 the property list including an extra property :name with the block name."
10963 (unless (looking-at org-dblock-start-re)
10964 (error "Not at a dynamic block"))
10965 (let* ((begdel (1+ (match-end 0)))
10966 (name (org-no-properties (match-string 1)))
10967 (params (append (list :name name)
10968 (read (concat "(" (match-string 3) ")")))))
10969 (save-excursion
10970 (beginning-of-line 1)
10971 (skip-chars-forward " \t")
10972 (setq params (plist-put params :indentation-column (current-column))))
10973 (unless (re-search-forward org-dblock-end-re nil t)
10974 (error "Dynamic block not terminated"))
10975 (setq params
10976 (append params
10977 (list :content (buffer-substring
10978 begdel (match-beginning 0)))))
10979 (delete-region begdel (match-beginning 0))
10980 (goto-char begdel)
10981 (open-line 1)
10982 params))
10984 (defun org-map-dblocks (&optional command)
10985 "Apply COMMAND to all dynamic blocks in the current buffer.
10986 If COMMAND is not given, use `org-update-dblock'."
10987 (let ((cmd (or command 'org-update-dblock)))
10988 (save-excursion
10989 (goto-char (point-min))
10990 (while (re-search-forward org-dblock-start-re nil t)
10991 (goto-char (match-beginning 0))
10992 (save-excursion
10993 (condition-case nil
10994 (funcall cmd)
10995 (error (message "Error during update of dynamic block"))))
10996 (unless (re-search-forward org-dblock-end-re nil t)
10997 (error "Dynamic block not terminated"))))))
10999 (defun org-dblock-update (&optional arg)
11000 "User command for updating dynamic blocks.
11001 Update the dynamic block at point. With prefix ARG, update all dynamic
11002 blocks in the buffer."
11003 (interactive "P")
11004 (if arg
11005 (org-update-all-dblocks)
11006 (or (looking-at org-dblock-start-re)
11007 (org-beginning-of-dblock))
11008 (org-update-dblock)))
11010 (defun org-update-dblock ()
11011 "Update the dynamic block at point.
11012 This means to empty the block, parse for parameters and then call
11013 the correct writing function."
11014 (interactive)
11015 (save-window-excursion
11016 (let* ((pos (point))
11017 (line (org-current-line))
11018 (params (org-prepare-dblock))
11019 (name (plist-get params :name))
11020 (indent (plist-get params :indentation-column))
11021 (cmd (intern (concat "org-dblock-write:" name))))
11022 (message "Updating dynamic block `%s' at line %d..." name line)
11023 (funcall cmd params)
11024 (message "Updating dynamic block `%s' at line %d...done" name line)
11025 (goto-char pos)
11026 (when (and indent (> indent 0))
11027 (setq indent (make-string indent ?\ ))
11028 (save-excursion
11029 (org-beginning-of-dblock)
11030 (forward-line 1)
11031 (while (not (looking-at org-dblock-end-re))
11032 (insert indent)
11033 (beginning-of-line 2))
11034 (when (looking-at org-dblock-end-re)
11035 (and (looking-at "[ \t]+")
11036 (replace-match ""))
11037 (insert indent)))))))
11039 (defun org-beginning-of-dblock ()
11040 "Find the beginning of the dynamic block at point.
11041 Error if there is no such block at point."
11042 (let ((pos (point))
11043 beg)
11044 (end-of-line 1)
11045 (if (and (re-search-backward org-dblock-start-re nil t)
11046 (setq beg (match-beginning 0))
11047 (re-search-forward org-dblock-end-re nil t)
11048 (> (match-end 0) pos))
11049 (goto-char beg)
11050 (goto-char pos)
11051 (error "Not in a dynamic block"))))
11053 (defun org-update-all-dblocks ()
11054 "Update all dynamic blocks in the buffer.
11055 This function can be used in a hook."
11056 (interactive)
11057 (when (eq major-mode 'org-mode)
11058 (org-map-dblocks 'org-update-dblock)))
11061 ;;;; Completion
11063 (defconst org-additional-option-like-keywords
11064 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11065 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11066 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11067 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11068 "BEGIN:" "END:"
11069 "ORGTBL" "TBLFM:" "TBLNAME:"
11070 "BEGIN_EXAMPLE" "END_EXAMPLE"
11071 "BEGIN_QUOTE" "END_QUOTE"
11072 "BEGIN_VERSE" "END_VERSE"
11073 "BEGIN_CENTER" "END_CENTER"
11074 "BEGIN_SRC" "END_SRC"
11075 "BEGIN_RESULT" "END_RESULT"
11076 "NAME:" "RESULTS:"
11077 "HEADER:" "HEADERS:"
11078 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11079 "CAPTION:" "LABEL:"
11080 "SETUPFILE:"
11081 "INCLUDE:"
11082 "BIND:"
11083 "MACRO:"))
11085 (defcustom org-structure-template-alist
11087 ("s" "#+begin_src ?\n\n#+end_src"
11088 "<src lang=\"?\">\n\n</src>")
11089 ("e" "#+begin_example\n?\n#+end_example"
11090 "<example>\n?\n</example>")
11091 ("q" "#+begin_quote\n?\n#+end_quote"
11092 "<quote>\n?\n</quote>")
11093 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11094 "<verse>\n?\n</verse>")
11095 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11096 "<center>\n?\n</center>")
11097 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11098 "<literal style=\"latex\">\n?\n</literal>")
11099 ("L" "#+latex: "
11100 "<literal style=\"latex\">?</literal>")
11101 ("h" "#+begin_html\n?\n#+end_html"
11102 "<literal style=\"html\">\n?\n</literal>")
11103 ("H" "#+html: "
11104 "<literal style=\"html\">?</literal>")
11105 ("a" "#+begin_ascii\n?\n#+end_ascii")
11106 ("A" "#+ascii: ")
11107 ("i" "#+index: ?"
11108 "#+index: ?")
11109 ("I" "#+include %file ?"
11110 "<include file=%file markup=\"?\">")
11112 "Structure completion elements.
11113 This is a list of abbreviation keys and values. The value gets inserted
11114 if you type `<' followed by the key and then press the completion key,
11115 usually `M-TAB'. %file will be replaced by a file name after prompting
11116 for the file using completion. The cursor will be placed at the position
11117 of the `?` in the template.
11118 There are two templates for each key, the first uses the original Org syntax,
11119 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11120 the default when the /org-mtags.el/ module has been loaded. See also the
11121 variable `org-mtags-prefer-muse-templates'.
11122 This is an experimental feature, it is undecided if it is going to stay in."
11123 :group 'org-completion
11124 :type '(repeat
11125 (string :tag "Key")
11126 (string :tag "Template")
11127 (string :tag "Muse Template")))
11129 (defun org-try-structure-completion ()
11130 "Try to complete a structure template before point.
11131 This looks for strings like \"<e\" on an otherwise empty line and
11132 expands them."
11133 (let ((l (buffer-substring (point-at-bol) (point)))
11135 (when (and (looking-at "[ \t]*$")
11136 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11137 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11138 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11139 (match-beginning 1)) a)
11140 t)))
11142 (defun org-complete-expand-structure-template (start cell)
11143 "Expand a structure template."
11144 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11145 (rpl (nth (if musep 2 1) cell))
11146 (ind ""))
11147 (delete-region start (point))
11148 (when (string-match "\\`#\\+" rpl)
11149 (cond
11150 ((bolp))
11151 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11152 (setq ind (buffer-substring (point-at-bol) (point))))
11153 (t (newline))))
11154 (setq start (point))
11155 (if (string-match "%file" rpl)
11156 (setq rpl (replace-match
11157 (concat
11158 "\""
11159 (save-match-data
11160 (abbreviate-file-name (read-file-name "Include file: ")))
11161 "\"")
11162 t t rpl)))
11163 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11164 (concat "\n" ind)))
11165 (insert rpl)
11166 (if (re-search-backward "\\?" start t) (delete-char 1))))
11168 ;;;; TODO, DEADLINE, Comments
11170 (defun org-toggle-comment ()
11171 "Change the COMMENT state of an entry."
11172 (interactive)
11173 (save-excursion
11174 (org-back-to-heading)
11175 (let (case-fold-search)
11176 (cond
11177 ((looking-at (format org-heading-keyword-regexp-format
11178 org-comment-string))
11179 (goto-char (match-end 1))
11180 (looking-at (concat " +" org-comment-string))
11181 (replace-match "" t t)
11182 (when (eolp) (insert " ")))
11183 ((looking-at org-outline-regexp)
11184 (goto-char (match-end 0))
11185 (insert org-comment-string " "))))))
11187 (defvar org-last-todo-state-is-todo nil
11188 "This is non-nil when the last TODO state change led to a TODO state.
11189 If the last change removed the TODO tag or switched to DONE, then
11190 this is nil.")
11192 (defvar org-setting-tags nil) ; dynamically skipped
11194 (defvar org-todo-setup-filter-hook nil
11195 "Hook for functions that pre-filter todo specs.
11196 Each function takes a todo spec and returns either nil or the spec
11197 transformed into canonical form." )
11199 (defvar org-todo-get-default-hook nil
11200 "Hook for functions that get a default item for todo.
11201 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11202 nil or a string to be used for the todo mark." )
11204 (defvar org-agenda-headline-snapshot-before-repeat)
11206 (defun org-current-effective-time ()
11207 "Return current time adjusted for `org-extend-today-until' variable"
11208 (let* ((ct (org-current-time))
11209 (dct (decode-time ct))
11210 (ct1
11211 (if (and org-use-effective-time
11212 (< (nth 2 dct) org-extend-today-until))
11213 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11214 ct)))
11215 ct1))
11217 (defun org-todo-yesterday (&optional arg)
11218 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11219 (interactive "P")
11220 (if (eq major-mode 'org-agenda-mode)
11221 (apply 'org-agenda-todo-yesterday arg)
11222 (let* ((hour (third (decode-time
11223 (org-current-time))))
11224 (org-extend-today-until (1+ hour)))
11225 (org-todo arg))))
11227 (defun org-todo (&optional arg)
11228 "Change the TODO state of an item.
11229 The state of an item is given by a keyword at the start of the heading,
11230 like
11231 *** TODO Write paper
11232 *** DONE Call mom
11234 The different keywords are specified in the variable `org-todo-keywords'.
11235 By default the available states are \"TODO\" and \"DONE\".
11236 So for this example: when the item starts with TODO, it is changed to DONE.
11237 When it starts with DONE, the DONE is removed. And when neither TODO nor
11238 DONE are present, add TODO at the beginning of the heading.
11240 With \\[universal-argument] prefix arg, use completion to determine the new \
11241 state.
11242 With numeric prefix arg, switch to that state.
11243 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11244 keywords (nextset).
11245 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11246 With a numeric prefix arg of 0, inhibit note taking for the change.
11248 For calling through lisp, arg is also interpreted in the following way:
11249 'none -> empty state
11250 \"\"(empty string) -> switch to empty state
11251 'done -> switch to DONE
11252 'nextset -> switch to the next set of keywords
11253 'previousset -> switch to the previous set of keywords
11254 \"WAITING\" -> switch to the specified keyword, but only if it
11255 really is a member of `org-todo-keywords'."
11256 (interactive "P")
11257 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11258 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11259 'region-start-level 'region))
11260 org-loop-over-headlines-in-active-region)
11261 (org-map-entries
11262 `(org-todo ,arg)
11263 org-loop-over-headlines-in-active-region
11264 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11265 (if (equal arg '(16)) (setq arg 'nextset))
11266 (let ((org-blocker-hook org-blocker-hook)
11267 (case-fold-search nil))
11268 (when (equal arg '(64))
11269 (setq arg nil org-blocker-hook nil))
11270 (when (and org-blocker-hook
11271 (or org-inhibit-blocking
11272 (org-entry-get nil "NOBLOCKING")))
11273 (setq org-blocker-hook nil))
11274 (save-excursion
11275 (catch 'exit
11276 (org-back-to-heading t)
11277 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11278 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11279 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11280 (let* ((match-data (match-data))
11281 (startpos (point-at-bol))
11282 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11283 (org-log-done org-log-done)
11284 (org-log-repeat org-log-repeat)
11285 (org-todo-log-states org-todo-log-states)
11286 (org-inhibit-logging
11287 (if (equal arg 0)
11288 (progn (setq arg nil) 'note) org-inhibit-logging))
11289 (this (match-string 1))
11290 (hl-pos (match-beginning 0))
11291 (head (org-get-todo-sequence-head this))
11292 (ass (assoc head org-todo-kwd-alist))
11293 (interpret (nth 1 ass))
11294 (done-word (nth 3 ass))
11295 (final-done-word (nth 4 ass))
11296 (org-last-state (or this ""))
11297 (completion-ignore-case t)
11298 (member (member this org-todo-keywords-1))
11299 (tail (cdr member))
11300 (org-state (cond
11301 ((and org-todo-key-trigger
11302 (or (and (equal arg '(4))
11303 (eq org-use-fast-todo-selection 'prefix))
11304 (and (not arg) org-use-fast-todo-selection
11305 (not (eq org-use-fast-todo-selection
11306 'prefix)))))
11307 ;; Use fast selection
11308 (org-fast-todo-selection))
11309 ((and (equal arg '(4))
11310 (or (not org-use-fast-todo-selection)
11311 (not org-todo-key-trigger)))
11312 ;; Read a state with completion
11313 (org-icompleting-read
11314 "State: " (mapcar (lambda(x) (list x))
11315 org-todo-keywords-1)
11316 nil t))
11317 ((eq arg 'right)
11318 (if this
11319 (if tail (car tail) nil)
11320 (car org-todo-keywords-1)))
11321 ((eq arg 'left)
11322 (if (equal member org-todo-keywords-1)
11324 (if this
11325 (nth (- (length org-todo-keywords-1)
11326 (length tail) 2)
11327 org-todo-keywords-1)
11328 (org-last org-todo-keywords-1))))
11329 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11330 (setq arg nil))) ; hack to fall back to cycling
11331 (arg
11332 ;; user or caller requests a specific state
11333 (cond
11334 ((equal arg "") nil)
11335 ((eq arg 'none) nil)
11336 ((eq arg 'done) (or done-word (car org-done-keywords)))
11337 ((eq arg 'nextset)
11338 (or (car (cdr (member head org-todo-heads)))
11339 (car org-todo-heads)))
11340 ((eq arg 'previousset)
11341 (let ((org-todo-heads (reverse org-todo-heads)))
11342 (or (car (cdr (member head org-todo-heads)))
11343 (car org-todo-heads))))
11344 ((car (member arg org-todo-keywords-1)))
11345 ((stringp arg)
11346 (error "State `%s' not valid in this file" arg))
11347 ((nth (1- (prefix-numeric-value arg))
11348 org-todo-keywords-1))))
11349 ((null member) (or head (car org-todo-keywords-1)))
11350 ((equal this final-done-word) nil) ;; -> make empty
11351 ((null tail) nil) ;; -> first entry
11352 ((memq interpret '(type priority))
11353 (if (eq this-command last-command)
11354 (car tail)
11355 (if (> (length tail) 0)
11356 (or done-word (car org-done-keywords))
11357 nil)))
11359 (car tail))))
11360 (org-state (or
11361 (run-hook-with-args-until-success
11362 'org-todo-get-default-hook org-state org-last-state)
11363 org-state))
11364 (next (if org-state (concat " " org-state " ") " "))
11365 (change-plist (list :type 'todo-state-change :from this :to org-state
11366 :position startpos))
11367 dolog now-done-p)
11368 (when org-blocker-hook
11369 (setq org-last-todo-state-is-todo
11370 (not (member this org-done-keywords)))
11371 (unless (save-excursion
11372 (save-match-data
11373 (org-with-wide-buffer
11374 (run-hook-with-args-until-failure
11375 'org-blocker-hook change-plist))))
11376 (if (org-called-interactively-p 'interactive)
11377 (error "TODO state change from %s to %s blocked" this org-state)
11378 ;; fail silently
11379 (message "TODO state change from %s to %s blocked" this org-state)
11380 (throw 'exit nil))))
11381 (store-match-data match-data)
11382 (replace-match next t t)
11383 (unless (pos-visible-in-window-p hl-pos)
11384 (message "TODO state changed to %s" (org-trim next)))
11385 (unless head
11386 (setq head (org-get-todo-sequence-head org-state)
11387 ass (assoc head org-todo-kwd-alist)
11388 interpret (nth 1 ass)
11389 done-word (nth 3 ass)
11390 final-done-word (nth 4 ass)))
11391 (when (memq arg '(nextset previousset))
11392 (message "Keyword-Set %d/%d: %s"
11393 (- (length org-todo-sets) -1
11394 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11395 (length org-todo-sets)
11396 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11397 (setq org-last-todo-state-is-todo
11398 (not (member org-state org-done-keywords)))
11399 (setq now-done-p (and (member org-state org-done-keywords)
11400 (not (member this org-done-keywords))))
11401 (and logging (org-local-logging logging))
11402 (when (and (or org-todo-log-states org-log-done)
11403 (not (eq org-inhibit-logging t))
11404 (not (memq arg '(nextset previousset))))
11405 ;; we need to look at recording a time and note
11406 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11407 (nth 2 (assoc this org-todo-log-states))))
11408 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11409 (setq dolog 'time))
11410 (when (and org-state
11411 (member org-state org-not-done-keywords)
11412 (not (member this org-not-done-keywords)))
11413 ;; This is now a todo state and was not one before
11414 ;; If there was a CLOSED time stamp, get rid of it.
11415 (org-add-planning-info nil nil 'closed))
11416 (when (and now-done-p org-log-done)
11417 ;; It is now done, and it was not done before
11418 (org-add-planning-info 'closed (org-current-effective-time))
11419 (if (and (not dolog) (eq 'note org-log-done))
11420 (org-add-log-setup 'done org-state this 'findpos 'note)))
11421 (when (and org-state dolog)
11422 ;; This is a non-nil state, and we need to log it
11423 (org-add-log-setup 'state org-state this 'findpos dolog)))
11424 ;; Fixup tag positioning
11425 (org-todo-trigger-tag-changes org-state)
11426 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11427 (when org-provide-todo-statistics
11428 (org-update-parent-todo-statistics))
11429 (run-hooks 'org-after-todo-state-change-hook)
11430 (if (and arg (not (member org-state org-done-keywords)))
11431 (setq head (org-get-todo-sequence-head org-state)))
11432 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11433 ;; Do we need to trigger a repeat?
11434 (when now-done-p
11435 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11436 ;; This is for the agenda, take a snapshot of the headline.
11437 (save-match-data
11438 (setq org-agenda-headline-snapshot-before-repeat
11439 (org-get-heading))))
11440 (org-auto-repeat-maybe org-state))
11441 ;; Fixup cursor location if close to the keyword
11442 (if (and (outline-on-heading-p)
11443 (not (bolp))
11444 (save-excursion (beginning-of-line 1)
11445 (looking-at org-todo-line-regexp))
11446 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11447 (progn
11448 (goto-char (or (match-end 2) (match-end 1)))
11449 (and (looking-at " ") (just-one-space))))
11450 (when org-trigger-hook
11451 (save-excursion
11452 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11454 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11455 "Block turning an entry into a TODO, using the hierarchy.
11456 This checks whether the current task should be blocked from state
11457 changes. Such blocking occurs when:
11459 1. The task has children which are not all in a completed state.
11461 2. A task has a parent with the property :ORDERED:, and there
11462 are siblings prior to the current task with incomplete
11463 status.
11465 3. The parent of the task is blocked because it has siblings that should
11466 be done first, or is child of a block grandparent TODO entry."
11468 (if (not org-enforce-todo-dependencies)
11469 t ; if locally turned off don't block
11470 (catch 'dont-block
11471 ;; If this is not a todo state change, or if this entry is already DONE,
11472 ;; do not block
11473 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11474 (member (plist-get change-plist :from)
11475 (cons 'done org-done-keywords))
11476 (member (plist-get change-plist :to)
11477 (cons 'todo org-not-done-keywords))
11478 (not (plist-get change-plist :to)))
11479 (throw 'dont-block t))
11480 ;; If this task has children, and any are undone, it's blocked
11481 (save-excursion
11482 (org-back-to-heading t)
11483 (let ((this-level (funcall outline-level)))
11484 (outline-next-heading)
11485 (let ((child-level (funcall outline-level)))
11486 (while (and (not (eobp))
11487 (> child-level this-level))
11488 ;; this todo has children, check whether they are all
11489 ;; completed
11490 (if (and (not (org-entry-is-done-p))
11491 (org-entry-is-todo-p))
11492 (throw 'dont-block nil))
11493 (outline-next-heading)
11494 (setq child-level (funcall outline-level))))))
11495 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11496 ;; any previous siblings are undone, it's blocked
11497 (save-excursion
11498 (org-back-to-heading t)
11499 (let* ((pos (point))
11500 (parent-pos (and (org-up-heading-safe) (point))))
11501 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11502 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11503 (forward-line 1)
11504 (re-search-forward org-not-done-heading-regexp pos t))
11505 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11506 ;; Search further up the hierarchy, to see if an ancestor is blocked
11507 (while t
11508 (goto-char parent-pos)
11509 (if (not (looking-at org-not-done-heading-regexp))
11510 (throw 'dont-block t)) ; do not block, parent is not a TODO
11511 (setq pos (point))
11512 (setq parent-pos (and (org-up-heading-safe) (point)))
11513 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11514 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11515 (forward-line 1)
11516 (re-search-forward org-not-done-heading-regexp pos t))
11517 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11519 (defcustom org-track-ordered-property-with-tag nil
11520 "Should the ORDERED property also be shown as a tag?
11521 The ORDERED property decides if an entry should require subtasks to be
11522 completed in sequence. Since a property is not very visible, setting
11523 this option means that toggling the ORDERED property with the command
11524 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11525 not relevant for the behavior, but it makes things more visible.
11527 Note that toggling the tag with tags commands will not change the property
11528 and therefore not influence behavior!
11530 This can be t, meaning the tag ORDERED should be used, It can also be a
11531 string to select a different tag for this task."
11532 :group 'org-todo
11533 :type '(choice
11534 (const :tag "No tracking" nil)
11535 (const :tag "Track with ORDERED tag" t)
11536 (string :tag "Use other tag")))
11538 (defun org-toggle-ordered-property ()
11539 "Toggle the ORDERED property of the current entry.
11540 For better visibility, you can track the value of this property with a tag.
11541 See variable `org-track-ordered-property-with-tag'."
11542 (interactive)
11543 (let* ((t1 org-track-ordered-property-with-tag)
11544 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11545 (save-excursion
11546 (org-back-to-heading)
11547 (if (org-entry-get nil "ORDERED")
11548 (progn
11549 (org-delete-property "ORDERED")
11550 (and tag (org-toggle-tag tag 'off))
11551 (message "Subtasks can be completed in arbitrary order"))
11552 (org-entry-put nil "ORDERED" "t")
11553 (and tag (org-toggle-tag tag 'on))
11554 (message "Subtasks must be completed in sequence")))))
11556 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11557 (defun org-block-todo-from-checkboxes (change-plist)
11558 "Block turning an entry into a TODO, using checkboxes.
11559 This checks whether the current task should be blocked from state
11560 changes because there are unchecked boxes in this entry."
11561 (if (not org-enforce-todo-checkbox-dependencies)
11562 t ; if locally turned off don't block
11563 (catch 'dont-block
11564 ;; If this is not a todo state change, or if this entry is already DONE,
11565 ;; do not block
11566 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11567 (member (plist-get change-plist :from)
11568 (cons 'done org-done-keywords))
11569 (member (plist-get change-plist :to)
11570 (cons 'todo org-not-done-keywords))
11571 (not (plist-get change-plist :to)))
11572 (throw 'dont-block t))
11573 ;; If this task has checkboxes that are not checked, it's blocked
11574 (save-excursion
11575 (org-back-to-heading t)
11576 (let ((beg (point)) end)
11577 (outline-next-heading)
11578 (setq end (point))
11579 (goto-char beg)
11580 (if (org-list-search-forward
11581 (concat (org-item-beginning-re)
11582 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11583 "\\[[- ]\\]")
11584 end t)
11585 (progn
11586 (if (boundp 'org-blocked-by-checkboxes)
11587 (setq org-blocked-by-checkboxes t))
11588 (throw 'dont-block nil)))))
11589 t))) ; do not block
11591 (defun org-entry-blocked-p ()
11592 "Is the current entry blocked?"
11593 (if (org-entry-get nil "NOBLOCKING")
11594 nil ;; Never block this entry
11595 (not
11596 (run-hook-with-args-until-failure
11597 'org-blocker-hook
11598 (list :type 'todo-state-change
11599 :position (point)
11600 :from 'todo
11601 :to 'done)))))
11603 (defun org-update-statistics-cookies (all)
11604 "Update the statistics cookie, either from TODO or from checkboxes.
11605 This should be called with the cursor in a line with a statistics cookie."
11606 (interactive "P")
11607 (if all
11608 (progn
11609 (org-update-checkbox-count 'all)
11610 (org-map-entries 'org-update-parent-todo-statistics))
11611 (if (not (org-at-heading-p))
11612 (org-update-checkbox-count)
11613 (let ((pos (move-marker (make-marker) (point)))
11614 end l1 l2)
11615 (ignore-errors (org-back-to-heading t))
11616 (if (not (org-at-heading-p))
11617 (org-update-checkbox-count)
11618 (setq l1 (org-outline-level))
11619 (setq end (save-excursion
11620 (outline-next-heading)
11621 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11622 (point)))
11623 (if (and (save-excursion
11624 (re-search-forward
11625 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11626 (not (save-excursion (re-search-forward
11627 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11628 (org-update-checkbox-count)
11629 (if (and l2 (> l2 l1))
11630 (progn
11631 (goto-char end)
11632 (org-update-parent-todo-statistics))
11633 (goto-char pos)
11634 (beginning-of-line 1)
11635 (while (re-search-forward
11636 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11637 (point-at-eol) t)
11638 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11639 (goto-char pos)
11640 (move-marker pos nil)))))
11642 (defvar org-entry-property-inherited-from) ;; defined below
11643 (defun org-update-parent-todo-statistics ()
11644 "Update any statistics cookie in the parent of the current headline.
11645 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11646 the entire subtree and this will travel up the hierarchy and update
11647 statistics everywhere."
11648 (let* ((prop (save-excursion (org-up-heading-safe)
11649 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11650 (recursive (or (not org-hierarchical-todo-statistics)
11651 (and prop (string-match "\\<recursive\\>" prop))))
11652 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11654 (first t)
11655 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11656 level ltoggle l1 new ndel
11657 (cnt-all 0) (cnt-done 0) is-percent kwd
11658 checkbox-beg ov ovs ove cookie-present)
11659 (catch 'exit
11660 (save-excursion
11661 (beginning-of-line 1)
11662 (setq ltoggle (funcall outline-level))
11663 ;; Three situations are to consider:
11665 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11666 ;; to the top-level ancestor on the headline;
11668 ;; 2. If parent has "recursive" property, repeat up to the
11669 ;; headline setting that property, taking inheritance into
11670 ;; account;
11672 ;; 3. Else, move up to direct parent and proceed only once.
11673 (while (and (setq level (org-up-heading-safe))
11674 (or recursive first)
11675 (>= (point) lim))
11676 (setq first nil cookie-present nil)
11677 (unless (and level
11678 (not (string-match
11679 "\\<checkbox\\>"
11680 (downcase (or (org-entry-get nil "COOKIE_DATA")
11681 "")))))
11682 (throw 'exit nil))
11683 (while (re-search-forward box-re (point-at-eol) t)
11684 (setq cnt-all 0 cnt-done 0 cookie-present t)
11685 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11686 (save-match-data
11687 (unless (outline-next-heading) (throw 'exit nil))
11688 (while (and (looking-at org-complex-heading-regexp)
11689 (> (setq l1 (length (match-string 1))) level))
11690 (setq kwd (and (or recursive (= l1 ltoggle))
11691 (match-string 2)))
11692 (if (or (eq org-provide-todo-statistics 'all-headlines)
11693 (and (listp org-provide-todo-statistics)
11694 (or (member kwd org-provide-todo-statistics)
11695 (member kwd org-done-keywords))))
11696 (setq cnt-all (1+ cnt-all))
11697 (if (eq org-provide-todo-statistics t)
11698 (and kwd (setq cnt-all (1+ cnt-all)))))
11699 (and (member kwd org-done-keywords)
11700 (setq cnt-done (1+ cnt-done)))
11701 (outline-next-heading)))
11702 (setq new
11703 (if is-percent
11704 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11705 (format "[%d/%d]" cnt-done cnt-all))
11706 ndel (- (match-end 0) checkbox-beg))
11707 ;; handle overlays when updating cookie from column view
11708 (when (setq ov (car (overlays-at checkbox-beg)))
11709 (setq ovs (overlay-start ov) ove (overlay-end ov))
11710 (delete-overlay ov))
11711 (goto-char checkbox-beg)
11712 (insert new)
11713 (delete-region (point) (+ (point) ndel))
11714 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11715 (when ov (move-overlay ov ovs ove)))
11716 (when cookie-present
11717 (run-hook-with-args 'org-after-todo-statistics-hook
11718 cnt-done (- cnt-all cnt-done))))))
11719 (run-hooks 'org-todo-statistics-hook)))
11721 (defvar org-after-todo-statistics-hook nil
11722 "Hook that is called after a TODO statistics cookie has been updated.
11723 Each function is called with two arguments: the number of not-done entries
11724 and the number of done entries.
11726 For example, the following function, when added to this hook, will switch
11727 an entry to DONE when all children are done, and back to TODO when new
11728 entries are set to a TODO status. Note that this hook is only called
11729 when there is a statistics cookie in the headline!
11731 (defun org-summary-todo (n-done n-not-done)
11732 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11733 (let (org-log-done org-log-states) ; turn off logging
11734 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11737 (defvar org-todo-statistics-hook nil
11738 "Hook that is run whenever Org thinks TODO statistics should be updated.
11739 This hook runs even if there is no statistics cookie present, in which case
11740 `org-after-todo-statistics-hook' would not run.")
11742 (defun org-todo-trigger-tag-changes (state)
11743 "Apply the changes defined in `org-todo-state-tags-triggers'."
11744 (let ((l org-todo-state-tags-triggers)
11745 changes)
11746 (when (or (not state) (equal state ""))
11747 (setq changes (append changes (cdr (assoc "" l)))))
11748 (when (and (stringp state) (> (length state) 0))
11749 (setq changes (append changes (cdr (assoc state l)))))
11750 (when (member state org-not-done-keywords)
11751 (setq changes (append changes (cdr (assoc 'todo l)))))
11752 (when (member state org-done-keywords)
11753 (setq changes (append changes (cdr (assoc 'done l)))))
11754 (dolist (c changes)
11755 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11757 (defun org-local-logging (value)
11758 "Get logging settings from a property VALUE."
11759 (let* (words w a)
11760 ;; directly set the variables, they are already local.
11761 (setq org-log-done nil
11762 org-log-repeat nil
11763 org-todo-log-states nil)
11764 (setq words (org-split-string value))
11765 (while (setq w (pop words))
11766 (cond
11767 ((setq a (assoc w org-startup-options))
11768 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11769 (set (nth 1 a) (nth 2 a))))
11770 ((setq a (org-extract-log-state-settings w))
11771 (and (member (car a) org-todo-keywords-1)
11772 (push a org-todo-log-states)))))))
11774 (defun org-get-todo-sequence-head (kwd)
11775 "Return the head of the TODO sequence to which KWD belongs.
11776 If KWD is not set, check if there is a text property remembering the
11777 right sequence."
11778 (let (p)
11779 (cond
11780 ((not kwd)
11781 (or (get-text-property (point-at-bol) 'org-todo-head)
11782 (progn
11783 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11784 nil (point-at-eol)))
11785 (get-text-property p 'org-todo-head))))
11786 ((not (member kwd org-todo-keywords-1))
11787 (car org-todo-keywords-1))
11788 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11790 (defun org-fast-todo-selection ()
11791 "Fast TODO keyword selection with single keys.
11792 Returns the new TODO keyword, or nil if no state change should occur."
11793 (let* ((fulltable org-todo-key-alist)
11794 (done-keywords org-done-keywords) ;; needed for the faces.
11795 (maxlen (apply 'max (mapcar
11796 (lambda (x)
11797 (if (stringp (car x)) (string-width (car x)) 0))
11798 fulltable)))
11799 (expert nil)
11800 (fwidth (+ maxlen 3 1 3))
11801 (ncol (/ (- (window-width) 4) fwidth))
11802 tg cnt e c tbl
11803 groups ingroup)
11804 (save-excursion
11805 (save-window-excursion
11806 (if expert
11807 (set-buffer (get-buffer-create " *Org todo*"))
11808 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11809 (erase-buffer)
11810 (org-set-local 'org-done-keywords done-keywords)
11811 (setq tbl fulltable cnt 0)
11812 (while (setq e (pop tbl))
11813 (cond
11814 ((equal e '(:startgroup))
11815 (push '() groups) (setq ingroup t)
11816 (when (not (= cnt 0))
11817 (setq cnt 0)
11818 (insert "\n"))
11819 (insert "{ "))
11820 ((equal e '(:endgroup))
11821 (setq ingroup nil cnt 0)
11822 (insert "}\n"))
11823 ((equal e '(:newline))
11824 (when (not (= cnt 0))
11825 (setq cnt 0)
11826 (insert "\n")
11827 (setq e (car tbl))
11828 (while (equal (car tbl) '(:newline))
11829 (insert "\n")
11830 (setq tbl (cdr tbl)))))
11832 (setq tg (car e) c (cdr e))
11833 (if ingroup (push tg (car groups)))
11834 (setq tg (org-add-props tg nil 'face
11835 (org-get-todo-face tg)))
11836 (if (and (= cnt 0) (not ingroup)) (insert " "))
11837 (insert "[" c "] " tg (make-string
11838 (- fwidth 4 (length tg)) ?\ ))
11839 (when (= (setq cnt (1+ cnt)) ncol)
11840 (insert "\n")
11841 (if ingroup (insert " "))
11842 (setq cnt 0)))))
11843 (insert "\n")
11844 (goto-char (point-min))
11845 (if (not expert) (org-fit-window-to-buffer))
11846 (message "[a-z..]:Set [SPC]:clear")
11847 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11848 (cond
11849 ((or (= c ?\C-g)
11850 (and (= c ?q) (not (rassoc c fulltable))))
11851 (setq quit-flag t))
11852 ((= c ?\ ) nil)
11853 ((setq e (rassoc c fulltable) tg (car e))
11855 (t (setq quit-flag t)))))))
11857 (defun org-entry-is-todo-p ()
11858 (member (org-get-todo-state) org-not-done-keywords))
11860 (defun org-entry-is-done-p ()
11861 (member (org-get-todo-state) org-done-keywords))
11863 (defun org-get-todo-state ()
11864 (save-excursion
11865 (org-back-to-heading t)
11866 (and (looking-at org-todo-line-regexp)
11867 (match-end 2)
11868 (match-string 2))))
11870 (defun org-at-date-range-p (&optional inactive-ok)
11871 "Is the cursor inside a date range?"
11872 (interactive)
11873 (save-excursion
11874 (catch 'exit
11875 (let ((pos (point)))
11876 (skip-chars-backward "^[<\r\n")
11877 (skip-chars-backward "<[")
11878 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11879 (>= (match-end 0) pos)
11880 (throw 'exit t))
11881 (skip-chars-backward "^<[\r\n")
11882 (skip-chars-backward "<[")
11883 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11884 (>= (match-end 0) pos)
11885 (throw 'exit t)))
11886 nil)))
11888 (defun org-get-repeat (&optional tagline)
11889 "Check if there is a deadline/schedule with repeater in this entry."
11890 (save-match-data
11891 (save-excursion
11892 (org-back-to-heading t)
11893 (and (re-search-forward (if tagline
11894 (concat tagline "\\s-*" org-repeat-re)
11895 org-repeat-re)
11896 (org-entry-end-position) t)
11897 (match-string-no-properties 1)))))
11899 (defvar org-last-changed-timestamp)
11900 (defvar org-last-inserted-timestamp)
11901 (defvar org-log-post-message)
11902 (defvar org-log-note-purpose)
11903 (defvar org-log-note-how)
11904 (defvar org-log-note-extra)
11905 (defun org-auto-repeat-maybe (done-word)
11906 "Check if the current headline contains a repeated deadline/schedule.
11907 If yes, set TODO state back to what it was and change the base date
11908 of repeating deadline/scheduled time stamps to new date.
11909 This function is run automatically after each state change to a DONE state."
11910 ;; last-state is dynamically scoped into this function
11911 (let* ((repeat (org-get-repeat))
11912 (aa (assoc org-last-state org-todo-kwd-alist))
11913 (interpret (nth 1 aa))
11914 (head (nth 2 aa))
11915 (whata '(("d" . day) ("m" . month) ("y" . year)))
11916 (msg "Entry repeats: ")
11917 (org-log-done nil)
11918 (org-todo-log-states nil)
11919 re type n what ts time to-state)
11920 (when repeat
11921 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11922 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11923 org-todo-repeat-to-state))
11924 (unless (and to-state (member to-state org-todo-keywords-1))
11925 (setq to-state (if (eq interpret 'type) org-last-state head)))
11926 (org-todo to-state)
11927 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11928 (org-entry-put nil "LAST_REPEAT" (format-time-string
11929 (org-time-stamp-format t t))))
11930 (when org-log-repeat
11931 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11932 (memq 'org-add-log-note post-command-hook))
11933 ;; OK, we are already setup for some record
11934 (if (eq org-log-repeat 'note)
11935 ;; make sure we take a note, not only a time stamp
11936 (setq org-log-note-how 'note))
11937 ;; Set up for taking a record
11938 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11939 org-last-state
11940 'findpos org-log-repeat)))
11941 (org-back-to-heading t)
11942 (org-add-planning-info nil nil 'closed)
11943 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11944 org-deadline-time-regexp "\\)\\|\\("
11945 org-ts-regexp "\\)"))
11946 (while (re-search-forward
11947 re (save-excursion (outline-next-heading) (point)) t)
11948 (setq type (if (match-end 1) org-scheduled-string
11949 (if (match-end 3) org-deadline-string "Plain:"))
11950 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11951 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11952 (setq n (string-to-number (match-string 2 ts))
11953 what (match-string 3 ts))
11954 (if (equal what "w") (setq n (* n 7) what "d"))
11955 ;; Preparation, see if we need to modify the start date for the change
11956 (when (match-end 1)
11957 (setq time (save-match-data (org-time-string-to-time ts)))
11958 (cond
11959 ((equal (match-string 1 ts) ".")
11960 ;; Shift starting date to today
11961 (org-timestamp-change
11962 (- (org-today) (time-to-days time))
11963 'day))
11964 ((equal (match-string 1 ts) "+")
11965 (let ((nshiftmax 10) (nshift 0))
11966 (while (or (= nshift 0)
11967 (<= (time-to-days time)
11968 (time-to-days (current-time))))
11969 (when (= (incf nshift) nshiftmax)
11970 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11971 (error "Abort")))
11972 (org-timestamp-change n (cdr (assoc what whata)))
11973 (org-at-timestamp-p t)
11974 (setq ts (match-string 1))
11975 (setq time (save-match-data (org-time-string-to-time ts)))))
11976 (org-timestamp-change (- n) (cdr (assoc what whata)))
11977 ;; rematch, so that we have everything in place for the real shift
11978 (org-at-timestamp-p t)
11979 (setq ts (match-string 1))
11980 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11981 (org-timestamp-change n (cdr (assoc what whata)))
11982 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11983 (setq org-log-post-message msg)
11984 (message "%s" msg))))
11986 (defun org-show-todo-tree (arg)
11987 "Make a compact tree which shows all headlines marked with TODO.
11988 The tree will show the lines where the regexp matches, and all higher
11989 headlines above the match.
11990 With a \\[universal-argument] prefix, prompt for a regexp to match.
11991 With a numeric prefix N, construct a sparse tree for the Nth element
11992 of `org-todo-keywords-1'."
11993 (interactive "P")
11994 (let ((case-fold-search nil)
11995 (kwd-re
11996 (cond ((null arg) org-not-done-regexp)
11997 ((equal arg '(4))
11998 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11999 (mapcar 'list org-todo-keywords-1))))
12000 (concat "\\("
12001 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12002 "\\)\\>")))
12003 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12004 (regexp-quote (nth (1- (prefix-numeric-value arg))
12005 org-todo-keywords-1)))
12006 (t (error "Invalid prefix argument: %s" arg)))))
12007 (message "%d TODO entries found"
12008 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12010 (defun org-deadline (&optional remove time)
12011 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12012 With argument REMOVE, remove any deadline from the item.
12013 With argument TIME, set the deadline at the corresponding date. TIME
12014 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12015 (interactive "P")
12016 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12017 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12018 'region-start-level 'region))
12019 org-loop-over-headlines-in-active-region)
12020 (org-map-entries
12021 `(org-deadline ',remove ,time)
12022 org-loop-over-headlines-in-active-region
12023 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12024 (let* ((old-date (org-entry-get nil "DEADLINE"))
12025 (repeater (and old-date
12026 (string-match
12027 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12028 old-date)
12029 (match-string 1 old-date))))
12030 (if remove
12031 (progn
12032 (when (and old-date org-log-redeadline)
12033 (org-add-log-setup 'deldeadline nil old-date 'findpos
12034 org-log-redeadline))
12035 (org-remove-timestamp-with-keyword org-deadline-string)
12036 (message "Item no longer has a deadline."))
12037 (org-add-planning-info 'deadline time 'closed)
12038 (when (and old-date org-log-redeadline
12039 (not (equal old-date
12040 (substring org-last-inserted-timestamp 1 -1))))
12041 (org-add-log-setup 'redeadline nil old-date 'findpos
12042 org-log-redeadline))
12043 (when repeater
12044 (save-excursion
12045 (org-back-to-heading t)
12046 (when (re-search-forward (concat org-deadline-string " "
12047 org-last-inserted-timestamp)
12048 (save-excursion
12049 (outline-next-heading) (point)) t)
12050 (goto-char (1- (match-end 0)))
12051 (insert " " repeater)
12052 (setq org-last-inserted-timestamp
12053 (concat (substring org-last-inserted-timestamp 0 -1)
12054 " " repeater
12055 (substring org-last-inserted-timestamp -1))))))
12056 (message "Deadline on %s" org-last-inserted-timestamp)))))
12058 (defun org-schedule (&optional remove time)
12059 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12060 With argument REMOVE, remove any scheduling date from the item.
12061 With argument TIME, scheduled at the corresponding date. TIME can
12062 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12063 (interactive "P")
12064 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12065 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12066 'region-start-level 'region))
12067 org-loop-over-headlines-in-active-region)
12068 (org-map-entries
12069 `(org-schedule ',remove ,time)
12070 org-loop-over-headlines-in-active-region
12071 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12072 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12073 (repeater (and old-date
12074 (string-match
12075 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12076 old-date)
12077 (match-string 1 old-date))))
12078 (if remove
12079 (progn
12080 (when (and old-date org-log-reschedule)
12081 (org-add-log-setup 'delschedule nil old-date 'findpos
12082 org-log-reschedule))
12083 (org-remove-timestamp-with-keyword org-scheduled-string)
12084 (message "Item is no longer scheduled."))
12085 (org-add-planning-info 'scheduled time 'closed)
12086 (when (and old-date org-log-reschedule
12087 (not (equal old-date
12088 (substring org-last-inserted-timestamp 1 -1))))
12089 (org-add-log-setup 'reschedule nil old-date 'findpos
12090 org-log-reschedule))
12091 (when repeater
12092 (save-excursion
12093 (org-back-to-heading t)
12094 (when (re-search-forward (concat org-scheduled-string " "
12095 org-last-inserted-timestamp)
12096 (save-excursion
12097 (outline-next-heading) (point)) t)
12098 (goto-char (1- (match-end 0)))
12099 (insert " " repeater)
12100 (setq org-last-inserted-timestamp
12101 (concat (substring org-last-inserted-timestamp 0 -1)
12102 " " repeater
12103 (substring org-last-inserted-timestamp -1))))))
12104 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12106 (defun org-get-scheduled-time (pom &optional inherit)
12107 "Get the scheduled time as a time tuple, of a format suitable
12108 for calling org-schedule with, or if there is no scheduling,
12109 returns nil."
12110 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12111 (when time
12112 (apply 'encode-time (org-parse-time-string time)))))
12114 (defun org-get-deadline-time (pom &optional inherit)
12115 "Get the deadline as a time tuple, of a format suitable for
12116 calling org-deadline with, or if there is no scheduling, returns
12117 nil."
12118 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12119 (when time
12120 (apply 'encode-time (org-parse-time-string time)))))
12122 (defun org-remove-timestamp-with-keyword (keyword)
12123 "Remove all time stamps with KEYWORD in the current entry."
12124 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12125 beg)
12126 (save-excursion
12127 (org-back-to-heading t)
12128 (setq beg (point))
12129 (outline-next-heading)
12130 (while (re-search-backward re beg t)
12131 (replace-match "")
12132 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12133 (equal (char-before) ?\ ))
12134 (backward-delete-char 1)
12135 (if (string-match "^[ \t]*$" (buffer-substring
12136 (point-at-bol) (point-at-eol)))
12137 (delete-region (point-at-bol)
12138 (min (point-max) (1+ (point-at-eol))))))))))
12140 (defun org-add-planning-info (what &optional time &rest remove)
12141 "Insert new timestamp with keyword in the line directly after the headline.
12142 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12143 If non is given, the user is prompted for a date.
12144 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12145 be removed."
12146 (interactive)
12147 (let (org-time-was-given org-end-time-was-given ts
12148 end default-time default-input)
12150 (catch 'exit
12151 (when (and (memq what '(scheduled deadline))
12152 (or (not time)
12153 (and (stringp time)
12154 (string-match "^[-+]+[0-9]" time))))
12155 ;; Try to get a default date/time from existing timestamp
12156 (save-excursion
12157 (org-back-to-heading t)
12158 (setq end (save-excursion (outline-next-heading) (point)))
12159 (when (re-search-forward (if (eq what 'scheduled)
12160 org-scheduled-time-regexp
12161 org-deadline-time-regexp)
12162 end t)
12163 (setq ts (match-string 1)
12164 default-time
12165 (apply 'encode-time (org-parse-time-string ts))
12166 default-input (and ts (org-get-compact-tod ts))))))
12167 (when what
12168 (setq time
12169 (if (stringp time)
12170 ;; This is a string (relative or absolute), set proper date
12171 (apply 'encode-time
12172 (org-read-date-analyze
12173 time default-time (decode-time default-time)))
12174 ;; If necessary, get the time from the user
12175 (or time (org-read-date nil 'to-time nil nil
12176 default-time default-input)))))
12178 (when (and org-insert-labeled-timestamps-at-point
12179 (member what '(scheduled deadline)))
12180 (insert
12181 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12182 (org-insert-time-stamp time org-time-was-given
12183 nil nil nil (list org-end-time-was-given))
12184 (setq what nil))
12185 (save-excursion
12186 (save-restriction
12187 (let (col list elt ts buffer-invisibility-spec)
12188 (org-back-to-heading t)
12189 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12190 (goto-char (match-end 1))
12191 (setq col (current-column))
12192 (goto-char (match-end 0))
12193 (if (eobp) (insert "\n") (forward-char 1))
12194 (when (and (not what)
12195 (not (looking-at
12196 (concat "[ \t]*"
12197 org-keyword-time-not-clock-regexp))))
12198 ;; Nothing to add, nothing to remove...... :-)
12199 (throw 'exit nil))
12200 (if (and (not (looking-at org-outline-regexp))
12201 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12202 "[^\r\n]*"))
12203 (not (equal (match-string 1) org-clock-string)))
12204 (narrow-to-region (match-beginning 0) (match-end 0))
12205 (insert-before-markers "\n")
12206 (backward-char 1)
12207 (narrow-to-region (point) (point))
12208 (and org-adapt-indentation (org-indent-to-column col)))
12209 ;; Check if we have to remove something.
12210 (setq list (cons what remove))
12211 (while list
12212 (setq elt (pop list))
12213 (when (or (and (eq elt 'scheduled)
12214 (re-search-forward org-scheduled-time-regexp nil t))
12215 (and (eq elt 'deadline)
12216 (re-search-forward org-deadline-time-regexp nil t))
12217 (and (eq elt 'closed)
12218 (re-search-forward org-closed-time-regexp nil t)))
12219 (replace-match "")
12220 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12221 (and (looking-at "[ \t]+") (replace-match ""))
12222 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12223 (when what
12224 (insert
12225 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12226 (cond ((eq what 'scheduled) org-scheduled-string)
12227 ((eq what 'deadline) org-deadline-string)
12228 ((eq what 'closed) org-closed-string))
12229 " ")
12230 (setq ts (org-insert-time-stamp
12231 time
12232 (or org-time-was-given
12233 (and (eq what 'closed) org-log-done-with-time))
12234 (eq what 'closed)
12235 nil nil (list org-end-time-was-given)))
12236 (insert
12237 (if (not (or (bolp) (eq (char-before) ?\ )
12238 (memq (char-after) '(32 10))
12239 (eobp))) " " ""))
12240 (end-of-line 1))
12241 (goto-char (point-min))
12242 (widen)
12243 (if (and (looking-at "[ \t]*\n")
12244 (equal (char-before) ?\n))
12245 (delete-region (1- (point)) (point-at-eol)))
12246 ts))))))
12248 (defvar org-log-note-marker (make-marker))
12249 (defvar org-log-note-purpose nil)
12250 (defvar org-log-note-state nil)
12251 (defvar org-log-note-previous-state nil)
12252 (defvar org-log-note-how nil)
12253 (defvar org-log-note-extra nil)
12254 (defvar org-log-note-window-configuration nil)
12255 (defvar org-log-note-return-to (make-marker))
12256 (defvar org-log-note-effective-time nil
12257 "Remembered current time so that dynamically scoped
12258 `org-extend-today-until' affects tha timestamps in state change
12259 log")
12261 (defvar org-log-post-message nil
12262 "Message to be displayed after a log note has been stored.
12263 The auto-repeater uses this.")
12265 (defun org-add-note ()
12266 "Add a note to the current entry.
12267 This is done in the same way as adding a state change note."
12268 (interactive)
12269 (org-add-log-setup 'note nil nil 'findpos nil))
12271 (defvar org-property-end-re)
12272 (defun org-add-log-setup (&optional purpose state prev-state
12273 findpos how extra)
12274 "Set up the post command hook to take a note.
12275 If this is about to TODO state change, the new state is expected in STATE.
12276 When FINDPOS is non-nil, find the correct position for the note in
12277 the current entry. If not, assume that it can be inserted at point.
12278 HOW is an indicator what kind of note should be created.
12279 EXTRA is additional text that will be inserted into the notes buffer."
12280 (let* ((org-log-into-drawer (org-log-into-drawer))
12281 (drawer (cond ((stringp org-log-into-drawer)
12282 org-log-into-drawer)
12283 (org-log-into-drawer "LOGBOOK")
12284 (t nil))))
12285 (save-restriction
12286 (save-excursion
12287 (when findpos
12288 (org-back-to-heading t)
12289 (narrow-to-region (point) (save-excursion
12290 (outline-next-heading) (point)))
12291 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12292 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12293 "[^\r\n]*\\)?"))
12294 (goto-char (match-end 0))
12295 (cond
12296 (drawer
12297 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12298 nil t)
12299 (progn
12300 (goto-char (match-end 0))
12301 (or org-log-states-order-reversed
12302 (and (re-search-forward org-property-end-re nil t)
12303 (goto-char (1- (match-beginning 0))))))
12304 (insert "\n:" drawer ":\n:END:")
12305 (beginning-of-line 0)
12306 (org-indent-line-function)
12307 (beginning-of-line 2)
12308 (org-indent-line-function)
12309 (end-of-line 0)))
12310 ((and org-log-state-notes-insert-after-drawers
12311 (save-excursion
12312 (forward-line) (looking-at org-drawer-regexp)))
12313 (forward-line)
12314 (while (looking-at org-drawer-regexp)
12315 (goto-char (match-end 0))
12316 (re-search-forward org-property-end-re (point-max) t)
12317 (forward-line))
12318 (forward-line -1)))
12319 (unless org-log-states-order-reversed
12320 (and (= (char-after) ?\n) (forward-char 1))
12321 (org-skip-over-state-notes)
12322 (skip-chars-backward " \t\n\r")))
12323 (move-marker org-log-note-marker (point))
12324 (setq org-log-note-purpose purpose
12325 org-log-note-state state
12326 org-log-note-previous-state prev-state
12327 org-log-note-how how
12328 org-log-note-extra extra
12329 org-log-note-effective-time (org-current-effective-time))
12330 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12332 (defun org-skip-over-state-notes ()
12333 "Skip past the list of State notes in an entry."
12334 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12335 (when (ignore-errors (goto-char (org-in-item-p)))
12336 (let* ((struct (org-list-struct))
12337 (prevs (org-list-prevs-alist struct)))
12338 (while (looking-at "[ \t]*- State")
12339 (goto-char (or (org-list-get-next-item (point) struct prevs)
12340 (org-list-get-item-end (point) struct)))))))
12342 (defun org-add-log-note (&optional purpose)
12343 "Pop up a window for taking a note, and add this note later at point."
12344 (remove-hook 'post-command-hook 'org-add-log-note)
12345 (setq org-log-note-window-configuration (current-window-configuration))
12346 (delete-other-windows)
12347 (move-marker org-log-note-return-to (point))
12348 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12349 (goto-char org-log-note-marker)
12350 (org-switch-to-buffer-other-window "*Org Note*")
12351 (erase-buffer)
12352 (if (memq org-log-note-how '(time state))
12353 (let (current-prefix-arg) (org-store-log-note))
12354 (let ((org-inhibit-startup t)) (org-mode))
12355 (insert (format "# Insert note for %s.
12356 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12357 (cond
12358 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12359 ((eq org-log-note-purpose 'done) "closed todo item")
12360 ((eq org-log-note-purpose 'state)
12361 (format "state change from \"%s\" to \"%s\""
12362 (or org-log-note-previous-state "")
12363 (or org-log-note-state "")))
12364 ((eq org-log-note-purpose 'reschedule)
12365 "rescheduling")
12366 ((eq org-log-note-purpose 'delschedule)
12367 "no longer scheduled")
12368 ((eq org-log-note-purpose 'redeadline)
12369 "changing deadline")
12370 ((eq org-log-note-purpose 'deldeadline)
12371 "removing deadline")
12372 ((eq org-log-note-purpose 'refile)
12373 "refiling")
12374 ((eq org-log-note-purpose 'note)
12375 "this entry")
12376 (t (error "This should not happen")))))
12377 (if org-log-note-extra (insert org-log-note-extra))
12378 (org-set-local 'org-finish-function 'org-store-log-note)
12379 (run-hooks 'org-log-buffer-setup-hook)))
12381 (defvar org-note-abort nil) ; dynamically scoped
12382 (defun org-store-log-note ()
12383 "Finish taking a log note, and insert it to where it belongs."
12384 (let ((txt (buffer-string))
12385 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12386 lines ind bul)
12387 (kill-buffer (current-buffer))
12388 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12389 (setq txt (replace-match "" t t txt)))
12390 (if (string-match "\\s-+\\'" txt)
12391 (setq txt (replace-match "" t t txt)))
12392 (setq lines (org-split-string txt "\n"))
12393 (when (and note (string-match "\\S-" note))
12394 (setq note
12395 (org-replace-escapes
12396 note
12397 (list (cons "%u" (user-login-name))
12398 (cons "%U" user-full-name)
12399 (cons "%t" (format-time-string
12400 (org-time-stamp-format 'long 'inactive)
12401 org-log-note-effective-time))
12402 (cons "%T" (format-time-string
12403 (org-time-stamp-format 'long nil)
12404 org-log-note-effective-time))
12405 (cons "%d" (format-time-string
12406 (org-time-stamp-format nil 'inactive)
12407 org-log-note-effective-time))
12408 (cons "%D" (format-time-string
12409 (org-time-stamp-format nil nil)
12410 org-log-note-effective-time))
12411 (cons "%s" (if org-log-note-state
12412 (concat "\"" org-log-note-state "\"")
12413 ""))
12414 (cons "%S" (if org-log-note-previous-state
12415 (concat "\"" org-log-note-previous-state "\"")
12416 "\"\"")))))
12417 (if lines (setq note (concat note " \\\\")))
12418 (push note lines))
12419 (when (or current-prefix-arg org-note-abort)
12420 (when org-log-into-drawer
12421 (org-remove-empty-drawer-at
12422 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12423 org-log-note-marker))
12424 (setq lines nil))
12425 (when lines
12426 (with-current-buffer (marker-buffer org-log-note-marker)
12427 (save-excursion
12428 (goto-char org-log-note-marker)
12429 (move-marker org-log-note-marker nil)
12430 (end-of-line 1)
12431 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12432 (setq ind (save-excursion
12433 (if (ignore-errors (goto-char (org-in-item-p)))
12434 (let ((struct (org-list-struct)))
12435 (org-list-get-ind
12436 (org-list-get-top-point struct) struct))
12437 (skip-chars-backward " \r\t\n")
12438 (cond
12439 ((and (org-at-heading-p)
12440 org-adapt-indentation)
12441 (1+ (org-current-level)))
12442 ((org-at-heading-p) 0)
12443 (t (org-get-indentation))))))
12444 (setq bul (org-list-bullet-string "-"))
12445 (org-indent-line-to ind)
12446 (insert bul (pop lines))
12447 (let ((ind-body (+ (length bul) ind)))
12448 (while lines
12449 (insert "\n")
12450 (org-indent-line-to ind-body)
12451 (insert (pop lines))))
12452 (message "Note stored")
12453 (org-back-to-heading t)
12454 (org-cycle-hide-drawers 'children)))))
12455 (set-window-configuration org-log-note-window-configuration)
12456 (with-current-buffer (marker-buffer org-log-note-return-to)
12457 (goto-char org-log-note-return-to))
12458 (move-marker org-log-note-return-to nil)
12459 (and org-log-post-message (message "%s" org-log-post-message)))
12461 (defun org-remove-empty-drawer-at (drawer pos)
12462 "Remove an empty drawer DRAWER at position POS.
12463 POS may also be a marker."
12464 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12465 (save-excursion
12466 (save-restriction
12467 (widen)
12468 (goto-char pos)
12469 (if (org-in-regexp
12470 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12471 (replace-match ""))))))
12473 (defun org-sparse-tree (&optional arg)
12474 "Create a sparse tree, prompt for the details.
12475 This command can create sparse trees. You first need to select the type
12476 of match used to create the tree:
12478 t Show all TODO entries.
12479 T Show entries with a specific TODO keyword.
12480 m Show entries selected by a tags/property match.
12481 p Enter a property name and its value (both with completion on existing
12482 names/values) and show entries with that property.
12483 r Show entries matching a regular expression (`/' can be used as well)
12484 d Show deadlines due within `org-deadline-warning-days'.
12485 b Show deadlines and scheduled items before a date.
12486 a Show deadlines and scheduled items after a date."
12487 (interactive "P")
12488 (let (ans kwd value)
12489 (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")
12490 (setq ans (read-char-exclusive))
12491 (cond
12492 ((equal ans ?d)
12493 (call-interactively 'org-check-deadlines))
12494 ((equal ans ?b)
12495 (call-interactively 'org-check-before-date))
12496 ((equal ans ?a)
12497 (call-interactively 'org-check-after-date))
12498 ((equal ans ?D)
12499 (call-interactively 'org-check-dates-range))
12500 ((equal ans ?t)
12501 (org-show-todo-tree nil))
12502 ((equal ans ?T)
12503 (org-show-todo-tree '(4)))
12504 ((member ans '(?T ?m))
12505 (call-interactively 'org-match-sparse-tree))
12506 ((member ans '(?p ?P))
12507 (setq kwd (org-icompleting-read "Property: "
12508 (mapcar 'list (org-buffer-property-keys))))
12509 (setq value (org-icompleting-read "Value: "
12510 (mapcar 'list (org-property-values kwd))))
12511 (unless (string-match "\\`{.*}\\'" value)
12512 (setq value (concat "\"" value "\"")))
12513 (org-match-sparse-tree arg (concat kwd "=" value)))
12514 ((member ans '(?r ?R ?/))
12515 (call-interactively 'org-occur))
12516 (t (error "No such sparse tree command \"%c\"" ans)))))
12518 (defvar org-occur-highlights nil
12519 "List of overlays used for occur matches.")
12520 (make-variable-buffer-local 'org-occur-highlights)
12521 (defvar org-occur-parameters nil
12522 "Parameters of the active org-occur calls.
12523 This is a list, each call to org-occur pushes as cons cell,
12524 containing the regular expression and the callback, onto the list.
12525 The list can contain several entries if `org-occur' has been called
12526 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12527 will only contain one set of parameters. When the highlights are
12528 removed (for example with `C-c C-c', or with the next edit (depending
12529 on `org-remove-highlights-with-change'), this variable is emptied
12530 as well.")
12531 (make-variable-buffer-local 'org-occur-parameters)
12533 (defun org-occur (regexp &optional keep-previous callback)
12534 "Make a compact tree which shows all matches of REGEXP.
12535 The tree will show the lines where the regexp matches, and all higher
12536 headlines above the match. It will also show the heading after the match,
12537 to make sure editing the matching entry is easy.
12538 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12539 call to `org-occur' will be kept, to allow stacking of calls to this
12540 command.
12541 If CALLBACK is non-nil, it is a function which is called to confirm
12542 that the match should indeed be shown."
12543 (interactive "sRegexp: \nP")
12544 (when (equal regexp "")
12545 (error "Regexp cannot be empty"))
12546 (unless keep-previous
12547 (org-remove-occur-highlights nil nil t))
12548 (push (cons regexp callback) org-occur-parameters)
12549 (let ((cnt 0))
12550 (save-excursion
12551 (goto-char (point-min))
12552 (if (or (not keep-previous) ; do not want to keep
12553 (not org-occur-highlights)) ; no previous matches
12554 ;; hide everything
12555 (org-overview))
12556 (while (re-search-forward regexp nil t)
12557 (when (or (not callback)
12558 (save-match-data (funcall callback)))
12559 (setq cnt (1+ cnt))
12560 (when org-highlight-sparse-tree-matches
12561 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12562 (org-show-context 'occur-tree))))
12563 (when org-remove-highlights-with-change
12564 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12565 nil 'local))
12566 (unless org-sparse-tree-open-archived-trees
12567 (org-hide-archived-subtrees (point-min) (point-max)))
12568 (run-hooks 'org-occur-hook)
12569 (if (org-called-interactively-p 'interactive)
12570 (message "%d match(es) for regexp %s" cnt regexp))
12571 cnt))
12573 (defun org-occur-next-match (&optional n reset)
12574 "Function for `next-error-function' to find sparse tree matches.
12575 N is the number of matches to move, when negative move backwards.
12576 RESET is entirely ignored - this function always goes back to the
12577 starting point when no match is found."
12578 (let* ((limit (if (< n 0) (point-min) (point-max)))
12579 (search-func (if (< n 0)
12580 'previous-single-char-property-change
12581 'next-single-char-property-change))
12582 (n (abs n))
12583 (pos (point))
12585 (catch 'exit
12586 (while (setq p1 (funcall search-func (point) 'org-type))
12587 (when (equal p1 limit)
12588 (goto-char pos)
12589 (error "No more matches"))
12590 (when (equal (get-char-property p1 'org-type) 'org-occur)
12591 (setq n (1- n))
12592 (when (= n 0)
12593 (goto-char p1)
12594 (throw 'exit (point))))
12595 (goto-char p1))
12596 (goto-char p1)
12597 (error "No more matches"))))
12599 (defun org-show-context (&optional key)
12600 "Make sure point and context are visible.
12601 How much context is shown depends upon the variables
12602 `org-show-hierarchy-above', `org-show-following-heading',
12603 `org-show-entry-below' and `org-show-siblings'."
12604 (let ((heading-p (org-at-heading-p t))
12605 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12606 (following-p (org-get-alist-option org-show-following-heading key))
12607 (entry-p (org-get-alist-option org-show-entry-below key))
12608 (siblings-p (org-get-alist-option org-show-siblings key)))
12609 (catch 'exit
12610 ;; Show heading or entry text
12611 (if (and heading-p (not entry-p))
12612 (org-flag-heading nil) ; only show the heading
12613 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12614 (org-show-hidden-entry))) ; show entire entry
12615 (when following-p
12616 ;; Show next sibling, or heading below text
12617 (save-excursion
12618 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12619 (org-flag-heading nil))))
12620 (when siblings-p (org-show-siblings))
12621 (when hierarchy-p
12622 ;; show all higher headings, possibly with siblings
12623 (save-excursion
12624 (while (and (condition-case nil
12625 (progn (org-up-heading-all 1) t)
12626 (error nil))
12627 (not (bobp)))
12628 (org-flag-heading nil)
12629 (when siblings-p (org-show-siblings))))))))
12631 (defvar org-reveal-start-hook nil
12632 "Hook run before revealing a location.")
12634 (defun org-reveal (&optional siblings)
12635 "Show current entry, hierarchy above it, and the following headline.
12636 This can be used to show a consistent set of context around locations
12637 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12638 not t for the search context.
12640 With optional argument SIBLINGS, on each level of the hierarchy all
12641 siblings are shown. This repairs the tree structure to what it would
12642 look like when opened with hierarchical calls to `org-cycle'.
12643 With double optional argument \\[universal-argument] \\[universal-argument], \
12644 go to the parent and show the
12645 entire tree."
12646 (interactive "P")
12647 (run-hooks 'org-reveal-start-hook)
12648 (let ((org-show-hierarchy-above t)
12649 (org-show-following-heading t)
12650 (org-show-siblings (if siblings t org-show-siblings)))
12651 (org-show-context nil))
12652 (when (equal siblings '(16))
12653 (save-excursion
12654 (when (org-up-heading-safe)
12655 (org-show-subtree)
12656 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12658 (defun org-highlight-new-match (beg end)
12659 "Highlight from BEG to END and mark the highlight is an occur headline."
12660 (let ((ov (make-overlay beg end)))
12661 (overlay-put ov 'face 'secondary-selection)
12662 (overlay-put ov 'org-type 'org-occur)
12663 (push ov org-occur-highlights)))
12665 (defun org-remove-occur-highlights (&optional beg end noremove)
12666 "Remove the occur highlights from the buffer.
12667 BEG and END are ignored. If NOREMOVE is nil, remove this function
12668 from the `before-change-functions' in the current buffer."
12669 (interactive)
12670 (unless org-inhibit-highlight-removal
12671 (mapc 'delete-overlay org-occur-highlights)
12672 (setq org-occur-highlights nil)
12673 (setq org-occur-parameters nil)
12674 (unless noremove
12675 (remove-hook 'before-change-functions
12676 'org-remove-occur-highlights 'local))))
12678 ;;;; Priorities
12680 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12681 "Regular expression matching the priority indicator.")
12683 (defvar org-remove-priority-next-time nil)
12685 (defun org-priority-up ()
12686 "Increase the priority of the current item."
12687 (interactive)
12688 (org-priority 'up))
12690 (defun org-priority-down ()
12691 "Decrease the priority of the current item."
12692 (interactive)
12693 (org-priority 'down))
12695 (defun org-priority (&optional action)
12696 "Change the priority of an item by ARG.
12697 ACTION can be `set', `up', `down', or a character."
12698 (interactive)
12699 (unless org-enable-priority-commands
12700 (error "Priority commands are disabled"))
12701 (setq action (or action 'set))
12702 (let (current new news have remove)
12703 (save-excursion
12704 (org-back-to-heading t)
12705 (if (looking-at org-priority-regexp)
12706 (setq current (string-to-char (match-string 2))
12707 have t))
12708 (cond
12709 ((eq action 'remove)
12710 (setq remove t new ?\ ))
12711 ((or (eq action 'set)
12712 (if (featurep 'xemacs) (characterp action) (integerp action)))
12713 (if (not (eq action 'set))
12714 (setq new action)
12715 (message "Priority %c-%c, SPC to remove: "
12716 org-highest-priority org-lowest-priority)
12717 (save-match-data
12718 (setq new (read-char-exclusive))))
12719 (if (and (= (upcase org-highest-priority) org-highest-priority)
12720 (= (upcase org-lowest-priority) org-lowest-priority))
12721 (setq new (upcase new)))
12722 (cond ((equal new ?\ ) (setq remove t))
12723 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12724 (error "Priority must be between `%c' and `%c'"
12725 org-highest-priority org-lowest-priority))))
12726 ((eq action 'up)
12727 (setq new (if have
12728 (1- current) ; normal cycling
12729 ;; last priority was empty
12730 (if (eq last-command this-command)
12731 org-lowest-priority ; wrap around empty to lowest
12732 ;; default
12733 (if org-priority-start-cycle-with-default
12734 org-default-priority
12735 (1- org-default-priority))))))
12736 ((eq action 'down)
12737 (setq new (if have
12738 (1+ current) ; normal cycling
12739 ;; last priority was empty
12740 (if (eq last-command this-command)
12741 org-highest-priority ; wrap around empty to highest
12742 ;; default
12743 (if org-priority-start-cycle-with-default
12744 org-default-priority
12745 (1+ org-default-priority))))))
12746 (t (error "Invalid action")))
12747 (if (or (< (upcase new) org-highest-priority)
12748 (> (upcase new) org-lowest-priority))
12749 (if (and (memq action '(up down))
12750 (not have) (not (eq last-command this-command)))
12751 ;; `new' is from default priority
12752 (error
12753 "The default can not be set, see `org-default-priority' why")
12754 ;; normal cycling: `new' is beyond highest/lowest priority
12755 ;; and is wrapped around to the empty priority
12756 (setq remove t)))
12757 (setq news (format "%c" new))
12758 (if have
12759 (if remove
12760 (replace-match "" t t nil 1)
12761 (replace-match news t t nil 2))
12762 (if remove
12763 (error "No priority cookie found in line")
12764 (let ((case-fold-search nil))
12765 (looking-at org-todo-line-regexp))
12766 (if (match-end 2)
12767 (progn
12768 (goto-char (match-end 2))
12769 (insert " [#" news "]"))
12770 (goto-char (match-beginning 3))
12771 (insert "[#" news "] "))))
12772 (org-preserve-lc (org-set-tags nil 'align)))
12773 (if remove
12774 (message "Priority removed")
12775 (message "Priority of current item set to %s" news))))
12777 (defun org-get-priority (s)
12778 "Find priority cookie and return priority."
12779 (if (functionp org-get-priority-function)
12780 (funcall org-get-priority-function)
12781 (save-match-data
12782 (if (not (string-match org-priority-regexp s))
12783 (* 1000 (- org-lowest-priority org-default-priority))
12784 (* 1000 (- org-lowest-priority
12785 (string-to-char (match-string 2 s))))))))
12787 ;;;; Tags
12789 (defvar org-agenda-archives-mode)
12790 (defvar org-map-continue-from nil
12791 "Position from where mapping should continue.
12792 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12794 (defvar org-scanner-tags nil
12795 "The current tag list while the tags scanner is running.")
12796 (defvar org-trust-scanner-tags nil
12797 "Should `org-get-tags-at' use the tags for the scanner.
12798 This is for internal dynamical scoping only.
12799 When this is non-nil, the function `org-get-tags-at' will return the value
12800 of `org-scanner-tags' instead of building the list by itself. This
12801 can lead to large speed-ups when the tags scanner is used in a file with
12802 many entries, and when the list of tags is retrieved, for example to
12803 obtain a list of properties. Building the tags list for each entry in such
12804 a file becomes an N^2 operation - but with this variable set, it scales
12805 as N.")
12807 (defun org-scan-tags (action matcher todo-only &optional start-level)
12808 "Scan headline tags with inheritance and produce output ACTION.
12810 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12811 or `agenda' to produce an entry list for an agenda view. It can also be
12812 a Lisp form or a function that should be called at each matched headline, in
12813 this case the return value is a list of all return values from these calls.
12815 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12816 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12817 only lines with a not-done TODO keyword are included in the output.
12818 This should be the same variable that was scoped into
12819 and set by `org-make-tags-matcher' when it constructed MATCHER.
12821 START-LEVEL can be a string with asterisks, reducing the scope to
12822 headlines matching this string."
12823 (require 'org-agenda)
12824 (let* ((re (concat "^"
12825 (if start-level
12826 ;; Get the correct level to match
12827 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12828 org-outline-regexp)
12829 " *\\(\\<\\("
12830 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12831 (org-re
12832 (if todo-only
12833 "\\>\\)\\)[ \t]+\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"
12834 "\\>\\)\\)? *\\([^ ].*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))))
12835 (props (list 'face 'default
12836 'done-face 'org-agenda-done
12837 'undone-face 'default
12838 'mouse-face 'highlight
12839 'org-not-done-regexp org-not-done-regexp
12840 'org-todo-regexp org-todo-regexp
12841 'org-complex-heading-regexp org-complex-heading-regexp
12842 'help-echo
12843 (format "mouse-2 or RET jump to org file %s"
12844 (abbreviate-file-name
12845 (or (buffer-file-name (buffer-base-buffer))
12846 (buffer-name (buffer-base-buffer)))))))
12847 (case-fold-search nil)
12848 (org-map-continue-from nil)
12849 lspos tags tags-list
12850 (tags-alist (list (cons 0 org-file-tags)))
12851 (llast 0) rtn rtn1 level category i txt
12852 todo marker entry priority)
12853 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12854 (setq action (list 'lambda nil action)))
12855 (save-excursion
12856 (goto-char (point-min))
12857 (when (eq action 'sparse-tree)
12858 (org-overview)
12859 (org-remove-occur-highlights))
12860 (while (re-search-forward re nil t)
12861 (setq org-map-continue-from nil)
12862 (catch :skip
12863 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12864 tags (if (match-end 4) (org-match-string-no-properties 4)))
12865 (goto-char (setq lspos (match-beginning 0)))
12866 (setq level (org-reduced-level (funcall outline-level))
12867 category (org-get-category))
12868 (setq i llast llast level)
12869 ;; remove tag lists from same and sublevels
12870 (while (>= i level)
12871 (when (setq entry (assoc i tags-alist))
12872 (setq tags-alist (delete entry tags-alist)))
12873 (setq i (1- i)))
12874 ;; add the next tags
12875 (when tags
12876 (setq tags (org-split-string tags ":")
12877 tags-alist
12878 (cons (cons level tags) tags-alist)))
12879 ;; compile tags for current headline
12880 (setq tags-list
12881 (if org-use-tag-inheritance
12882 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12883 tags)
12884 org-scanner-tags tags-list)
12885 (when org-use-tag-inheritance
12886 (setcdr (car tags-alist)
12887 (mapcar (lambda (x)
12888 (setq x (copy-sequence x))
12889 (org-add-prop-inherited x))
12890 (cdar tags-alist))))
12891 (when (and tags org-use-tag-inheritance
12892 (or (not (eq t org-use-tag-inheritance))
12893 org-tags-exclude-from-inheritance))
12894 ;; selective inheritance, remove uninherited ones
12895 (setcdr (car tags-alist)
12896 (org-remove-uninherited-tags (cdar tags-alist))))
12897 (when (and
12899 ;; eval matcher only when the todo condition is OK
12900 (and (or (not todo-only) (member todo org-not-done-keywords))
12901 (let ((case-fold-search t)) (eval matcher)))
12903 ;; Call the skipper, but return t if it does not skip,
12904 ;; so that the `and' form continues evaluating
12905 (progn
12906 (unless (eq action 'sparse-tree) (org-agenda-skip))
12909 ;; Check if timestamps are deselecting this entry
12910 (or (not todo-only)
12911 (and (member todo org-not-done-keywords)
12912 (or (not org-agenda-tags-todo-honor-ignore-options)
12913 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12915 ;; Extra check for the archive tag
12916 ;; FIXME: Does the skipper already do this????
12918 (not (member org-archive-tag tags-list))
12919 ;; we have an archive tag, should we use this anyway?
12920 (or (not org-agenda-skip-archived-trees)
12921 (and (eq action 'agenda) org-agenda-archives-mode))))
12923 ;; select this headline
12925 (cond
12926 ((eq action 'sparse-tree)
12927 (and org-highlight-sparse-tree-matches
12928 (org-get-heading) (match-end 0)
12929 (org-highlight-new-match
12930 (match-beginning 1) (match-end 1)))
12931 (org-show-context 'tags-tree))
12932 ((eq action 'agenda)
12933 (setq txt (org-agenda-format-item
12935 (concat
12936 (if (eq org-tags-match-list-sublevels 'indented)
12937 (make-string (1- level) ?.) "")
12938 (org-get-heading))
12939 category
12940 tags-list
12942 priority (org-get-priority txt))
12943 (goto-char lspos)
12944 (setq marker (org-agenda-new-marker))
12945 (org-add-props txt props
12946 'org-marker marker 'org-hd-marker marker 'org-category category
12947 'todo-state todo
12948 'priority priority 'type "tagsmatch")
12949 (push txt rtn))
12950 ((functionp action)
12951 (setq org-map-continue-from nil)
12952 (save-excursion
12953 (setq rtn1 (funcall action))
12954 (push rtn1 rtn)))
12955 (t (error "Invalid action")))
12957 ;; if we are to skip sublevels, jump to end of subtree
12958 (unless org-tags-match-list-sublevels
12959 (org-end-of-subtree t)
12960 (backward-char 1))))
12961 ;; Get the correct position from where to continue
12962 (if org-map-continue-from
12963 (goto-char org-map-continue-from)
12964 (and (= (point) lspos) (end-of-line 1)))))
12965 (when (and (eq action 'sparse-tree)
12966 (not org-sparse-tree-open-archived-trees))
12967 (org-hide-archived-subtrees (point-min) (point-max)))
12968 (nreverse rtn)))
12970 (defun org-remove-uninherited-tags (tags)
12971 "Remove all tags that are not inherited from the list TAGS."
12972 (cond
12973 ((eq org-use-tag-inheritance t)
12974 (if org-tags-exclude-from-inheritance
12975 (org-delete-all org-tags-exclude-from-inheritance tags)
12976 tags))
12977 ((not org-use-tag-inheritance) nil)
12978 ((stringp org-use-tag-inheritance)
12979 (delq nil (mapcar
12980 (lambda (x)
12981 (if (and (string-match org-use-tag-inheritance x)
12982 (not (member x org-tags-exclude-from-inheritance)))
12983 x nil))
12984 tags)))
12985 ((listp org-use-tag-inheritance)
12986 (delq nil (mapcar
12987 (lambda (x)
12988 (if (member x org-use-tag-inheritance) x nil))
12989 tags)))))
12991 (defun org-match-sparse-tree (&optional todo-only match)
12992 "Create a sparse tree according to tags string MATCH.
12993 MATCH can contain positive and negative selection of tags, like
12994 \"+WORK+URGENT-WITHBOSS\".
12995 If optional argument TODO-ONLY is non-nil, only select lines that are
12996 also TODO lines."
12997 (interactive "P")
12998 (org-prepare-agenda-buffers (list (current-buffer)))
12999 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13001 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13003 (defvar org-cached-props nil)
13004 (defun org-cached-entry-get (pom property)
13005 (if (or (eq t org-use-property-inheritance)
13006 (and (stringp org-use-property-inheritance)
13007 (string-match org-use-property-inheritance property))
13008 (and (listp org-use-property-inheritance)
13009 (member property org-use-property-inheritance)))
13010 ;; Caching is not possible, check it directly
13011 (org-entry-get pom property 'inherit)
13012 ;; Get all properties, so that we can do complicated checks easily
13013 (cdr (assoc property (or org-cached-props
13014 (setq org-cached-props
13015 (org-entry-properties pom)))))))
13017 (defun org-global-tags-completion-table (&optional files)
13018 "Return the list of all tags in all agenda buffer/files.
13019 Optional FILES argument is a list of files to which can be used
13020 instead of the agenda files."
13021 (save-excursion
13022 (org-uniquify
13023 (delq nil
13024 (apply 'append
13025 (mapcar
13026 (lambda (file)
13027 (set-buffer (find-file-noselect file))
13028 (append (org-get-buffer-tags)
13029 (mapcar (lambda (x) (if (stringp (car-safe x))
13030 (list (car-safe x)) nil))
13031 org-tag-alist)))
13032 (if (and files (car files))
13033 files
13034 (org-agenda-files))))))))
13036 (defun org-make-tags-matcher (match)
13037 "Create the TAGS/TODO matcher form for the selection string MATCH.
13039 The variable `todo-only' is scoped dynamically into this function; it will be
13040 set to t if the matcher restricts matching to TODO entries,
13041 otherwise will not be touched.
13043 Returns a cons of the selection string MATCH and the constructed
13044 lisp form implementing the matcher. The matcher is to be
13045 evaluated at an Org entry, with point on the headline,
13046 and returns t if the entry matches the
13047 selection string MATCH. The returned lisp form references
13048 two variables with information about the entry, which must be
13049 bound around the form's evaluation: todo, the TODO keyword at the
13050 entry (or nil of none); and tags-list, the list of all tags at the
13051 entry including inherited ones. Additionally, the category
13052 of the entry (if any) must be specified as the text property
13053 'org-category on the headline.
13055 See also `org-scan-tags'.
13057 (declare (special todo-only))
13058 (unless (boundp 'todo-only)
13059 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13060 (unless match
13061 ;; Get a new match request, with completion
13062 (let ((org-last-tags-completion-table
13063 (org-global-tags-completion-table)))
13064 (setq match (org-completing-read-no-i
13065 "Match: " 'org-tags-completion-function nil nil nil
13066 'org-tags-history))))
13068 ;; Parse the string and create a lisp form
13069 (let ((match0 match)
13070 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13071 minus tag mm
13072 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13073 orterms term orlist re-p str-p level-p level-op time-p
13074 prop-p pn pv po gv rest)
13075 (if (string-match "/+" match)
13076 ;; match contains also a todo-matching request
13077 (progn
13078 (setq tagsmatch (substring match 0 (match-beginning 0))
13079 todomatch (substring match (match-end 0)))
13080 (if (string-match "^!" todomatch)
13081 (setq todo-only t todomatch (substring todomatch 1)))
13082 (if (string-match "^\\s-*$" todomatch)
13083 (setq todomatch nil)))
13084 ;; only matching tags
13085 (setq tagsmatch match todomatch nil))
13087 ;; Make the tags matcher
13088 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13089 (setq tagsmatcher t)
13090 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13091 (while (setq term (pop orterms))
13092 (while (and (equal (substring term -1) "\\") orterms)
13093 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13094 (while (string-match re term)
13095 (setq rest (substring term (match-end 0))
13096 minus (and (match-end 1)
13097 (equal (match-string 1 term) "-"))
13098 tag (save-match-data (replace-regexp-in-string
13099 "\\\\-" "-"
13100 (match-string 2 term)))
13101 re-p (equal (string-to-char tag) ?{)
13102 level-p (match-end 4)
13103 prop-p (match-end 5)
13104 mm (cond
13105 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13106 (level-p
13107 (setq level-op (org-op-to-function (match-string 3 term)))
13108 `(,level-op level ,(string-to-number
13109 (match-string 4 term))))
13110 (prop-p
13111 (setq pn (match-string 5 term)
13112 po (match-string 6 term)
13113 pv (match-string 7 term)
13114 re-p (equal (string-to-char pv) ?{)
13115 str-p (equal (string-to-char pv) ?\")
13116 time-p (save-match-data
13117 (string-match "^\"[[<].*[]>]\"$" pv))
13118 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13119 (if time-p (setq pv (org-matcher-time pv)))
13120 (setq po (org-op-to-function po (if time-p 'time str-p)))
13121 (cond
13122 ((equal pn "CATEGORY")
13123 (setq gv '(get-text-property (point) 'org-category)))
13124 ((equal pn "TODO")
13125 (setq gv 'todo))
13127 (setq gv `(org-cached-entry-get nil ,pn))))
13128 (if re-p
13129 (if (eq po 'org<>)
13130 `(not (string-match ,pv (or ,gv "")))
13131 `(string-match ,pv (or ,gv "")))
13132 (if str-p
13133 `(,po (or ,gv "") ,pv)
13134 `(,po (string-to-number (or ,gv ""))
13135 ,(string-to-number pv) ))))
13136 (t `(member ,tag tags-list)))
13137 mm (if minus (list 'not mm) mm)
13138 term rest)
13139 (push mm tagsmatcher))
13140 (push (if (> (length tagsmatcher) 1)
13141 (cons 'and tagsmatcher)
13142 (car tagsmatcher))
13143 orlist)
13144 (setq tagsmatcher nil))
13145 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13146 (setq tagsmatcher
13147 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13148 ;; Make the todo matcher
13149 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13150 (setq todomatcher t)
13151 (setq orterms (org-split-string todomatch "|") orlist nil)
13152 (while (setq term (pop orterms))
13153 (while (string-match re term)
13154 (setq minus (and (match-end 1)
13155 (equal (match-string 1 term) "-"))
13156 kwd (match-string 2 term)
13157 re-p (equal (string-to-char kwd) ?{)
13158 term (substring term (match-end 0))
13159 mm (if re-p
13160 `(string-match ,(substring kwd 1 -1) todo)
13161 (list 'equal 'todo kwd))
13162 mm (if minus (list 'not mm) mm))
13163 (push mm todomatcher))
13164 (push (if (> (length todomatcher) 1)
13165 (cons 'and todomatcher)
13166 (car todomatcher))
13167 orlist)
13168 (setq todomatcher nil))
13169 (setq todomatcher (if (> (length orlist) 1)
13170 (cons 'or orlist) (car orlist))))
13172 ;; Return the string and lisp forms of the matcher
13173 (setq matcher (if todomatcher
13174 (list 'and tagsmatcher todomatcher)
13175 tagsmatcher))
13176 (when todo-only
13177 (setq matcher (list 'and '(member todo org-not-done-keywords)
13178 matcher)))
13179 (cons match0 matcher)))
13181 (defun org-op-to-function (op &optional stringp)
13182 "Turn an operator into the appropriate function."
13183 (setq op
13184 (cond
13185 ((equal op "<" ) '(< string< org-time<))
13186 ((equal op ">" ) '(> org-string> org-time>))
13187 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13188 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13189 ((member op '("=" "==")) '(= string= org-time=))
13190 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13191 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13193 (defun org<> (a b) (not (= a b)))
13194 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13195 (defun org-string>= (a b) (not (string< a b)))
13196 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13197 (defun org-string<> (a b) (not (string= a b)))
13198 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13199 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13200 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13201 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13202 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13203 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13204 (defun org-2ft (s)
13205 "Convert S to a floating point time.
13206 If S is already a number, just return it. If it is a string, parse
13207 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13208 (cond
13209 ((numberp s) s)
13210 ((stringp s)
13211 (condition-case nil
13212 (float-time (apply 'encode-time (org-parse-time-string s)))
13213 (error 0.)))
13214 (t 0.)))
13216 (defun org-time-today ()
13217 "Time in seconds today at 0:00.
13218 Returns the float number of seconds since the beginning of the
13219 epoch to the beginning of today (00:00)."
13220 (float-time (apply 'encode-time
13221 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13223 (defun org-matcher-time (s)
13224 "Interpret a time comparison value."
13225 (save-match-data
13226 (cond
13227 ((string= s "<now>") (float-time))
13228 ((string= s "<today>") (org-time-today))
13229 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13230 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13231 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13232 (+ (org-time-today)
13233 (* (string-to-number (match-string 1 s))
13234 (cdr (assoc (match-string 2 s)
13235 '(("d" . 86400.0) ("w" . 604800.0)
13236 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13237 (t (org-2ft s)))))
13239 (defun org-match-any-p (re list)
13240 "Does re match any element of list?"
13241 (setq list (mapcar (lambda (x) (string-match re x)) list))
13242 (delq nil list))
13244 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13245 (defvar org-tags-overlay (make-overlay 1 1))
13246 (org-detach-overlay org-tags-overlay)
13248 (defun org-get-local-tags-at (&optional pos)
13249 "Get a list of tags defined in the current headline."
13250 (org-get-tags-at pos 'local))
13252 (defun org-get-local-tags ()
13253 "Get a list of tags defined in the current headline."
13254 (org-get-tags-at nil 'local))
13256 (defun org-get-tags-at (&optional pos local)
13257 "Get a list of all headline tags applicable at POS.
13258 POS defaults to point. If tags are inherited, the list contains
13259 the targets in the same sequence as the headlines appear, i.e.
13260 the tags of the current headline come last.
13261 When LOCAL is non-nil, only return tags from the current headline,
13262 ignore inherited ones."
13263 (interactive)
13264 (if (and org-trust-scanner-tags
13265 (or (not pos) (equal pos (point)))
13266 (not local))
13267 org-scanner-tags
13268 (let (tags ltags lastpos parent)
13269 (save-excursion
13270 (save-restriction
13271 (widen)
13272 (goto-char (or pos (point)))
13273 (save-match-data
13274 (catch 'done
13275 (condition-case nil
13276 (progn
13277 (org-back-to-heading t)
13278 (while (not (equal lastpos (point)))
13279 (setq lastpos (point))
13280 (when (looking-at
13281 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13282 (setq ltags (org-split-string
13283 (org-match-string-no-properties 1) ":"))
13284 (when parent
13285 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13286 (setq tags (append
13287 (if parent
13288 (org-remove-uninherited-tags ltags)
13289 ltags)
13290 tags)))
13291 (or org-use-tag-inheritance (throw 'done t))
13292 (if local (throw 'done t))
13293 (or (org-up-heading-safe) (error nil))
13294 (setq parent t)))
13295 (error nil)))))
13296 (if local
13297 tags
13298 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13300 (defun org-add-prop-inherited (s)
13301 (add-text-properties 0 (length s) '(inherited t) s)
13304 (defun org-toggle-tag (tag &optional onoff)
13305 "Toggle the tag TAG for the current line.
13306 If ONOFF is `on' or `off', don't toggle but set to this state."
13307 (let (res current)
13308 (save-excursion
13309 (org-back-to-heading t)
13310 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13311 (point-at-eol) t)
13312 (progn
13313 (setq current (match-string 1))
13314 (replace-match ""))
13315 (setq current ""))
13316 (setq current (nreverse (org-split-string current ":")))
13317 (cond
13318 ((eq onoff 'on)
13319 (setq res t)
13320 (or (member tag current) (push tag current)))
13321 ((eq onoff 'off)
13322 (or (not (member tag current)) (setq current (delete tag current))))
13323 (t (if (member tag current)
13324 (setq current (delete tag current))
13325 (setq res t)
13326 (push tag current))))
13327 (end-of-line 1)
13328 (if current
13329 (progn
13330 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13331 (org-set-tags nil t))
13332 (delete-horizontal-space))
13333 (run-hooks 'org-after-tags-change-hook))
13334 res))
13336 (defun org-align-tags-here (to-col)
13337 ;; Assumes that this is a headline
13338 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13339 (beginning-of-line 1)
13340 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13341 (< pos (match-beginning 2)))
13342 (progn
13343 (setq tags-l (- (match-end 2) (match-beginning 2)))
13344 (goto-char (match-beginning 1))
13345 (insert " ")
13346 (delete-region (point) (1+ (match-beginning 2)))
13347 (setq ncol (max (current-column)
13348 (1+ col)
13349 (if (> to-col 0)
13350 to-col
13351 (- (abs to-col) tags-l))))
13352 (setq p (point))
13353 (insert (make-string (- ncol (current-column)) ?\ ))
13354 (setq ncol (current-column))
13355 (when indent-tabs-mode (tabify p (point-at-eol)))
13356 (org-move-to-column (min ncol col) t))
13357 (goto-char pos))))
13359 (defun org-set-tags-command (&optional arg just-align)
13360 "Call the set-tags command for the current entry."
13361 (interactive "P")
13362 (if (org-at-heading-p)
13363 (org-set-tags arg just-align)
13364 (save-excursion
13365 (org-back-to-heading t)
13366 (org-set-tags arg just-align))))
13368 (defun org-set-tags-to (data)
13369 "Set the tags of the current entry to DATA, replacing the current tags.
13370 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13371 If DATA is nil or the empty string, any tags will be removed."
13372 (interactive "sTags: ")
13373 (setq data
13374 (cond
13375 ((eq data nil) "")
13376 ((equal data "") "")
13377 ((stringp data)
13378 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13379 ":"))
13380 ((listp data)
13381 (concat ":" (mapconcat 'identity data ":") ":"))
13382 (t nil)))
13383 (when data
13384 (save-excursion
13385 (org-back-to-heading t)
13386 (when (looking-at org-complex-heading-regexp)
13387 (if (match-end 5)
13388 (progn
13389 (goto-char (match-beginning 5))
13390 (insert data)
13391 (delete-region (point) (point-at-eol))
13392 (org-set-tags nil 'align))
13393 (goto-char (point-at-eol))
13394 (insert " " data)
13395 (org-set-tags nil 'align)))
13396 (beginning-of-line 1)
13397 (if (looking-at ".*?\\([ \t]+\\)$")
13398 (delete-region (match-beginning 1) (match-end 1))))))
13400 (defun org-align-all-tags ()
13401 "Align the tags i all headings."
13402 (interactive)
13403 (save-excursion
13404 (or (ignore-errors (org-back-to-heading t))
13405 (outline-next-heading))
13406 (if (org-at-heading-p)
13407 (org-set-tags t)
13408 (message "No headings"))))
13410 (defvar org-indent-indentation-per-level)
13411 (defun org-set-tags (&optional arg just-align)
13412 "Set the tags for the current headline.
13413 With prefix ARG, realign all tags in headings in the current buffer."
13414 (interactive "P")
13415 (let* ((re org-outline-regexp-bol)
13416 (current (org-get-tags-string))
13417 (col (current-column))
13418 (org-setting-tags t)
13419 table current-tags inherited-tags ; computed below when needed
13420 tags p0 c0 c1 rpl di tc level)
13421 (if arg
13422 (save-excursion
13423 (goto-char (point-min))
13424 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13425 (while (re-search-forward re nil t)
13426 (org-set-tags nil t)
13427 (end-of-line 1)))
13428 (message "All tags realigned to column %d" org-tags-column))
13429 (if just-align
13430 (setq tags current)
13431 ;; Get a new set of tags from the user
13432 (save-excursion
13433 (setq table (append org-tag-persistent-alist
13434 (or org-tag-alist (org-get-buffer-tags))
13435 (and
13436 org-complete-tags-always-offer-all-agenda-tags
13437 (org-global-tags-completion-table
13438 (org-agenda-files))))
13439 org-last-tags-completion-table table
13440 current-tags (org-split-string current ":")
13441 inherited-tags (nreverse
13442 (nthcdr (length current-tags)
13443 (nreverse (org-get-tags-at))))
13444 tags
13445 (if (or (eq t org-use-fast-tag-selection)
13446 (and org-use-fast-tag-selection
13447 (delq nil (mapcar 'cdr table))))
13448 (org-fast-tag-selection
13449 current-tags inherited-tags table
13450 (if org-fast-tag-selection-include-todo
13451 org-todo-key-alist))
13452 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13453 (org-trim
13454 (org-icompleting-read "Tags: "
13455 'org-tags-completion-function
13456 nil nil current 'org-tags-history))))))
13457 (while (string-match "[-+&]+" tags)
13458 ;; No boolean logic, just a list
13459 (setq tags (replace-match ":" t t tags))))
13461 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13463 (if org-tags-sort-function
13464 (setq tags (mapconcat 'identity
13465 (sort (org-split-string
13466 tags (org-re "[^[:alnum:]_@#%]+"))
13467 org-tags-sort-function) ":")))
13469 (if (string-match "\\`[\t ]*\\'" tags)
13470 (setq tags "")
13471 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13472 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13474 ;; Insert new tags at the correct column
13475 (beginning-of-line 1)
13476 (setq level (or (and (looking-at org-outline-regexp)
13477 (- (match-end 0) (point) 1))
13479 (cond
13480 ((and (equal current "") (equal tags "")))
13481 ((re-search-forward
13482 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13483 (point-at-eol) t)
13484 (if (equal tags "")
13485 (setq rpl "")
13486 (goto-char (match-beginning 0))
13487 (setq c0 (current-column)
13488 ;; compute offset for the case of org-indent-mode active
13489 di (if org-indent-mode
13490 (* (1- org-indent-indentation-per-level) (1- level))
13492 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13493 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13494 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13495 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13496 (replace-match rpl t t)
13497 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13498 tags)
13499 (t (error "Tags alignment failed")))
13500 (org-move-to-column col)
13501 (unless just-align
13502 (run-hooks 'org-after-tags-change-hook)))))
13504 (defun org-change-tag-in-region (beg end tag off)
13505 "Add or remove TAG for each entry in the region.
13506 This works in the agenda, and also in an org-mode buffer."
13507 (interactive
13508 (list (region-beginning) (region-end)
13509 (let ((org-last-tags-completion-table
13510 (if (eq major-mode 'org-mode)
13511 (org-get-buffer-tags)
13512 (org-global-tags-completion-table))))
13513 (org-icompleting-read
13514 "Tag: " 'org-tags-completion-function nil nil nil
13515 'org-tags-history))
13516 (progn
13517 (message "[s]et or [r]emove? ")
13518 (equal (read-char-exclusive) ?r))))
13519 (if (fboundp 'deactivate-mark) (deactivate-mark))
13520 (let ((agendap (equal major-mode 'org-agenda-mode))
13521 l1 l2 m buf pos newhead (cnt 0))
13522 (goto-char end)
13523 (setq l2 (1- (org-current-line)))
13524 (goto-char beg)
13525 (setq l1 (org-current-line))
13526 (loop for l from l1 to l2 do
13527 (org-goto-line l)
13528 (setq m (get-text-property (point) 'org-hd-marker))
13529 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13530 (and agendap m))
13531 (setq buf (if agendap (marker-buffer m) (current-buffer))
13532 pos (if agendap m (point)))
13533 (with-current-buffer buf
13534 (save-excursion
13535 (save-restriction
13536 (goto-char pos)
13537 (setq cnt (1+ cnt))
13538 (org-toggle-tag tag (if off 'off 'on))
13539 (setq newhead (org-get-heading)))))
13540 (and agendap (org-agenda-change-all-lines newhead m))))
13541 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13543 (defun org-tags-completion-function (string predicate &optional flag)
13544 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13545 (confirm (lambda (x) (stringp (car x)))))
13546 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13547 (setq s1 (match-string 1 string)
13548 s2 (match-string 2 string))
13549 (setq s1 "" s2 string))
13550 (cond
13551 ((eq flag nil)
13552 ;; try completion
13553 (setq rtn (try-completion s2 ctable confirm))
13554 (if (stringp rtn)
13555 (setq rtn
13556 (concat s1 s2 (substring rtn (length s2))
13557 (if (and org-add-colon-after-tag-completion
13558 (assoc rtn ctable))
13559 ":" ""))))
13560 rtn)
13561 ((eq flag t)
13562 ;; all-completions
13563 (all-completions s2 ctable confirm)
13565 ((eq flag 'lambda)
13566 ;; exact match?
13567 (assoc s2 ctable)))
13570 (defun org-fast-tag-insert (kwd tags face &optional end)
13571 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13572 (insert (format "%-12s" (concat kwd ":"))
13573 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13574 (or end "")))
13576 (defun org-fast-tag-show-exit (flag)
13577 (save-excursion
13578 (org-goto-line 3)
13579 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13580 (replace-match ""))
13581 (when flag
13582 (end-of-line 1)
13583 (org-move-to-column (- (window-width) 19) t)
13584 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13586 (defun org-set-current-tags-overlay (current prefix)
13587 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13588 (if (featurep 'xemacs)
13589 (org-overlay-display org-tags-overlay (concat prefix s)
13590 'secondary-selection)
13591 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13592 (org-overlay-display org-tags-overlay (concat prefix s)))))
13594 (defvar org-last-tag-selection-key nil)
13595 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13596 "Fast tag selection with single keys.
13597 CURRENT is the current list of tags in the headline, INHERITED is the
13598 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13599 possibly with grouping information. TODO-TABLE is a similar table with
13600 TODO keywords, should these have keys assigned to them.
13601 If the keys are nil, a-z are automatically assigned.
13602 Returns the new tags string, or nil to not change the current settings."
13603 (let* ((fulltable (append table todo-table))
13604 (maxlen (apply 'max (mapcar
13605 (lambda (x)
13606 (if (stringp (car x)) (string-width (car x)) 0))
13607 fulltable)))
13608 (buf (current-buffer))
13609 (expert (eq org-fast-tag-selection-single-key 'expert))
13610 (buffer-tags nil)
13611 (fwidth (+ maxlen 3 1 3))
13612 (ncol (/ (- (window-width) 4) fwidth))
13613 (i-face 'org-done)
13614 (c-face 'org-todo)
13615 tg cnt e c char c1 c2 ntable tbl rtn
13616 ov-start ov-end ov-prefix
13617 (exit-after-next org-fast-tag-selection-single-key)
13618 (done-keywords org-done-keywords)
13619 groups ingroup)
13620 (save-excursion
13621 (beginning-of-line 1)
13622 (if (looking-at
13623 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13624 (setq ov-start (match-beginning 1)
13625 ov-end (match-end 1)
13626 ov-prefix "")
13627 (setq ov-start (1- (point-at-eol))
13628 ov-end (1+ ov-start))
13629 (skip-chars-forward "^\n\r")
13630 (setq ov-prefix
13631 (concat
13632 (buffer-substring (1- (point)) (point))
13633 (if (> (current-column) org-tags-column)
13635 (make-string (- org-tags-column (current-column)) ?\ ))))))
13636 (move-overlay org-tags-overlay ov-start ov-end)
13637 (save-window-excursion
13638 (if expert
13639 (set-buffer (get-buffer-create " *Org tags*"))
13640 (delete-other-windows)
13641 (split-window-vertically)
13642 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13643 (erase-buffer)
13644 (org-set-local 'org-done-keywords done-keywords)
13645 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13646 (org-fast-tag-insert "Current" current c-face "\n\n")
13647 (org-fast-tag-show-exit exit-after-next)
13648 (org-set-current-tags-overlay current ov-prefix)
13649 (setq tbl fulltable char ?a cnt 0)
13650 (while (setq e (pop tbl))
13651 (cond
13652 ((equal (car e) :startgroup)
13653 (push '() groups) (setq ingroup t)
13654 (when (not (= cnt 0))
13655 (setq cnt 0)
13656 (insert "\n"))
13657 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13658 ((equal (car e) :endgroup)
13659 (setq ingroup nil cnt 0)
13660 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13661 ((equal e '(:newline))
13662 (when (not (= cnt 0))
13663 (setq cnt 0)
13664 (insert "\n")
13665 (setq e (car tbl))
13666 (while (equal (car tbl) '(:newline))
13667 (insert "\n")
13668 (setq tbl (cdr tbl)))))
13670 (setq tg (copy-sequence (car e)) c2 nil)
13671 (if (cdr e)
13672 (setq c (cdr e))
13673 ;; automatically assign a character.
13674 (setq c1 (string-to-char
13675 (downcase (substring
13676 tg (if (= (string-to-char tg) ?@) 1 0)))))
13677 (if (or (rassoc c1 ntable) (rassoc c1 table))
13678 (while (or (rassoc char ntable) (rassoc char table))
13679 (setq char (1+ char)))
13680 (setq c2 c1))
13681 (setq c (or c2 char)))
13682 (if ingroup (push tg (car groups)))
13683 (setq tg (org-add-props tg nil 'face
13684 (cond
13685 ((not (assoc tg table))
13686 (org-get-todo-face tg))
13687 ((member tg current) c-face)
13688 ((member tg inherited) i-face)
13689 (t nil))))
13690 (if (and (= cnt 0) (not ingroup)) (insert " "))
13691 (insert "[" c "] " tg (make-string
13692 (- fwidth 4 (length tg)) ?\ ))
13693 (push (cons tg c) ntable)
13694 (when (= (setq cnt (1+ cnt)) ncol)
13695 (insert "\n")
13696 (if ingroup (insert " "))
13697 (setq cnt 0)))))
13698 (setq ntable (nreverse ntable))
13699 (insert "\n")
13700 (goto-char (point-min))
13701 (if (not expert) (org-fit-window-to-buffer))
13702 (setq rtn
13703 (catch 'exit
13704 (while t
13705 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13706 (if (not groups) "no " "")
13707 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13708 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13709 (setq org-last-tag-selection-key c)
13710 (cond
13711 ((= c ?\r) (throw 'exit t))
13712 ((= c ?!)
13713 (setq groups (not groups))
13714 (goto-char (point-min))
13715 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13716 ((= c ?\C-c)
13717 (if (not expert)
13718 (org-fast-tag-show-exit
13719 (setq exit-after-next (not exit-after-next)))
13720 (setq expert nil)
13721 (delete-other-windows)
13722 (set-window-buffer (split-window-vertically) " *Org tags*")
13723 (org-switch-to-buffer-other-window " *Org tags*")
13724 (org-fit-window-to-buffer)))
13725 ((or (= c ?\C-g)
13726 (and (= c ?q) (not (rassoc c ntable))))
13727 (org-detach-overlay org-tags-overlay)
13728 (setq quit-flag t))
13729 ((= c ?\ )
13730 (setq current nil)
13731 (if exit-after-next (setq exit-after-next 'now)))
13732 ((= c ?\t)
13733 (condition-case nil
13734 (setq tg (org-icompleting-read
13735 "Tag: "
13736 (or buffer-tags
13737 (with-current-buffer buf
13738 (org-get-buffer-tags)))))
13739 (quit (setq tg "")))
13740 (when (string-match "\\S-" tg)
13741 (add-to-list 'buffer-tags (list tg))
13742 (if (member tg current)
13743 (setq current (delete tg current))
13744 (push tg current)))
13745 (if exit-after-next (setq exit-after-next 'now)))
13746 ((setq e (rassoc c todo-table) tg (car e))
13747 (with-current-buffer buf
13748 (save-excursion (org-todo tg)))
13749 (if exit-after-next (setq exit-after-next 'now)))
13750 ((setq e (rassoc c ntable) tg (car e))
13751 (if (member tg current)
13752 (setq current (delete tg current))
13753 (loop for g in groups do
13754 (if (member tg g)
13755 (mapc (lambda (x)
13756 (setq current (delete x current)))
13757 g)))
13758 (push tg current))
13759 (if exit-after-next (setq exit-after-next 'now))))
13761 ;; Create a sorted list
13762 (setq current
13763 (sort current
13764 (lambda (a b)
13765 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13766 (if (eq exit-after-next 'now) (throw 'exit t))
13767 (goto-char (point-min))
13768 (beginning-of-line 2)
13769 (delete-region (point) (point-at-eol))
13770 (org-fast-tag-insert "Current" current c-face)
13771 (org-set-current-tags-overlay current ov-prefix)
13772 (while (re-search-forward
13773 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13774 (setq tg (match-string 1))
13775 (add-text-properties
13776 (match-beginning 1) (match-end 1)
13777 (list 'face
13778 (cond
13779 ((member tg current) c-face)
13780 ((member tg inherited) i-face)
13781 (t (get-text-property (match-beginning 1) 'face))))))
13782 (goto-char (point-min)))))
13783 (org-detach-overlay org-tags-overlay)
13784 (if rtn
13785 (mapconcat 'identity current ":")
13786 nil))))
13788 (defun org-get-tags-string ()
13789 "Get the TAGS string in the current headline."
13790 (unless (org-at-heading-p t)
13791 (error "Not on a heading"))
13792 (save-excursion
13793 (beginning-of-line 1)
13794 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13795 (org-match-string-no-properties 1)
13796 "")))
13798 (defun org-get-tags ()
13799 "Get the list of tags specified in the current headline."
13800 (org-split-string (org-get-tags-string) ":"))
13802 (defun org-get-buffer-tags ()
13803 "Get a table of all tags used in the buffer, for completion."
13804 (let (tags)
13805 (save-excursion
13806 (goto-char (point-min))
13807 (while (re-search-forward
13808 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13809 (when (equal (char-after (point-at-bol 0)) ?*)
13810 (mapc (lambda (x) (add-to-list 'tags x))
13811 (org-split-string (org-match-string-no-properties 1) ":")))))
13812 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13813 (mapcar 'list tags)))
13815 ;;;; The mapping API
13817 ;;;###autoload
13818 (defun org-map-entries (func &optional match scope &rest skip)
13819 "Call FUNC at each headline selected by MATCH in SCOPE.
13821 FUNC is a function or a lisp form. The function will be called without
13822 arguments, with the cursor positioned at the beginning of the headline.
13823 The return values of all calls to the function will be collected and
13824 returned as a list.
13826 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13827 does not need to preserve point. After evaluation, the cursor will be
13828 moved to the end of the line (presumably of the headline of the
13829 processed entry) and search continues from there. Under some
13830 circumstances, this may not produce the wanted results. For example,
13831 if you have removed (e.g. archived) the current (sub)tree it could
13832 mean that the next entry will be skipped entirely. In such cases, you
13833 can specify the position from where search should continue by making
13834 FUNC set the variable `org-map-continue-from' to the desired buffer
13835 position.
13837 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13838 Only headlines that are matched by this query will be considered during
13839 the iteration. When MATCH is nil or t, all headlines will be
13840 visited by the iteration.
13842 SCOPE determines the scope of this command. It can be any of:
13844 nil The current buffer, respecting the restriction if any
13845 tree The subtree started with the entry at point
13846 region The entries within the active region, if any
13847 region-start-level
13848 The entries within the active region, but only those at
13849 the same level than the first one.
13850 file The current buffer, without restriction
13851 file-with-archives
13852 The current buffer, and any archives associated with it
13853 agenda All agenda files
13854 agenda-with-archives
13855 All agenda files with any archive files associated with them
13856 \(file1 file2 ...)
13857 If this is a list, all files in the list will be scanned
13859 The remaining args are treated as settings for the skipping facilities of
13860 the scanner. The following items can be given here:
13862 archive skip trees with the archive tag.
13863 comment skip trees with the COMMENT keyword
13864 function or Emacs Lisp form:
13865 will be used as value for `org-agenda-skip-function', so whenever
13866 the function returns t, FUNC will not be called for that
13867 entry and search will continue from the point where the
13868 function leaves it.
13870 If your function needs to retrieve the tags including inherited tags
13871 at the *current* entry, you can use the value of the variable
13872 `org-scanner-tags' which will be much faster than getting the value
13873 with `org-get-tags-at'. If your function gets properties with
13874 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13875 to t around the call to `org-entry-properties' to get the same speedup.
13876 Note that if your function moves around to retrieve tags and properties at
13877 a *different* entry, you cannot use these techniques."
13878 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13879 (not (org-region-active-p)))
13880 (let* ((org-agenda-archives-mode nil) ; just to make sure
13881 (org-agenda-skip-archived-trees (memq 'archive skip))
13882 (org-agenda-skip-comment-trees (memq 'comment skip))
13883 (org-agenda-skip-function
13884 (car (org-delete-all '(comment archive) skip)))
13885 (org-tags-match-list-sublevels t)
13886 (start-level (eq scope 'region-start-level))
13887 matcher file res
13888 org-todo-keywords-for-agenda
13889 org-done-keywords-for-agenda
13890 org-todo-keyword-alist-for-agenda
13891 org-drawers-for-agenda
13892 org-tag-alist-for-agenda
13893 todo-only)
13895 (cond
13896 ((eq match t) (setq matcher t))
13897 ((eq match nil) (setq matcher t))
13898 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13900 (save-excursion
13901 (save-restriction
13902 (cond ((eq scope 'tree)
13903 (org-back-to-heading t)
13904 (org-narrow-to-subtree)
13905 (setq scope nil))
13906 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13907 (org-region-active-p))
13908 ;; If needed, set start-level to a string like "2"
13909 (when start-level
13910 (save-excursion
13911 (goto-char (region-beginning))
13912 (unless (org-at-heading-p) (outline-next-heading))
13913 (setq start-level (org-current-level))))
13914 (narrow-to-region (region-beginning)
13915 (save-excursion
13916 (goto-char (region-end))
13917 (unless (and (bolp) (org-at-heading-p))
13918 (outline-next-heading))
13919 (point)))
13920 (setq scope nil)))
13922 (if (not scope)
13923 (progn
13924 (org-prepare-agenda-buffers
13925 (list (buffer-file-name (current-buffer))))
13926 (setq res (org-scan-tags func matcher todo-only start-level)))
13927 ;; Get the right scope
13928 (cond
13929 ((and scope (listp scope) (symbolp (car scope)))
13930 (setq scope (eval scope)))
13931 ((eq scope 'agenda)
13932 (setq scope (org-agenda-files t)))
13933 ((eq scope 'agenda-with-archives)
13934 (setq scope (org-agenda-files t))
13935 (setq scope (org-add-archive-files scope)))
13936 ((eq scope 'file)
13937 (setq scope (list (buffer-file-name))))
13938 ((eq scope 'file-with-archives)
13939 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13940 (org-prepare-agenda-buffers scope)
13941 (while (setq file (pop scope))
13942 (with-current-buffer (org-find-base-buffer-visiting file)
13943 (save-excursion
13944 (save-restriction
13945 (widen)
13946 (goto-char (point-min))
13947 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
13948 res)))
13950 ;;;; Properties
13952 ;;; Setting and retrieving properties
13954 (defconst org-special-properties
13955 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13956 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13957 "The special properties valid in Org-mode.
13959 These are properties that are not defined in the property drawer,
13960 but in some other way.")
13962 (defconst org-default-properties
13963 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13964 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13965 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13966 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13967 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13968 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13969 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13970 "Some properties that are used by Org-mode for various purposes.
13971 Being in this list makes sure that they are offered for completion.")
13973 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13974 "Regular expression matching the first line of a property drawer.")
13976 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13977 "Regular expression matching the last line of a property drawer.")
13979 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13980 "Regular expression matching the first line of a property drawer.")
13982 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13983 "Regular expression matching the first line of a property drawer.")
13985 (defconst org-property-drawer-re
13986 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13987 org-property-end-re "\\)\n?")
13988 "Matches an entire property drawer.")
13990 (defconst org-clock-drawer-re
13991 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13992 org-property-end-re "\\)\n?")
13993 "Matches an entire clock drawer.")
13995 (defsubst org-re-property (property)
13996 "Return a regexp matching PROPERTY.
13997 Match group 1 will be set to the value "
13998 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14000 (defun org-property-action ()
14001 "Do an action on properties."
14002 (interactive)
14003 (let (c)
14004 (org-at-property-p)
14005 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14006 (setq c (read-char-exclusive))
14007 (cond
14008 ((equal c ?s)
14009 (call-interactively 'org-set-property))
14010 ((equal c ?d)
14011 (call-interactively 'org-delete-property))
14012 ((equal c ?D)
14013 (call-interactively 'org-delete-property-globally))
14014 ((equal c ?c)
14015 (call-interactively 'org-compute-property-at-point))
14016 (t (error "No such property action %c" c)))))
14018 (defun org-set-effort (&optional value)
14019 "Set the effort property of the current entry.
14020 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14021 allowed value."
14022 (interactive "P")
14023 (if (equal value 0) (setq value 10))
14024 (let* ((completion-ignore-case t)
14025 (prop org-effort-property)
14026 (cur (org-entry-get nil prop))
14027 (allowed (org-property-get-allowed-values nil prop 'table))
14028 (existing (mapcar 'list (org-property-values prop)))
14030 (val (cond
14031 ((stringp value) value)
14032 ((and allowed (integerp value))
14033 (or (car (nth (1- value) allowed))
14034 (car (org-last allowed))))
14035 (allowed
14036 (message "Select 1-9,0, [RET%s]: %s"
14037 (if cur (concat "=" cur) "")
14038 (mapconcat 'car allowed " "))
14039 (setq rpl (read-char-exclusive))
14040 (if (equal rpl ?\r)
14042 (setq rpl (- rpl ?0))
14043 (if (equal rpl 0) (setq rpl 10))
14044 (if (and (> rpl 0) (<= rpl (length allowed)))
14045 (car (nth (1- rpl) allowed))
14046 (org-completing-read "Effort: " allowed nil))))
14048 (let (org-completion-use-ido org-completion-use-iswitchb)
14049 (org-completing-read
14050 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14051 (concat "[" cur "]") "")
14052 ": ")
14053 existing nil nil "" nil cur))))))
14054 (unless (equal (org-entry-get nil prop) val)
14055 (org-entry-put nil prop val))
14056 (message "%s is now %s" prop val)))
14058 (defun org-at-property-p ()
14059 "Is cursor inside a property drawer?"
14060 (save-excursion
14061 (beginning-of-line 1)
14062 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14063 (save-match-data ;; Used by calling procedures
14064 (let ((p (point))
14065 (range (unless (org-before-first-heading-p)
14066 (org-get-property-block))))
14067 (and range (<= (car range) p) (< p (cdr range))))))))
14069 (defun org-get-property-block (&optional beg end force)
14070 "Return the (beg . end) range of the body of the property drawer.
14071 BEG and END can be beginning and end of subtree, if not given
14072 they will be found.
14073 If the drawer does not exist and FORCE is non-nil, create the drawer."
14074 (catch 'exit
14075 (save-excursion
14076 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14077 (end (or end (progn (outline-next-heading) (point)))))
14078 (goto-char beg)
14079 (if (re-search-forward org-property-start-re end t)
14080 (setq beg (1+ (match-end 0)))
14081 (if force
14082 (save-excursion
14083 (org-insert-property-drawer)
14084 (setq end (progn (outline-next-heading) (point))))
14085 (throw 'exit nil))
14086 (goto-char beg)
14087 (if (re-search-forward org-property-start-re end t)
14088 (setq beg (1+ (match-end 0)))))
14089 (if (re-search-forward org-property-end-re end t)
14090 (setq end (match-beginning 0))
14091 (or force (throw 'exit nil))
14092 (goto-char beg)
14093 (setq end beg)
14094 (org-indent-line-function)
14095 (insert ":END:\n"))
14096 (cons beg end)))))
14098 (defun org-entry-properties (&optional pom which specific)
14099 "Get all properties of the entry at point-or-marker POM.
14100 This includes the TODO keyword, the tags, time strings for deadline,
14101 scheduled, and clocking, and any additional properties defined in the
14102 entry. The return value is an alist, keys may occur multiple times
14103 if the property key was used several times.
14104 POM may also be nil, in which case the current entry is used.
14105 If WHICH is nil or `all', get all properties. If WHICH is
14106 `special' or `standard', only get that subclass. If WHICH
14107 is a string only get exactly this property. SPECIFIC can be a string, the
14108 specific property we are interested in. Specifying it can speed
14109 things up because then unnecessary parsing is avoided."
14110 (setq which (or which 'all))
14111 (org-with-point-at pom
14112 (let ((clockstr (substring org-clock-string 0 -1))
14113 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14114 (case-fold-search nil)
14115 beg end range props sum-props key key1 value string clocksum)
14116 (save-excursion
14117 (when (condition-case nil
14118 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14119 (error nil))
14120 (setq beg (point))
14121 (setq sum-props (get-text-property (point) 'org-summaries))
14122 (setq clocksum (get-text-property (point) :org-clock-minutes))
14123 (outline-next-heading)
14124 (setq end (point))
14125 (when (memq which '(all special))
14126 ;; Get the special properties, like TODO and tags
14127 (goto-char beg)
14128 (when (and (or (not specific) (string= specific "TODO"))
14129 (looking-at org-todo-line-regexp) (match-end 2))
14130 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14131 (when (and (or (not specific) (string= specific "PRIORITY"))
14132 (looking-at org-priority-regexp))
14133 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14134 (when (or (not specific) (string= specific "FILE"))
14135 (push (cons "FILE" buffer-file-name) props))
14136 (when (and (or (not specific) (string= specific "TAGS"))
14137 (setq value (org-get-tags-string))
14138 (string-match "\\S-" value))
14139 (push (cons "TAGS" value) props))
14140 (when (and (or (not specific) (string= specific "ALLTAGS"))
14141 (setq value (org-get-tags-at)))
14142 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14143 ":"))
14144 props))
14145 (when (or (not specific) (string= specific "BLOCKED"))
14146 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14147 (when (or (not specific)
14148 (member specific
14149 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14150 "TIMESTAMP" "TIMESTAMP_IA")))
14151 (catch 'match
14152 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14153 (setq key (if (match-end 1)
14154 (substring (org-match-string-no-properties 1)
14155 0 -1))
14156 string (if (equal key clockstr)
14157 (org-no-properties
14158 (org-trim
14159 (buffer-substring
14160 (match-beginning 3) (goto-char
14161 (point-at-eol)))))
14162 (substring (org-match-string-no-properties 3)
14163 1 -1)))
14164 ;; Get the correct property name from the key. This is
14165 ;; necessary if the user has configured time keywords.
14166 (setq key1 (concat key ":"))
14167 (cond
14168 ((not key)
14169 (setq key
14170 (if (= (char-after (match-beginning 3)) ?\[)
14171 "TIMESTAMP_IA" "TIMESTAMP")))
14172 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14173 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14174 ((equal key1 org-closed-string) (setq key "CLOSED"))
14175 ((equal key1 org-clock-string) (setq key "CLOCK")))
14176 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14177 (progn
14178 (push (cons key string) props)
14179 ;; no need to search further if match is found
14180 (throw 'match t))
14181 (when (or (equal key "CLOCK") (not (assoc key props)))
14182 (push (cons key string) props))))))
14185 (when (memq which '(all standard))
14186 ;; Get the standard properties, like :PROP: ...
14187 (setq range (org-get-property-block beg end))
14188 (when range
14189 (goto-char (car range))
14190 (while (re-search-forward
14191 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14192 (cdr range) t)
14193 (setq key (org-match-string-no-properties 1)
14194 value (org-trim (or (org-match-string-no-properties 2) "")))
14195 (unless (member key excluded)
14196 (push (cons key (or value "")) props)))))
14197 (if clocksum
14198 (push (cons "CLOCKSUM"
14199 (org-columns-number-to-string (/ (float clocksum) 60.)
14200 'add_times))
14201 props))
14202 (unless (assoc "CATEGORY" props)
14203 (push (cons "CATEGORY" (org-get-category)) props))
14204 (append sum-props (nreverse props)))))))
14206 (defun org-entry-get (pom property &optional inherit literal-nil)
14207 "Get value of PROPERTY for entry at point-or-marker POM.
14208 If INHERIT is non-nil and the entry does not have the property,
14209 then also check higher levels of the hierarchy.
14210 If INHERIT is the symbol `selective', use inheritance only if the setting
14211 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14212 If the property is present but empty, the return value is the empty string.
14213 If the property is not present at all, nil is returned.
14215 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14216 do not interpret it as the list atom nil. This is used for inheritance
14217 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14218 (org-with-point-at pom
14219 (if (and inherit (if (eq inherit 'selective)
14220 (org-property-inherit-p property)
14222 (org-entry-get-with-inheritance property literal-nil)
14223 (if (member property org-special-properties)
14224 ;; We need a special property. Use `org-entry-properties' to
14225 ;; retrieve it, but specify the wanted property
14226 (cdr (assoc property (org-entry-properties nil 'special property)))
14227 (let ((range (unless (org-before-first-heading-p)
14228 (org-get-property-block)))
14229 (props (list (or (assoc property org-file-properties)
14230 (assoc property org-global-properties)
14231 (assoc property org-global-properties-fixed))))
14232 val)
14233 (flet ((ap (key)
14234 (when (re-search-forward
14235 (org-re-property key) (cdr range) t)
14236 (setq props
14237 (org-update-property-plist
14239 (if (match-end 1)
14240 (org-match-string-no-properties 1) "")
14241 props)))))
14242 (when (and range (goto-char (car range)))
14243 (ap property)
14244 (goto-char (car range))
14245 (while (ap (concat property "+")))
14246 (setq val (cdr (assoc property props)))
14247 (when val (if literal-nil val (org-not-nil val))))))))))
14249 (defun org-property-or-variable-value (var &optional inherit)
14250 "Check if there is a property fixing the value of VAR.
14251 If yes, return this value. If not, return the current value of the variable."
14252 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14253 (if (and prop (stringp prop) (string-match "\\S-" prop))
14254 (read prop)
14255 (symbol-value var))))
14257 (defun org-entry-delete (pom property)
14258 "Delete the property PROPERTY from entry at point-or-marker POM."
14259 (org-with-point-at pom
14260 (if (member property org-special-properties)
14261 nil ; cannot delete these properties.
14262 (let ((range (org-get-property-block)))
14263 (if (and range
14264 (goto-char (car range))
14265 (re-search-forward
14266 (org-re-property property)
14267 (cdr range) t))
14268 (progn
14269 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14271 nil)))))
14273 ;; Multi-values properties are properties that contain multiple values
14274 ;; These values are assumed to be single words, separated by whitespace.
14275 (defun org-entry-add-to-multivalued-property (pom property value)
14276 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14277 (let* ((old (org-entry-get pom property))
14278 (values (and old (org-split-string old "[ \t]"))))
14279 (setq value (org-entry-protect-space value))
14280 (unless (member value values)
14281 (setq values (cons value values))
14282 (org-entry-put pom property
14283 (mapconcat 'identity values " ")))))
14285 (defun org-entry-remove-from-multivalued-property (pom property value)
14286 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14287 (let* ((old (org-entry-get pom property))
14288 (values (and old (org-split-string old "[ \t]"))))
14289 (setq value (org-entry-protect-space value))
14290 (when (member value values)
14291 (setq values (delete value values))
14292 (org-entry-put pom property
14293 (mapconcat 'identity values " ")))))
14295 (defun org-entry-member-in-multivalued-property (pom property value)
14296 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14297 (let* ((old (org-entry-get pom property))
14298 (values (and old (org-split-string old "[ \t]"))))
14299 (setq value (org-entry-protect-space value))
14300 (member value values)))
14302 (defun org-entry-get-multivalued-property (pom property)
14303 "Return a list of values in a multivalued property."
14304 (let* ((value (org-entry-get pom property))
14305 (values (and value (org-split-string value "[ \t]"))))
14306 (mapcar 'org-entry-restore-space values)))
14308 (defun org-entry-put-multivalued-property (pom property &rest values)
14309 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14310 VALUES should be a list of strings. Spaces will be protected."
14311 (org-entry-put pom property
14312 (mapconcat 'org-entry-protect-space values " "))
14313 (let* ((value (org-entry-get pom property))
14314 (values (and value (org-split-string value "[ \t]"))))
14315 (mapcar 'org-entry-restore-space values)))
14317 (defun org-entry-protect-space (s)
14318 "Protect spaces and newline in string S."
14319 (while (string-match " " s)
14320 (setq s (replace-match "%20" t t s)))
14321 (while (string-match "\n" s)
14322 (setq s (replace-match "%0A" t t s)))
14325 (defun org-entry-restore-space (s)
14326 "Restore spaces and newline in string S."
14327 (while (string-match "%20" s)
14328 (setq s (replace-match " " t t s)))
14329 (while (string-match "%0A" s)
14330 (setq s (replace-match "\n" t t s)))
14333 (defvar org-entry-property-inherited-from (make-marker)
14334 "Marker pointing to the entry from where a property was inherited.
14335 Each call to `org-entry-get-with-inheritance' will set this marker to the
14336 location of the entry where the inheritance search matched. If there was
14337 no match, the marker will point nowhere.
14338 Note that also `org-entry-get' calls this function, if the INHERIT flag
14339 is set.")
14341 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14342 "Get entry property, and search higher levels if not present.
14343 The search will stop at the first ancestor which has the property defined.
14344 If the value found is \"nil\", return nil to show that the property
14345 should be considered as undefined (this is the meaning of nil here).
14346 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14347 (move-marker org-entry-property-inherited-from nil)
14348 (let (tmp)
14349 (unless (org-before-first-heading-p)
14350 (save-excursion
14351 (save-restriction
14352 (widen)
14353 (catch 'ex
14354 (while t
14355 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14356 (org-back-to-heading t)
14357 (move-marker org-entry-property-inherited-from (point))
14358 (throw 'ex tmp))
14359 (or (org-up-heading-safe) (throw 'ex nil)))))))
14360 (setq tmp (or tmp
14361 (cdr (assoc property org-file-properties))
14362 (cdr (assoc property org-global-properties))
14363 (cdr (assoc property org-global-properties-fixed))))
14364 (if literal-nil tmp (org-not-nil tmp))))
14366 (defvar org-property-changed-functions nil
14367 "Hook called when the value of a property has changed.
14368 Each hook function should accept two arguments, the name of the property
14369 and the new value.")
14371 (defun org-entry-put (pom property value)
14372 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14373 (org-with-point-at pom
14374 (org-back-to-heading t)
14375 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14376 range)
14377 (cond
14378 ((equal property "TODO")
14379 (when (and (stringp value) (string-match "\\S-" value)
14380 (not (member value org-todo-keywords-1)))
14381 (error "\"%s\" is not a valid TODO state" value))
14382 (if (or (not value)
14383 (not (string-match "\\S-" value)))
14384 (setq value 'none))
14385 (org-todo value)
14386 (org-set-tags nil 'align))
14387 ((equal property "PRIORITY")
14388 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14389 (string-to-char value) ?\ ))
14390 (org-set-tags nil 'align))
14391 ((equal property "SCHEDULED")
14392 (if (re-search-forward org-scheduled-time-regexp end t)
14393 (cond
14394 ((eq value 'earlier) (org-timestamp-change -1 'day))
14395 ((eq value 'later) (org-timestamp-change 1 'day))
14396 (t (call-interactively 'org-schedule)))
14397 (call-interactively 'org-schedule)))
14398 ((equal property "DEADLINE")
14399 (if (re-search-forward org-deadline-time-regexp end t)
14400 (cond
14401 ((eq value 'earlier) (org-timestamp-change -1 'day))
14402 ((eq value 'later) (org-timestamp-change 1 'day))
14403 (t (call-interactively 'org-deadline)))
14404 (call-interactively 'org-deadline)))
14405 ((member property org-special-properties)
14406 (error "The %s property can not yet be set with `org-entry-put'"
14407 property))
14408 (t ; a non-special property
14409 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14410 (setq range (org-get-property-block beg end 'force))
14411 (goto-char (car range))
14412 (if (re-search-forward
14413 (org-re-property property) (cdr range) t)
14414 (progn
14415 (delete-region (match-beginning 0) (match-end 0))
14416 (goto-char (match-beginning 0)))
14417 (goto-char (cdr range))
14418 (insert "\n")
14419 (backward-char 1)
14420 (org-indent-line-function))
14421 (insert ":" property ":")
14422 (and value (insert " " value))
14423 (org-indent-line-function)))))
14424 (run-hook-with-args 'org-property-changed-functions property value)))
14426 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14427 "Get all property keys in the current buffer.
14428 With INCLUDE-SPECIALS, also list the special properties that reflect things
14429 like tags and TODO state.
14430 With INCLUDE-DEFAULTS, also include properties that has special meaning
14431 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14432 and others.
14433 With INCLUDE-COLUMNS, also include property names given in COLUMN
14434 formats in the current buffer."
14435 (let (rtn range cfmt s p)
14436 (save-excursion
14437 (save-restriction
14438 (widen)
14439 (goto-char (point-min))
14440 (while (re-search-forward org-property-start-re nil t)
14441 (setq range (org-get-property-block))
14442 (goto-char (car range))
14443 (while (re-search-forward
14444 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14445 (cdr range) t)
14446 (add-to-list 'rtn (org-match-string-no-properties 1)))
14447 (outline-next-heading))))
14449 (when include-specials
14450 (setq rtn (append org-special-properties rtn)))
14452 (when include-defaults
14453 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14454 (add-to-list 'rtn org-effort-property))
14456 (when include-columns
14457 (save-excursion
14458 (save-restriction
14459 (widen)
14460 (goto-char (point-min))
14461 (while (re-search-forward
14462 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14463 nil t)
14464 (setq cfmt (match-string 2) s 0)
14465 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14466 cfmt s)
14467 (setq s (match-end 0)
14468 p (match-string 1 cfmt))
14469 (unless (or (equal p "ITEM")
14470 (member p org-special-properties))
14471 (add-to-list 'rtn (match-string 1 cfmt))))))))
14473 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14475 (defun org-property-values (key)
14476 "Return a list of all values of property KEY in the current buffer."
14477 (save-excursion
14478 (save-restriction
14479 (widen)
14480 (goto-char (point-min))
14481 (let ((re (org-re-property key))
14482 values)
14483 (while (re-search-forward re nil t)
14484 (add-to-list 'values (org-trim (match-string 1))))
14485 (delete "" values)))))
14487 (defun org-insert-property-drawer ()
14488 "Insert a property drawer into the current entry."
14489 (interactive)
14490 (org-back-to-heading t)
14491 (looking-at org-outline-regexp)
14492 (let ((indent (if org-adapt-indentation
14493 (- (match-end 0)(match-beginning 0))
14495 (beg (point))
14496 (re (concat "^[ \t]*" org-keyword-time-regexp))
14497 end hiddenp)
14498 (outline-next-heading)
14499 (setq end (point))
14500 (goto-char beg)
14501 (while (re-search-forward re end t))
14502 (setq hiddenp (outline-invisible-p))
14503 (end-of-line 1)
14504 (and (equal (char-after) ?\n) (forward-char 1))
14505 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14506 (if (member (match-string 1) '("CLOCK:" ":END:"))
14507 ;; just skip this line
14508 (beginning-of-line 2)
14509 ;; Drawer start, find the end
14510 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14511 (beginning-of-line 1)))
14512 (org-skip-over-state-notes)
14513 (skip-chars-backward " \t\n\r")
14514 (if (eq (char-before) ?*) (forward-char 1))
14515 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14516 (beginning-of-line 0)
14517 (org-indent-to-column indent)
14518 (beginning-of-line 2)
14519 (org-indent-to-column indent)
14520 (beginning-of-line 0)
14521 (if hiddenp
14522 (save-excursion
14523 (org-back-to-heading t)
14524 (hide-entry))
14525 (org-flag-drawer t))))
14527 (defvar org-property-set-functions-alist nil
14528 "Property set function alist.
14529 Each entry should have the following format:
14531 (PROPERTY . READ-FUNCTION)
14533 The read function will be called with the same argument as
14534 `org-completing-read'.")
14536 (defun org-set-property-function (property)
14537 "Get the function that should be used to set PROPERTY.
14538 This is computed according to `org-property-set-functions-alist'."
14539 (or (cdr (assoc property org-property-set-functions-alist))
14540 'org-completing-read))
14542 (defun org-read-property-value (property)
14543 "Read PROPERTY value from user."
14544 (let* ((completion-ignore-case t)
14545 (allowed (org-property-get-allowed-values nil property 'table))
14546 (cur (org-entry-get nil property))
14547 (prompt (concat property " value"
14548 (if (and cur (string-match "\\S-" cur))
14549 (concat " [" cur "]") "") ": "))
14550 (set-function (org-set-property-function property))
14551 (val (if allowed
14552 (funcall set-function prompt allowed nil
14553 (not (get-text-property 0 'org-unrestricted
14554 (caar allowed))))
14555 (let (org-completion-use-ido org-completion-use-iswitchb)
14556 (funcall set-function prompt
14557 (mapcar 'list (org-property-values property))
14558 nil nil "" nil cur)))))
14559 (if (equal val "")
14561 val)))
14563 (defvar org-last-set-property nil)
14564 (defun org-read-property-name ()
14565 "Read a property name."
14566 (let* ((completion-ignore-case t)
14567 (keys (org-buffer-property-keys nil t t))
14568 (default-prop (or (save-excursion
14569 (save-match-data
14570 (beginning-of-line)
14571 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14572 (null (string= (match-string 1) "END"))
14573 (match-string 1))))
14574 org-last-set-property))
14575 (property (org-icompleting-read
14576 (concat "Property"
14577 (if default-prop (concat " [" default-prop "]") "")
14578 ": ")
14579 (mapcar 'list keys)
14580 nil nil nil nil
14581 default-prop
14583 (if (member property keys)
14584 property
14585 (or (cdr (assoc (downcase property)
14586 (mapcar (lambda (x) (cons (downcase x) x))
14587 keys)))
14588 property))))
14590 (defun org-set-property (property value)
14591 "In the current entry, set PROPERTY to VALUE.
14592 When called interactively, this will prompt for a property name, offering
14593 completion on existing and default properties. And then it will prompt
14594 for a value, offering completion either on allowed values (via an inherited
14595 xxx_ALL property) or on existing values in other instances of this property
14596 in the current file."
14597 (interactive (list nil nil))
14598 (let* ((property (or property (org-read-property-name)))
14599 (value (or value (org-read-property-value property)))
14600 (fn (assoc property org-properties-postprocess-alist)))
14601 (setq org-last-set-property property)
14602 ;; Possibly postprocess the inserted value:
14603 (when fn (setq value (funcall (cadr fn) value)))
14604 (unless (equal (org-entry-get nil property) value)
14605 (org-entry-put nil property value))))
14607 (defun org-delete-property (property)
14608 "In the current entry, delete PROPERTY."
14609 (interactive
14610 (let* ((completion-ignore-case t)
14611 (prop (org-icompleting-read "Property: "
14612 (org-entry-properties nil 'standard))))
14613 (list prop)))
14614 (message "Property %s %s" property
14615 (if (org-entry-delete nil property)
14616 "deleted"
14617 "was not present in the entry")))
14619 (defun org-delete-property-globally (property)
14620 "Remove PROPERTY globally, from all entries."
14621 (interactive
14622 (let* ((completion-ignore-case t)
14623 (prop (org-icompleting-read
14624 "Globally remove property: "
14625 (mapcar 'list (org-buffer-property-keys)))))
14626 (list prop)))
14627 (save-excursion
14628 (save-restriction
14629 (widen)
14630 (goto-char (point-min))
14631 (let ((cnt 0))
14632 (while (re-search-forward
14633 (org-re-property property)
14634 nil t)
14635 (setq cnt (1+ cnt))
14636 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14637 (message "Property \"%s\" removed from %d entries" property cnt)))))
14639 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14641 (defun org-compute-property-at-point ()
14642 "Compute the property at point.
14643 This looks for an enclosing column format, extracts the operator and
14644 then applies it to the property in the column format's scope."
14645 (interactive)
14646 (unless (org-at-property-p)
14647 (error "Not at a property"))
14648 (let ((prop (org-match-string-no-properties 2)))
14649 (org-columns-get-format-and-top-level)
14650 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14651 (error "No operator defined for property %s" prop))
14652 (org-columns-compute prop)))
14654 (defvar org-property-allowed-value-functions nil
14655 "Hook for functions supplying allowed values for a specific property.
14656 The functions must take a single argument, the name of the property, and
14657 return a flat list of allowed values. If \":ETC\" is one of
14658 the values, this means that these values are intended as defaults for
14659 completion, but that other values should be allowed too.
14660 The functions must return nil if they are not responsible for this
14661 property.")
14663 (defun org-property-get-allowed-values (pom property &optional table)
14664 "Get allowed values for the property PROPERTY.
14665 When TABLE is non-nil, return an alist that can directly be used for
14666 completion."
14667 (let (vals)
14668 (cond
14669 ((equal property "TODO")
14670 (setq vals (org-with-point-at pom
14671 (append org-todo-keywords-1 '("")))))
14672 ((equal property "PRIORITY")
14673 (let ((n org-lowest-priority))
14674 (while (>= n org-highest-priority)
14675 (push (char-to-string n) vals)
14676 (setq n (1- n)))))
14677 ((member property org-special-properties))
14678 ((setq vals (run-hook-with-args-until-success
14679 'org-property-allowed-value-functions property)))
14681 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14682 (when (and vals (string-match "\\S-" vals))
14683 (setq vals (car (read-from-string (concat "(" vals ")"))))
14684 (setq vals (mapcar (lambda (x)
14685 (cond ((stringp x) x)
14686 ((numberp x) (number-to-string x))
14687 ((symbolp x) (symbol-name x))
14688 (t "???")))
14689 vals)))))
14690 (when (member ":ETC" vals)
14691 (setq vals (remove ":ETC" vals))
14692 (org-add-props (car vals) '(org-unrestricted t)))
14693 (if table (mapcar 'list vals) vals)))
14695 (defun org-property-previous-allowed-value (&optional previous)
14696 "Switch to the next allowed value for this property."
14697 (interactive)
14698 (org-property-next-allowed-value t))
14700 (defun org-property-next-allowed-value (&optional previous)
14701 "Switch to the next allowed value for this property."
14702 (interactive)
14703 (unless (org-at-property-p)
14704 (error "Not at a property"))
14705 (let* ((key (match-string 2))
14706 (value (match-string 3))
14707 (allowed (or (org-property-get-allowed-values (point) key)
14708 (and (member value '("[ ]" "[-]" "[X]"))
14709 '("[ ]" "[X]"))))
14710 nval)
14711 (unless allowed
14712 (error "Allowed values for this property have not been defined"))
14713 (if previous (setq allowed (reverse allowed)))
14714 (if (member value allowed)
14715 (setq nval (car (cdr (member value allowed)))))
14716 (setq nval (or nval (car allowed)))
14717 (if (equal nval value)
14718 (error "Only one allowed value for this property"))
14719 (org-at-property-p)
14720 (replace-match (concat " :" key ": " nval) t t)
14721 (org-indent-line-function)
14722 (beginning-of-line 1)
14723 (skip-chars-forward " \t")
14724 (run-hook-with-args 'org-property-changed-functions key nval)))
14726 (defun org-find-olp (path &optional this-buffer)
14727 "Return a marker pointing to the entry at outline path OLP.
14728 If anything goes wrong, throw an error.
14729 You can wrap this call to catch the error like this:
14731 (condition-case msg
14732 (org-mobile-locate-entry (match-string 4))
14733 (error (nth 1 msg)))
14735 The return value will then be either a string with the error message,
14736 or a marker if everything is OK.
14738 If THIS-BUFFER is set, the outline path does not contain a file,
14739 only headings."
14740 (let* ((file (if this-buffer buffer-file-name (pop path)))
14741 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14742 (level 1)
14743 (lmin 1)
14744 (lmax 1)
14745 limit re end found pos heading cnt flevel)
14746 (unless buffer (error "File not found :%s" file))
14747 (with-current-buffer buffer
14748 (save-excursion
14749 (save-restriction
14750 (widen)
14751 (setq limit (point-max))
14752 (goto-char (point-min))
14753 (while (setq heading (pop path))
14754 (setq re (format org-complex-heading-regexp-format
14755 (regexp-quote heading)))
14756 (setq cnt 0 pos (point))
14757 (while (re-search-forward re end t)
14758 (setq level (- (match-end 1) (match-beginning 1)))
14759 (if (and (>= level lmin) (<= level lmax))
14760 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14761 (when (= cnt 0) (error "Heading not found on level %d: %s"
14762 lmax heading))
14763 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14764 lmax heading))
14765 (goto-char found)
14766 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14767 (setq end (save-excursion (org-end-of-subtree t t))))
14768 (when (org-at-heading-p)
14769 (move-marker (make-marker) (point))))))))
14771 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14772 "Find node HEADING in BUFFER.
14773 Return a marker to the heading if it was found, or nil if not.
14774 If POS-ONLY is set, return just the position instead of a marker.
14776 The heading text must match exact, but it may have a TODO keyword,
14777 a priority cookie and tags in the standard locations."
14778 (with-current-buffer (or buffer (current-buffer))
14779 (save-excursion
14780 (save-restriction
14781 (widen)
14782 (goto-char (point-min))
14783 (let (case-fold-search)
14784 (if (re-search-forward
14785 (format org-complex-heading-regexp-format
14786 (regexp-quote heading)) nil t)
14787 (if pos-only
14788 (match-beginning 0)
14789 (move-marker (make-marker) (match-beginning 0)))))))))
14791 (defun org-find-exact-heading-in-directory (heading &optional dir)
14792 "Find Org node headline HEADING in all .org files in directory DIR.
14793 When the target headline is found, return a marker to this location."
14794 (let ((files (directory-files (or dir default-directory)
14795 nil "\\`[^.#].*\\.org\\'"))
14796 file visiting m buffer)
14797 (catch 'found
14798 (while (setq file (pop files))
14799 (message "trying %s" file)
14800 (setq visiting (org-find-base-buffer-visiting file))
14801 (setq buffer (or visiting (find-file-noselect file)))
14802 (setq m (org-find-exact-headline-in-buffer
14803 heading buffer))
14804 (when (and (not m) (not visiting)) (kill-buffer buffer))
14805 (and m (throw 'found m))))))
14807 (defun org-find-entry-with-id (ident)
14808 "Locate the entry that contains the ID property with exact value IDENT.
14809 IDENT can be a string, a symbol or a number, this function will search for
14810 the string representation of it.
14811 Return the position where this entry starts, or nil if there is no such entry."
14812 (interactive "sID: ")
14813 (let ((id (cond
14814 ((stringp ident) ident)
14815 ((symbol-name ident) (symbol-name ident))
14816 ((numberp ident) (number-to-string ident))
14817 (t (error "IDENT %s must be a string, symbol or number" ident))))
14818 (case-fold-search nil))
14819 (save-excursion
14820 (save-restriction
14821 (widen)
14822 (goto-char (point-min))
14823 (when (re-search-forward
14824 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14825 nil t)
14826 (org-back-to-heading t)
14827 (point))))))
14829 ;;;; Timestamps
14831 (defvar org-last-changed-timestamp nil)
14832 (defvar org-last-inserted-timestamp nil
14833 "The last time stamp inserted with `org-insert-time-stamp'.")
14834 (defvar org-time-was-given) ; dynamically scoped parameter
14835 (defvar org-end-time-was-given) ; dynamically scoped parameter
14836 (defvar org-ts-what) ; dynamically scoped parameter
14838 (defun org-time-stamp (arg &optional inactive)
14839 "Prompt for a date/time and insert a time stamp.
14840 If the user specifies a time like HH:MM, or if this command is called
14841 with a prefix argument, the time stamp will contain date and time.
14842 Otherwise, only the date will be included. All parts of a date not
14843 specified by the user will be filled in from the current date/time.
14844 So if you press just return without typing anything, the time stamp
14845 will represent the current date/time. If there is already a timestamp
14846 at the cursor, it will be modified."
14847 (interactive "P")
14848 (let* ((ts nil)
14849 (default-time
14850 ;; Default time is either today, or, when entering a range,
14851 ;; the range start.
14852 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14853 (save-excursion
14854 (re-search-backward
14855 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14856 (- (point) 20) t)))
14857 (apply 'encode-time (org-parse-time-string (match-string 1)))
14858 (current-time)))
14859 (default-input (and ts (org-get-compact-tod ts)))
14860 (repeater (save-excursion
14861 (save-match-data
14862 (beginning-of-line)
14863 (when (re-search-forward
14864 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14865 (save-excursion (progn (end-of-line) (point))) t)
14866 (match-string 0)))))
14867 org-time-was-given org-end-time-was-given time)
14868 (cond
14869 ((and (org-at-timestamp-p t)
14870 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14871 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14872 (insert "--")
14873 (setq time (let ((this-command this-command))
14874 (org-read-date arg 'totime nil nil
14875 default-time default-input)))
14876 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14877 ((org-at-timestamp-p t)
14878 (setq time (let ((this-command this-command))
14879 (org-read-date arg 'totime nil nil default-time default-input)))
14880 (when (org-at-timestamp-p t) ; just to get the match data
14881 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14882 (replace-match "")
14883 (setq org-last-changed-timestamp
14884 (org-insert-time-stamp
14885 time (or org-time-was-given arg)
14886 inactive nil nil (list org-end-time-was-given)))
14887 (when repeater (goto-char (1- (point))) (insert " " repeater)
14888 (setq org-last-changed-timestamp
14889 (concat (substring org-last-inserted-timestamp 0 -1)
14890 " " repeater ">"))))
14891 (message "Timestamp updated"))
14893 (setq time (let ((this-command this-command))
14894 (org-read-date arg 'totime nil nil default-time default-input)))
14895 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14896 nil nil (list org-end-time-was-given))))))
14898 ;; FIXME: can we use this for something else, like computing time differences?
14899 (defun org-get-compact-tod (s)
14900 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14901 (let* ((t1 (match-string 1 s))
14902 (h1 (string-to-number (match-string 2 s)))
14903 (m1 (string-to-number (match-string 3 s)))
14904 (t2 (and (match-end 4) (match-string 5 s)))
14905 (h2 (and t2 (string-to-number (match-string 6 s))))
14906 (m2 (and t2 (string-to-number (match-string 7 s))))
14907 dh dm)
14908 (if (not t2)
14910 (setq dh (- h2 h1) dm (- m2 m1))
14911 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14912 (concat t1 "+" (number-to-string dh)
14913 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14915 (defun org-time-stamp-inactive (&optional arg)
14916 "Insert an inactive time stamp.
14917 An inactive time stamp is enclosed in square brackets instead of angle
14918 brackets. It is inactive in the sense that it does not trigger agenda entries,
14919 does not link to the calendar and cannot be changed with the S-cursor keys.
14920 So these are more for recording a certain time/date."
14921 (interactive "P")
14922 (org-time-stamp arg 'inactive))
14924 (defvar org-date-ovl (make-overlay 1 1))
14925 (overlay-put org-date-ovl 'face 'org-date-selected)
14926 (org-detach-overlay org-date-ovl)
14928 (defvar org-ans1) ; dynamically scoped parameter
14929 (defvar org-ans2) ; dynamically scoped parameter
14931 (defvar org-plain-time-of-day-regexp) ; defined below
14933 (defvar org-overriding-default-time nil) ; dynamically scoped
14934 (defvar org-read-date-overlay nil)
14935 (defvar org-dcst nil) ; dynamically scoped
14936 (defvar org-read-date-history nil)
14937 (defvar org-read-date-final-answer nil)
14938 (defvar org-read-date-analyze-futurep nil)
14939 (defvar org-read-date-analyze-forced-year nil)
14941 (defun org-read-date (&optional org-with-time to-time from-string prompt
14942 default-time default-input)
14943 "Read a date, possibly a time, and make things smooth for the user.
14944 The prompt will suggest to enter an ISO date, but you can also enter anything
14945 which will at least partially be understood by `parse-time-string'.
14946 Unrecognized parts of the date will default to the current day, month, year,
14947 hour and minute. If this command is called to replace a timestamp at point,
14948 or to enter the second timestamp of a range, the default time is taken
14949 from the existing stamp. Furthermore, the command prefers the future,
14950 so if you are giving a date where the year is not given, and the day-month
14951 combination is already past in the current year, it will assume you
14952 mean next year. For details, see the manual. A few examples:
14954 3-2-5 --> 2003-02-05
14955 feb 15 --> currentyear-02-15
14956 2/15 --> currentyear-02-15
14957 sep 12 9 --> 2009-09-12
14958 12:45 --> today 12:45
14959 22 sept 0:34 --> currentyear-09-22 0:34
14960 12 --> currentyear-currentmonth-12
14961 Fri --> nearest Friday (today or later)
14962 etc.
14964 Furthermore you can specify a relative date by giving, as the *first* thing
14965 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14966 change in days weeks, months, years.
14967 With a single plus or minus, the date is relative to today. With a double
14968 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14969 +4d --> four days from today
14970 +4 --> same as above
14971 +2w --> two weeks from today
14972 ++5 --> five days from default date
14974 The function understands only English month and weekday abbreviations.
14976 While prompting, a calendar is popped up - you can also select the
14977 date with the mouse (button 1). The calendar shows a period of three
14978 months. To scroll it to other months, use the keys `>' and `<'.
14979 If you don't like the calendar, turn it off with
14980 \(setq org-read-date-popup-calendar nil)
14982 With optional argument TO-TIME, the date will immediately be converted
14983 to an internal time.
14984 With an optional argument WITH-TIME, the prompt will suggest to also
14985 insert a time. Note that when WITH-TIME is not set, you can still
14986 enter a time, and this function will inform the calling routine about
14987 this change. The calling routine may then choose to change the format
14988 used to insert the time stamp into the buffer to include the time.
14989 With optional argument FROM-STRING, read from this string instead from
14990 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14991 the time/date that is used for everything that is not specified by the
14992 user."
14993 (require 'parse-time)
14994 (let* ((org-time-stamp-rounding-minutes
14995 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14996 (org-dcst org-display-custom-times)
14997 (ct (org-current-time))
14998 (org-def (or org-overriding-default-time default-time ct))
14999 (org-defdecode (decode-time org-def))
15000 (dummy (progn
15001 (when (< (nth 2 org-defdecode) org-extend-today-until)
15002 (setcar (nthcdr 2 org-defdecode) -1)
15003 (setcar (nthcdr 1 org-defdecode) 59)
15004 (setq org-def (apply 'encode-time org-defdecode)
15005 org-defdecode (decode-time org-def)))))
15006 (calendar-frame-setup nil)
15007 (calendar-setup nil)
15008 (calendar-move-hook nil)
15009 (calendar-view-diary-initially-flag nil)
15010 (calendar-view-holidays-initially-flag nil)
15011 (timestr (format-time-string
15012 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15013 (prompt (concat (if prompt (concat prompt " ") "")
15014 (format "Date+time [%s]: " timestr)))
15015 ans (org-ans0 "") org-ans1 org-ans2 final)
15017 (cond
15018 (from-string (setq ans from-string))
15019 (org-read-date-popup-calendar
15020 (save-excursion
15021 (save-window-excursion
15022 (calendar)
15023 (unwind-protect
15024 (progn
15025 (calendar-forward-day (- (time-to-days org-def)
15026 (calendar-absolute-from-gregorian
15027 (calendar-current-date))))
15028 (org-eval-in-calendar nil t)
15029 (let* ((old-map (current-local-map))
15030 (map (copy-keymap calendar-mode-map))
15031 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15032 (org-defkey map (kbd "RET") 'org-calendar-select)
15033 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15034 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15035 (org-defkey minibuffer-local-map [(meta shift left)]
15036 (lambda () (interactive)
15037 (org-eval-in-calendar '(calendar-backward-month 1))))
15038 (org-defkey minibuffer-local-map [(meta shift right)]
15039 (lambda () (interactive)
15040 (org-eval-in-calendar '(calendar-forward-month 1))))
15041 (org-defkey minibuffer-local-map [(meta shift up)]
15042 (lambda () (interactive)
15043 (org-eval-in-calendar '(calendar-backward-year 1))))
15044 (org-defkey minibuffer-local-map [(meta shift down)]
15045 (lambda () (interactive)
15046 (org-eval-in-calendar '(calendar-forward-year 1))))
15047 (org-defkey minibuffer-local-map [?\e (shift left)]
15048 (lambda () (interactive)
15049 (org-eval-in-calendar '(calendar-backward-month 1))))
15050 (org-defkey minibuffer-local-map [?\e (shift right)]
15051 (lambda () (interactive)
15052 (org-eval-in-calendar '(calendar-forward-month 1))))
15053 (org-defkey minibuffer-local-map [?\e (shift up)]
15054 (lambda () (interactive)
15055 (org-eval-in-calendar '(calendar-backward-year 1))))
15056 (org-defkey minibuffer-local-map [?\e (shift down)]
15057 (lambda () (interactive)
15058 (org-eval-in-calendar '(calendar-forward-year 1))))
15059 (org-defkey minibuffer-local-map [(shift up)]
15060 (lambda () (interactive)
15061 (org-eval-in-calendar '(calendar-backward-week 1))))
15062 (org-defkey minibuffer-local-map [(shift down)]
15063 (lambda () (interactive)
15064 (org-eval-in-calendar '(calendar-forward-week 1))))
15065 (org-defkey minibuffer-local-map [(shift left)]
15066 (lambda () (interactive)
15067 (org-eval-in-calendar '(calendar-backward-day 1))))
15068 (org-defkey minibuffer-local-map [(shift right)]
15069 (lambda () (interactive)
15070 (org-eval-in-calendar '(calendar-forward-day 1))))
15071 (org-defkey minibuffer-local-map ">"
15072 (lambda () (interactive)
15073 (org-eval-in-calendar '(scroll-calendar-left 1))))
15074 (org-defkey minibuffer-local-map "<"
15075 (lambda () (interactive)
15076 (org-eval-in-calendar '(scroll-calendar-right 1))))
15077 (org-defkey minibuffer-local-map "\C-v"
15078 (lambda () (interactive)
15079 (org-eval-in-calendar
15080 '(calendar-scroll-left-three-months 1))))
15081 (org-defkey minibuffer-local-map "\M-v"
15082 (lambda () (interactive)
15083 (org-eval-in-calendar
15084 '(calendar-scroll-right-three-months 1))))
15085 (run-hooks 'org-read-date-minibuffer-setup-hook)
15086 (unwind-protect
15087 (progn
15088 (use-local-map map)
15089 (add-hook 'post-command-hook 'org-read-date-display)
15090 (setq org-ans0 (read-string prompt default-input
15091 'org-read-date-history nil))
15092 ;; org-ans0: from prompt
15093 ;; org-ans1: from mouse click
15094 ;; org-ans2: from calendar motion
15095 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15096 (remove-hook 'post-command-hook 'org-read-date-display)
15097 (use-local-map old-map)
15098 (when org-read-date-overlay
15099 (delete-overlay org-read-date-overlay)
15100 (setq org-read-date-overlay nil)))))
15101 (bury-buffer "*Calendar*")))))
15103 (t ; Naked prompt only
15104 (unwind-protect
15105 (setq ans (read-string prompt default-input
15106 'org-read-date-history timestr))
15107 (when org-read-date-overlay
15108 (delete-overlay org-read-date-overlay)
15109 (setq org-read-date-overlay nil)))))
15111 (setq final (org-read-date-analyze ans org-def org-defdecode))
15113 (when org-read-date-analyze-forced-year
15114 (message "Year was forced into %s"
15115 (if org-read-date-force-compatible-dates
15116 "compatible range (1970-2037)"
15117 "range representable on this machine"))
15118 (ding))
15120 ;; One round trip to get rid of 34th of August and stuff like that....
15121 (setq final (decode-time (apply 'encode-time final)))
15123 (setq org-read-date-final-answer ans)
15125 (if to-time
15126 (apply 'encode-time final)
15127 (if (and (boundp 'org-time-was-given) org-time-was-given)
15128 (format "%04d-%02d-%02d %02d:%02d"
15129 (nth 5 final) (nth 4 final) (nth 3 final)
15130 (nth 2 final) (nth 1 final))
15131 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15133 (defvar org-def)
15134 (defvar org-defdecode)
15135 (defvar org-with-time)
15136 (defun org-read-date-display ()
15137 "Display the current date prompt interpretation in the minibuffer."
15138 (when org-read-date-display-live
15139 (when org-read-date-overlay
15140 (delete-overlay org-read-date-overlay))
15141 (when (minibufferp (current-buffer))
15142 (save-excursion
15143 (end-of-line 1)
15144 (while (not (equal (buffer-substring
15145 (max (point-min) (- (point) 4)) (point))
15146 " "))
15147 (insert " ")))
15148 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15149 " " (or org-ans1 org-ans2)))
15150 (org-end-time-was-given nil)
15151 (f (org-read-date-analyze ans org-def org-defdecode))
15152 (fmts (if org-dcst
15153 org-time-stamp-custom-formats
15154 org-time-stamp-formats))
15155 (fmt (if (or org-with-time
15156 (and (boundp 'org-time-was-given) org-time-was-given))
15157 (cdr fmts)
15158 (car fmts)))
15159 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15160 (when (and org-end-time-was-given
15161 (string-match org-plain-time-of-day-regexp txt))
15162 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15163 org-end-time-was-given
15164 (substring txt (match-end 0)))))
15165 (when org-read-date-analyze-futurep
15166 (setq txt (concat txt " (=>F)")))
15167 (setq org-read-date-overlay
15168 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15169 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15171 (defun org-read-date-analyze (ans org-def org-defdecode)
15172 "Analyze the combined answer of the date prompt."
15173 ;; FIXME: cleanup and comment
15174 (let ((nowdecode (decode-time (current-time)))
15175 delta deltan deltaw deltadef year month day
15176 hour minute second wday pm h2 m2 tl wday1
15177 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15178 (setq org-read-date-analyze-futurep nil
15179 org-read-date-analyze-forced-year nil)
15180 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15181 (setq ans "+0"))
15183 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15184 (setq ans (replace-match "" t t ans)
15185 deltan (car delta)
15186 deltaw (nth 1 delta)
15187 deltadef (nth 2 delta)))
15189 ;; Check if there is an iso week date in there
15190 ;; If yes, store the info and postpone interpreting it until the rest
15191 ;; of the parsing is done
15192 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15193 (setq iso-year (if (match-end 1)
15194 (org-small-year-to-year
15195 (string-to-number (match-string 1 ans))))
15196 iso-weekday (if (match-end 3)
15197 (string-to-number (match-string 3 ans)))
15198 iso-week (string-to-number (match-string 2 ans)))
15199 (setq ans (replace-match "" t t ans)))
15201 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15202 (when (string-match
15203 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15204 (setq year (if (match-end 2)
15205 (string-to-number (match-string 2 ans))
15206 (progn (setq kill-year t)
15207 (string-to-number (format-time-string "%Y"))))
15208 month (string-to-number (match-string 3 ans))
15209 day (string-to-number (match-string 4 ans)))
15210 (if (< year 100) (setq year (+ 2000 year)))
15211 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15212 t nil ans)))
15214 ;; Help matching dotted european dates
15215 (when (string-match
15216 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15217 (setq year (if (match-end 3)
15218 (string-to-number (match-string 3 ans))
15219 (progn (setq kill-year t)
15220 (string-to-number (format-time-string "%Y"))))
15221 day (string-to-number (match-string 1 ans))
15222 month (string-to-number (match-string 2 ans))
15223 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15224 t nil ans)))
15226 ;; Help matching american dates, like 5/30 or 5/30/7
15227 (when (string-match
15228 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15229 (setq year (if (match-end 4)
15230 (string-to-number (match-string 4 ans))
15231 (progn (setq kill-year t)
15232 (string-to-number (format-time-string "%Y"))))
15233 month (string-to-number (match-string 1 ans))
15234 day (string-to-number (match-string 2 ans)))
15235 (if (< year 100) (setq year (+ 2000 year)))
15236 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15237 t nil ans)))
15238 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15239 ;; If there is a time with am/pm, and *no* time without it, we convert
15240 ;; so that matching will be successful.
15241 (loop for i from 1 to 2 do ; twice, for end time as well
15242 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15243 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15244 (setq hour (string-to-number (match-string 1 ans))
15245 minute (if (match-end 3)
15246 (string-to-number (match-string 3 ans))
15248 pm (equal ?p
15249 (string-to-char (downcase (match-string 4 ans)))))
15250 (if (and (= hour 12) (not pm))
15251 (setq hour 0)
15252 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15253 (setq ans (replace-match (format "%02d:%02d" hour minute)
15254 t t ans))))
15256 ;; Check if a time range is given as a duration
15257 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15258 (setq hour (string-to-number (match-string 1 ans))
15259 h2 (+ hour (string-to-number (match-string 3 ans)))
15260 minute (string-to-number (match-string 2 ans))
15261 m2 (+ minute (if (match-end 5) (string-to-number
15262 (match-string 5 ans))0)))
15263 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15264 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15265 t t ans)))
15267 ;; Check if there is a time range
15268 (when (boundp 'org-end-time-was-given)
15269 (setq org-time-was-given nil)
15270 (when (and (string-match org-plain-time-of-day-regexp ans)
15271 (match-end 8))
15272 (setq org-end-time-was-given (match-string 8 ans))
15273 (setq ans (concat (substring ans 0 (match-beginning 7))
15274 (substring ans (match-end 7))))))
15276 (setq tl (parse-time-string ans)
15277 day (or (nth 3 tl) (nth 3 org-defdecode))
15278 month (or (nth 4 tl)
15279 (if (and org-read-date-prefer-future
15280 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15281 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15282 (nth 4 org-defdecode)))
15283 year (or (and (not kill-year) (nth 5 tl))
15284 (if (and org-read-date-prefer-future
15285 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15286 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15287 (nth 5 org-defdecode)))
15288 hour (or (nth 2 tl) (nth 2 org-defdecode))
15289 minute (or (nth 1 tl) (nth 1 org-defdecode))
15290 second (or (nth 0 tl) 0)
15291 wday (nth 6 tl))
15293 (when (and (eq org-read-date-prefer-future 'time)
15294 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15295 (equal day (nth 3 nowdecode))
15296 (equal month (nth 4 nowdecode))
15297 (equal year (nth 5 nowdecode))
15298 (nth 2 tl)
15299 (or (< (nth 2 tl) (nth 2 nowdecode))
15300 (and (= (nth 2 tl) (nth 2 nowdecode))
15301 (nth 1 tl)
15302 (< (nth 1 tl) (nth 1 nowdecode)))))
15303 (setq day (1+ day)
15304 futurep t))
15306 ;; Special date definitions below
15307 (cond
15308 (iso-week
15309 ;; There was an iso week
15310 (require 'cal-iso)
15311 (setq futurep nil)
15312 (setq year (or iso-year year)
15313 day (or iso-weekday wday 1)
15314 wday nil ; to make sure that the trigger below does not match
15315 iso-date (calendar-gregorian-from-absolute
15316 (calendar-absolute-from-iso
15317 (list iso-week day year))))
15318 ; FIXME: Should we also push ISO weeks into the future?
15319 ; (when (and org-read-date-prefer-future
15320 ; (not iso-year)
15321 ; (< (calendar-absolute-from-gregorian iso-date)
15322 ; (time-to-days (current-time))))
15323 ; (setq year (1+ year)
15324 ; iso-date (calendar-gregorian-from-absolute
15325 ; (calendar-absolute-from-iso
15326 ; (list iso-week day year)))))
15327 (setq month (car iso-date)
15328 year (nth 2 iso-date)
15329 day (nth 1 iso-date)))
15330 (deltan
15331 (setq futurep nil)
15332 (unless deltadef
15333 (let ((now (decode-time (current-time))))
15334 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15335 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15336 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15337 ((equal deltaw "m") (setq month (+ month deltan)))
15338 ((equal deltaw "y") (setq year (+ year deltan)))))
15339 ((and wday (not (nth 3 tl)))
15340 (setq futurep nil)
15341 ;; Weekday was given, but no day, so pick that day in the week
15342 ;; on or after the derived date.
15343 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15344 (unless (equal wday wday1)
15345 (setq day (+ day (% (- wday wday1 -7) 7))))))
15346 (if (and (boundp 'org-time-was-given)
15347 (nth 2 tl))
15348 (setq org-time-was-given t))
15349 (if (< year 100) (setq year (+ 2000 year)))
15350 ;; Check of the date is representable
15351 (if org-read-date-force-compatible-dates
15352 (progn
15353 (if (< year 1970)
15354 (setq year 1970 org-read-date-analyze-forced-year t))
15355 (if (> year 2037)
15356 (setq year 2037 org-read-date-analyze-forced-year t)))
15357 (condition-case nil
15358 (ignore (encode-time second minute hour day month year))
15359 (error
15360 (setq year (nth 5 org-defdecode))
15361 (setq org-read-date-analyze-forced-year t))))
15362 (setq org-read-date-analyze-futurep futurep)
15363 (list second minute hour day month year)))
15365 (defvar parse-time-weekdays)
15366 (defun org-read-date-get-relative (s today default)
15367 "Check string S for special relative date string.
15368 TODAY and DEFAULT are internal times, for today and for a default.
15369 Return shift list (N what def-flag)
15370 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15371 N is the number of WHATs to shift.
15372 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15373 the DEFAULT date rather than TODAY."
15374 (require 'parse-time)
15375 (when (and
15376 (string-match
15377 (concat
15378 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15379 "\\([0-9]+\\)?"
15380 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15381 "\\([ \t]\\|$\\)") s)
15382 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15383 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15384 (string-to-char (substring (match-string 1 s) -1))
15385 ?+))
15386 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15387 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15388 (what (if (match-end 3) (match-string 3 s) "d"))
15389 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15390 (date (if rel default today))
15391 (wday (nth 6 (decode-time date)))
15392 delta)
15393 (if wday1
15394 (progn
15395 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15396 (if (= dir ?-) (setq delta (- delta 7)))
15397 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15398 (list delta "d" rel))
15399 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15401 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15402 "Turn a user-specified date into the internal representation.
15403 The internal representation needed by the calendar is (month day year).
15404 This is a wrapper to handle the brain-dead convention in calendar that
15405 user function argument order change dependent on argument order."
15406 (if (boundp 'calendar-date-style)
15407 (cond
15408 ((eq calendar-date-style 'american)
15409 (list arg1 arg2 arg3))
15410 ((eq calendar-date-style 'european)
15411 (list arg2 arg1 arg3))
15412 ((eq calendar-date-style 'iso)
15413 (list arg2 arg3 arg1)))
15414 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15415 (if (org-bound-and-true-p european-calendar-style)
15416 (list arg2 arg1 arg3)
15417 (list arg1 arg2 arg3)))))
15419 (defun org-eval-in-calendar (form &optional keepdate)
15420 "Eval FORM in the calendar window and return to current window.
15421 Also, store the cursor date in variable org-ans2."
15422 (let ((sf (selected-frame))
15423 (sw (selected-window)))
15424 (select-window (get-buffer-window "*Calendar*" t))
15425 (eval form)
15426 (when (and (not keepdate) (calendar-cursor-to-date))
15427 (let* ((date (calendar-cursor-to-date))
15428 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15429 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15430 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15431 (select-window sw)
15432 (org-select-frame-set-input-focus sf)))
15434 (defun org-calendar-select ()
15435 "Return to `org-read-date' with the date currently selected.
15436 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15437 (interactive)
15438 (when (calendar-cursor-to-date)
15439 (let* ((date (calendar-cursor-to-date))
15440 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15441 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15442 (if (active-minibuffer-window) (exit-minibuffer))))
15444 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15445 "Insert a date stamp for the date given by the internal TIME.
15446 WITH-HM means use the stamp format that includes the time of the day.
15447 INACTIVE means use square brackets instead of angular ones, so that the
15448 stamp will not contribute to the agenda.
15449 PRE and POST are optional strings to be inserted before and after the
15450 stamp.
15451 The command returns the inserted time stamp."
15452 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15453 stamp)
15454 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15455 (insert-before-markers (or pre ""))
15456 (when (listp extra)
15457 (setq extra (car extra))
15458 (if (and (stringp extra)
15459 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15460 (setq extra (format "-%02d:%02d"
15461 (string-to-number (match-string 1 extra))
15462 (string-to-number (match-string 2 extra))))
15463 (setq extra nil)))
15464 (when extra
15465 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15466 (insert-before-markers (setq stamp (format-time-string fmt time)))
15467 (insert-before-markers (or post ""))
15468 (setq org-last-inserted-timestamp stamp)))
15470 (defun org-toggle-time-stamp-overlays ()
15471 "Toggle the use of custom time stamp formats."
15472 (interactive)
15473 (setq org-display-custom-times (not org-display-custom-times))
15474 (unless org-display-custom-times
15475 (let ((p (point-min)) (bmp (buffer-modified-p)))
15476 (while (setq p (next-single-property-change p 'display))
15477 (if (and (get-text-property p 'display)
15478 (eq (get-text-property p 'face) 'org-date))
15479 (remove-text-properties
15480 p (setq p (next-single-property-change p 'display))
15481 '(display t))))
15482 (set-buffer-modified-p bmp)))
15483 (if (featurep 'xemacs)
15484 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15485 (org-restart-font-lock)
15486 (setq org-table-may-need-update t)
15487 (if org-display-custom-times
15488 (message "Time stamps are overlaid with custom format")
15489 (message "Time stamp overlays removed")))
15491 (defun org-display-custom-time (beg end)
15492 "Overlay modified time stamp format over timestamp between BEG and END."
15493 (let* ((ts (buffer-substring beg end))
15494 t1 w1 with-hm tf time str w2 (off 0))
15495 (save-match-data
15496 (setq t1 (org-parse-time-string ts t))
15497 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15498 (setq off (- (match-end 0) (match-beginning 0)))))
15499 (setq end (- end off))
15500 (setq w1 (- end beg)
15501 with-hm (and (nth 1 t1) (nth 2 t1))
15502 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15503 time (org-fix-decoded-time t1)
15504 str (org-add-props
15505 (format-time-string
15506 (substring tf 1 -1) (apply 'encode-time time))
15507 nil 'mouse-face 'highlight)
15508 w2 (length str))
15509 (if (not (= w2 w1))
15510 (add-text-properties (1+ beg) (+ 2 beg)
15511 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15512 (if (featurep 'xemacs)
15513 (progn
15514 (put-text-property beg end 'invisible t)
15515 (put-text-property beg end 'end-glyph (make-glyph str)))
15516 (put-text-property beg end 'display str))))
15518 (defun org-translate-time (string)
15519 "Translate all timestamps in STRING to custom format.
15520 But do this only if the variable `org-display-custom-times' is set."
15521 (when org-display-custom-times
15522 (save-match-data
15523 (let* ((start 0)
15524 (re org-ts-regexp-both)
15525 t1 with-hm inactive tf time str beg end)
15526 (while (setq start (string-match re string start))
15527 (setq beg (match-beginning 0)
15528 end (match-end 0)
15529 t1 (save-match-data
15530 (org-parse-time-string (substring string beg end) t))
15531 with-hm (and (nth 1 t1) (nth 2 t1))
15532 inactive (equal (substring string beg (1+ beg)) "[")
15533 tf (funcall (if with-hm 'cdr 'car)
15534 org-time-stamp-custom-formats)
15535 time (org-fix-decoded-time t1)
15536 str (format-time-string
15537 (concat
15538 (if inactive "[" "<") (substring tf 1 -1)
15539 (if inactive "]" ">"))
15540 (apply 'encode-time time))
15541 string (replace-match str t t string)
15542 start (+ start (length str)))))))
15543 string)
15545 (defun org-fix-decoded-time (time)
15546 "Set 0 instead of nil for the first 6 elements of time.
15547 Don't touch the rest."
15548 (let ((n 0))
15549 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15551 (defun org-days-to-time (timestamp-string)
15552 "Difference between TIMESTAMP-STRING and now in days."
15553 (- (time-to-days (org-time-string-to-time timestamp-string))
15554 (time-to-days (current-time))))
15556 (defun org-deadline-close (timestamp-string &optional ndays)
15557 "Is the time in TIMESTAMP-STRING close to the current date?"
15558 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15559 (and (< (org-days-to-time timestamp-string) ndays)
15560 (not (org-entry-is-done-p))))
15562 (defun org-get-wdays (ts)
15563 "Get the deadline lead time appropriate for timestring TS."
15564 (cond
15565 ((<= org-deadline-warning-days 0)
15566 ;; 0 or negative, enforce this value no matter what
15567 (- org-deadline-warning-days))
15568 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15569 ;; lead time is specified.
15570 (floor (* (string-to-number (match-string 1 ts))
15571 (cdr (assoc (match-string 2 ts)
15572 '(("d" . 1) ("w" . 7)
15573 ("m" . 30.4) ("y" . 365.25)))))))
15574 ;; go for the default.
15575 (t org-deadline-warning-days)))
15577 (defun org-calendar-select-mouse (ev)
15578 "Return to `org-read-date' with the date currently selected.
15579 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15580 (interactive "e")
15581 (mouse-set-point ev)
15582 (when (calendar-cursor-to-date)
15583 (let* ((date (calendar-cursor-to-date))
15584 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15585 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15586 (if (active-minibuffer-window) (exit-minibuffer))))
15588 (defun org-check-deadlines (ndays)
15589 "Check if there are any deadlines due or past due.
15590 A deadline is considered due if it happens within `org-deadline-warning-days'
15591 days from today's date. If the deadline appears in an entry marked DONE,
15592 it is not shown. The prefix arg NDAYS can be used to test that many
15593 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15594 (interactive "P")
15595 (let* ((org-warn-days
15596 (cond
15597 ((equal ndays '(4)) 100000)
15598 (ndays (prefix-numeric-value ndays))
15599 (t (abs org-deadline-warning-days))))
15600 (case-fold-search nil)
15601 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15602 (callback
15603 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15605 (message "%d deadlines past-due or due within %d days"
15606 (org-occur regexp nil callback)
15607 org-warn-days)))
15609 (defun org-check-before-date (date)
15610 "Check if there are deadlines or scheduled entries before DATE."
15611 (interactive (list (org-read-date)))
15612 (let ((case-fold-search nil)
15613 (regexp (concat "\\<\\(" org-deadline-string
15614 "\\|" org-scheduled-string
15615 "\\) *<\\([^>]+\\)>"))
15616 (callback
15617 (lambda () (time-less-p
15618 (org-time-string-to-time (match-string 2))
15619 (org-time-string-to-time date)))))
15620 (message "%d entries before %s"
15621 (org-occur regexp nil callback) date)))
15623 (defun org-check-after-date (date)
15624 "Check if there are deadlines or scheduled entries after DATE."
15625 (interactive (list (org-read-date)))
15626 (let ((case-fold-search nil)
15627 (regexp (concat "\\<\\(" org-deadline-string
15628 "\\|" org-scheduled-string
15629 "\\) *<\\([^>]+\\)>"))
15630 (callback
15631 (lambda () (not
15632 (time-less-p
15633 (org-time-string-to-time (match-string 2))
15634 (org-time-string-to-time date))))))
15635 (message "%d entries after %s"
15636 (org-occur regexp nil callback) date)))
15638 (defun org-check-dates-range (start-date end-date)
15639 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15640 (interactive (list (org-read-date nil nil nil "Range starts")
15641 (org-read-date nil nil nil "Range end")))
15642 (let ((case-fold-search nil)
15643 (regexp (concat "\\<\\(" org-deadline-string
15644 "\\|" org-scheduled-string
15645 "\\) *<\\([^>]+\\)>"))
15646 (callback
15647 (lambda ()
15648 (let ((match (match-string 2)))
15649 (and
15650 (not (time-less-p
15651 (org-time-string-to-time match)
15652 (org-time-string-to-time start-date)))
15653 (time-less-p
15654 (org-time-string-to-time match)
15655 (org-time-string-to-time end-date)))))))
15656 (message "%d entries between %s and %s"
15657 (org-occur regexp nil callback) start-date end-date)))
15659 (defun org-evaluate-time-range (&optional to-buffer)
15660 "Evaluate a time range by computing the difference between start and end.
15661 Normally the result is just printed in the echo area, but with prefix arg
15662 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15663 If the time range is actually in a table, the result is inserted into the
15664 next column.
15665 For time difference computation, a year is assumed to be exactly 365
15666 days in order to avoid rounding problems."
15667 (interactive "P")
15669 (org-clock-update-time-maybe)
15670 (save-excursion
15671 (unless (org-at-date-range-p t)
15672 (goto-char (point-at-bol))
15673 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15674 (if (not (org-at-date-range-p t))
15675 (error "Not at a time-stamp range, and none found in current line")))
15676 (let* ((ts1 (match-string 1))
15677 (ts2 (match-string 2))
15678 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15679 (match-end (match-end 0))
15680 (time1 (org-time-string-to-time ts1))
15681 (time2 (org-time-string-to-time ts2))
15682 (t1 (org-float-time time1))
15683 (t2 (org-float-time time2))
15684 (diff (abs (- t2 t1)))
15685 (negative (< (- t2 t1) 0))
15686 ;; (ys (floor (* 365 24 60 60)))
15687 (ds (* 24 60 60))
15688 (hs (* 60 60))
15689 (fy "%dy %dd %02d:%02d")
15690 (fy1 "%dy %dd")
15691 (fd "%dd %02d:%02d")
15692 (fd1 "%dd")
15693 (fh "%02d:%02d")
15694 y d h m align)
15695 (if havetime
15696 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15698 d (floor (/ diff ds)) diff (mod diff ds)
15699 h (floor (/ diff hs)) diff (mod diff hs)
15700 m (floor (/ diff 60)))
15701 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15703 d (floor (+ (/ diff ds) 0.5))
15704 h 0 m 0))
15705 (if (not to-buffer)
15706 (message "%s" (org-make-tdiff-string y d h m))
15707 (if (org-at-table-p)
15708 (progn
15709 (goto-char match-end)
15710 (setq align t)
15711 (and (looking-at " *|") (goto-char (match-end 0))))
15712 (goto-char match-end))
15713 (if (looking-at
15714 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15715 (replace-match ""))
15716 (if negative (insert " -"))
15717 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15718 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15719 (insert " " (format fh h m))))
15720 (if align (org-table-align))
15721 (message "Time difference inserted")))))
15723 (defun org-make-tdiff-string (y d h m)
15724 (let ((fmt "")
15725 (l nil))
15726 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15727 l (push y l)))
15728 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15729 l (push d l)))
15730 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15731 l (push h l)))
15732 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15733 l (push m l)))
15734 (apply 'format fmt (nreverse l))))
15736 (defun org-time-string-to-time (s &optional buffer pos)
15737 (condition-case errdata
15738 (apply 'encode-time (org-parse-time-string s))
15739 (error (error "Bad timestamp `%s'%s\nError was: %s"
15740 s (if (not (and buffer pos))
15742 (format " at %d in buffer `%s'" pos buffer))
15743 (cdr errdata)))))
15745 (defun org-time-string-to-seconds (s)
15746 (org-float-time (org-time-string-to-time s)))
15748 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15749 "Convert a time stamp to an absolute day number.
15750 If there is a specifier for a cyclic time stamp, get the closest date to
15751 DAYNR.
15752 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15753 The variable date is bound by the calendar when this is called."
15754 (cond
15755 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15756 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15757 daynr
15758 (+ daynr 1000)))
15759 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15760 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15761 (time-to-days (current-time))) (match-string 0 s)
15762 prefer show-all))
15763 (t (time-to-days
15764 (condition-case errdata
15765 (apply 'encode-time (org-parse-time-string s))
15766 (error (error "Bad timestamp `%s'%s\nError was: %s"
15767 s (if (not (and buffer pos))
15769 (format " at %d in buffer `%s'" pos buffer))
15770 (cdr errdata))))))))
15772 (defun org-days-to-iso-week (days)
15773 "Return the iso week number."
15774 (require 'cal-iso)
15775 (car (calendar-iso-from-absolute days)))
15777 (defun org-small-year-to-year (year)
15778 "Convert 2-digit years into 4-digit years.
15779 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15780 The year 2000 cannot be abbreviated. Any year larger than 99
15781 is returned unchanged."
15782 (if (< year 38)
15783 (setq year (+ 2000 year))
15784 (if (< year 100)
15785 (setq year (+ 1900 year))))
15786 year)
15788 (defun org-time-from-absolute (d)
15789 "Return the time corresponding to date D.
15790 D may be an absolute day number, or a calendar-type list (month day year)."
15791 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15792 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15794 (defun org-calendar-holiday ()
15795 "List of holidays, for Diary display in Org-mode."
15796 (require 'holidays)
15797 (let ((hl (funcall
15798 (if (fboundp 'calendar-check-holidays)
15799 'calendar-check-holidays 'check-calendar-holidays) date)))
15800 (if hl (mapconcat 'identity hl "; "))))
15802 (defun org-diary-sexp-entry (sexp entry date)
15803 "Process a SEXP diary ENTRY for DATE."
15804 (require 'diary-lib)
15805 (let ((result (if calendar-debug-sexp
15806 (let ((stack-trace-on-error t))
15807 (eval (car (read-from-string sexp))))
15808 (condition-case nil
15809 (eval (car (read-from-string sexp)))
15810 (error
15811 (beep)
15812 (message "Bad sexp at line %d in %s: %s"
15813 (org-current-line)
15814 (buffer-file-name) sexp)
15815 (sleep-for 2))))))
15816 (cond ((stringp result) (split-string result "; "))
15817 ((and (consp result)
15818 (not (consp (cdr result)))
15819 (stringp (cdr result))) (cdr result))
15820 ((and (consp result)
15821 (stringp (car result))) result)
15822 (result entry)
15823 (t nil))))
15825 (defun org-diary-to-ical-string (frombuf)
15826 "Get iCalendar entries from diary entries in buffer FROMBUF.
15827 This uses the icalendar.el library."
15828 (let* ((tmpdir (if (featurep 'xemacs)
15829 (temp-directory)
15830 temporary-file-directory))
15831 (tmpfile (make-temp-name
15832 (expand-file-name "orgics" tmpdir)))
15833 buf rtn b e)
15834 (with-current-buffer frombuf
15835 (icalendar-export-region (point-min) (point-max) tmpfile)
15836 (setq buf (find-buffer-visiting tmpfile))
15837 (set-buffer buf)
15838 (goto-char (point-min))
15839 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15840 (setq b (match-beginning 0)))
15841 (goto-char (point-max))
15842 (if (re-search-backward "^END:VEVENT" nil t)
15843 (setq e (match-end 0)))
15844 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15845 (kill-buffer buf)
15846 (delete-file tmpfile)
15847 rtn))
15849 (defun org-closest-date (start current change prefer show-all)
15850 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15851 When PREFER is `past', return a date that is either CURRENT or past.
15852 When PREFER is `future', return a date that is either CURRENT or future.
15853 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15854 ;; Make the proper lists from the dates
15855 (catch 'exit
15856 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15857 dn dw sday cday n1 n2 n0
15858 d m y y1 y2 date1 date2 nmonths nm ny m2)
15860 (setq start (org-date-to-gregorian start)
15861 current (org-date-to-gregorian
15862 (if show-all
15863 current
15864 (time-to-days (current-time))))
15865 sday (calendar-absolute-from-gregorian start)
15866 cday (calendar-absolute-from-gregorian current))
15868 (if (<= cday sday) (throw 'exit sday))
15870 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15871 (setq dn (string-to-number (match-string 1 change))
15872 dw (cdr (assoc (match-string 2 change) a1)))
15873 (error "Invalid change specifier: %s" change))
15874 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15875 (cond
15876 ((eq dw 'day)
15877 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15878 n2 (+ n1 dn)))
15879 ((eq dw 'year)
15880 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15881 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15882 (setq date1 (list m d y1)
15883 n1 (calendar-absolute-from-gregorian date1)
15884 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15885 n2 (calendar-absolute-from-gregorian date2)))
15886 ((eq dw 'month)
15887 ;; approx number of month between the two dates
15888 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15889 ;; How often does dn fit in there?
15890 (setq d (nth 1 start) m (car start) y (nth 2 start)
15891 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15892 m (+ m nm)
15893 ny (floor (/ m 12))
15894 y (+ y ny)
15895 m (- m (* ny 12)))
15896 (while (> m 12) (setq m (- m 12) y (1+ y)))
15897 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15898 (setq m2 (+ m dn) y2 y)
15899 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15900 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15901 (while (<= n2 cday)
15902 (setq n1 n2 m m2 y y2)
15903 (setq m2 (+ m dn) y2 y)
15904 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15905 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15906 ;; Make sure n1 is the earlier date
15907 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15908 (if show-all
15909 (cond
15910 ((eq prefer 'past) (if (= cday n2) n2 n1))
15911 ((eq prefer 'future) (if (= cday n1) n1 n2))
15912 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15913 (cond
15914 ((eq prefer 'past) (if (= cday n2) n2 n1))
15915 ((eq prefer 'future) (if (= cday n1) n1 n2))
15916 (t (if (= cday n1) n1 n2)))))))
15918 (defun org-date-to-gregorian (date)
15919 "Turn any specification of DATE into a Gregorian date for the calendar."
15920 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15921 ((and (listp date) (= (length date) 3)) date)
15922 ((stringp date)
15923 (setq date (org-parse-time-string date))
15924 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15925 ((listp date)
15926 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15928 (defun org-parse-time-string (s &optional nodefault)
15929 "Parse the standard Org-mode time string.
15930 This should be a lot faster than the normal `parse-time-string'.
15931 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15932 hour and minute fields will be nil if not given."
15933 (if (string-match org-ts-regexp0 s)
15934 (list 0
15935 (if (or (match-beginning 8) (not nodefault))
15936 (string-to-number (or (match-string 8 s) "0")))
15937 (if (or (match-beginning 7) (not nodefault))
15938 (string-to-number (or (match-string 7 s) "0")))
15939 (string-to-number (match-string 4 s))
15940 (string-to-number (match-string 3 s))
15941 (string-to-number (match-string 2 s))
15942 nil nil nil)
15943 (error "Not a standard Org-mode time string: %s" s)))
15945 (defun org-timestamp-up (&optional arg)
15946 "Increase the date item at the cursor by one.
15947 If the cursor is on the year, change the year. If it is on the month,
15948 the day or the time, change that.
15949 With prefix ARG, change by that many units."
15950 (interactive "p")
15951 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15953 (defun org-timestamp-down (&optional arg)
15954 "Decrease the date item at the cursor by one.
15955 If the cursor is on the year, change the year. If it is on the month,
15956 the day or the time, change that.
15957 With prefix ARG, change by that many units."
15958 (interactive "p")
15959 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15961 (defun org-timestamp-up-day (&optional arg)
15962 "Increase the date in the time stamp by one day.
15963 With prefix ARG, change that many days."
15964 (interactive "p")
15965 (if (and (not (org-at-timestamp-p t))
15966 (org-at-heading-p))
15967 (org-todo 'up)
15968 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15970 (defun org-timestamp-down-day (&optional arg)
15971 "Decrease the date in the time stamp by one day.
15972 With prefix ARG, change that many days."
15973 (interactive "p")
15974 (if (and (not (org-at-timestamp-p t))
15975 (org-at-heading-p))
15976 (org-todo 'down)
15977 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15979 (defun org-at-timestamp-p (&optional inactive-ok)
15980 "Determine if the cursor is in or at a timestamp."
15981 (interactive)
15982 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15983 (pos (point))
15984 (ans (or (looking-at tsr)
15985 (save-excursion
15986 (skip-chars-backward "^[<\n\r\t")
15987 (if (> (point) (point-min)) (backward-char 1))
15988 (and (looking-at tsr)
15989 (> (- (match-end 0) pos) -1))))))
15990 (and ans
15991 (boundp 'org-ts-what)
15992 (setq org-ts-what
15993 (cond
15994 ((= pos (match-beginning 0)) 'bracket)
15995 ;; Point is considered to be "on the bracket" whether
15996 ;; it's really on it or right after it.
15997 ((or (= pos (1- (match-end 0)))
15998 (= pos (match-end 0))) 'bracket)
15999 ((org-pos-in-match-range pos 2) 'year)
16000 ((org-pos-in-match-range pos 3) 'month)
16001 ((org-pos-in-match-range pos 7) 'hour)
16002 ((org-pos-in-match-range pos 8) 'minute)
16003 ((or (org-pos-in-match-range pos 4)
16004 (org-pos-in-match-range pos 5)) 'day)
16005 ((and (> pos (or (match-end 8) (match-end 5)))
16006 (< pos (match-end 0)))
16007 (- pos (or (match-end 8) (match-end 5))))
16008 (t 'day))))
16009 ans))
16011 (defun org-toggle-timestamp-type ()
16012 "Toggle the type (<active> or [inactive]) of a time stamp."
16013 (interactive)
16014 (when (org-at-timestamp-p t)
16015 (let ((beg (match-beginning 0)) (end (match-end 0))
16016 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16017 (save-excursion
16018 (goto-char beg)
16019 (while (re-search-forward "[][<>]" end t)
16020 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16021 t t)))
16022 (message "Timestamp is now %sactive"
16023 (if (equal (char-after beg) ?<) "" "in")))))
16025 (defun org-timestamp-change (n &optional what updown)
16026 "Change the date in the time stamp at point.
16027 The date will be changed by N times WHAT. WHAT can be `day', `month',
16028 `year', `minute', `second'. If WHAT is not given, the cursor position
16029 in the timestamp determines what will be changed."
16030 (let ((origin (point)) origin-cat
16031 with-hm inactive
16032 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16033 org-ts-what
16034 extra rem
16035 ts time time0)
16036 (if (not (org-at-timestamp-p t))
16037 (error "Not at a timestamp"))
16038 (if (and (not what) (eq org-ts-what 'bracket))
16039 (org-toggle-timestamp-type)
16040 ;; Point isn't on brackets. Remember the part of the time-stamp
16041 ;; the point was in. Indeed, size of time-stamps may change,
16042 ;; but point must be kept in the same category nonetheless.
16043 (setq origin-cat org-ts-what)
16044 (if (and (not what) (not (eq org-ts-what 'day))
16045 org-display-custom-times
16046 (get-text-property (point) 'display)
16047 (not (get-text-property (1- (point)) 'display)))
16048 (setq org-ts-what 'day))
16049 (setq org-ts-what (or what org-ts-what)
16050 inactive (= (char-after (match-beginning 0)) ?\[)
16051 ts (match-string 0))
16052 (replace-match "")
16053 (if (string-match
16054 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16056 (setq extra (match-string 1 ts)))
16057 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16058 (setq with-hm t))
16059 (setq time0 (org-parse-time-string ts))
16060 (when (and updown
16061 (eq org-ts-what 'minute)
16062 (not current-prefix-arg))
16063 ;; This looks like s-up and s-down. Change by one rounding step.
16064 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16065 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16066 (setcar (cdr time0) (+ (nth 1 time0)
16067 (if (> n 0) (- rem) (- dm rem))))))
16068 (setq time
16069 (encode-time (or (car time0) 0)
16070 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16071 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16072 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16073 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16074 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16075 (nthcdr 6 time0)))
16076 (when (and (member org-ts-what '(hour minute))
16077 extra
16078 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16079 (setq extra (org-modify-ts-extra
16080 extra
16081 (if (eq org-ts-what 'hour) 2 5)
16082 n dm)))
16083 (when (integerp org-ts-what)
16084 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16085 (if (eq what 'calendar)
16086 (let ((cal-date (org-get-date-from-calendar)))
16087 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16088 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16089 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16090 (setcar time0 (or (car time0) 0))
16091 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16092 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16093 (setq time (apply 'encode-time time0))))
16094 ;; Insert the new time-stamp, and ensure point stays in the same
16095 ;; category as before (i.e. not after the last position in that
16096 ;; category).
16097 (let ((pos (point)))
16098 ;; Stay before inserted string. `save-excursion' is of no use.
16099 (setq org-last-changed-timestamp
16100 (org-insert-time-stamp time with-hm inactive nil nil extra))
16101 (goto-char pos))
16102 (save-match-data
16103 (looking-at org-ts-regexp3)
16104 (goto-char (cond
16105 ;; `day' category ends before `hour' if any, or at
16106 ;; the end of the day name.
16107 ((eq origin-cat 'day)
16108 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16109 ((eq origin-cat 'hour) (min (match-end 7) origin))
16110 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16111 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16112 ;; `year' and `month' have both fixed size: point
16113 ;; couldn't have moved into another part.
16114 (t origin))))
16115 ;; Update clock if on a CLOCK line.
16116 (org-clock-update-time-maybe)
16117 ;; Try to recenter the calendar window, if any.
16118 (if (and org-calendar-follow-timestamp-change
16119 (get-buffer-window "*Calendar*" t)
16120 (memq org-ts-what '(day month year)))
16121 (org-recenter-calendar (time-to-days time))))))
16123 (defun org-modify-ts-extra (s pos n dm)
16124 "Change the different parts of the lead-time and repeat fields in timestamp."
16125 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16126 ng h m new rem)
16127 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16128 (cond
16129 ((or (org-pos-in-match-range pos 2)
16130 (org-pos-in-match-range pos 3))
16131 (setq m (string-to-number (match-string 3 s))
16132 h (string-to-number (match-string 2 s)))
16133 (if (org-pos-in-match-range pos 2)
16134 (setq h (+ h n))
16135 (setq n (* dm (org-no-warnings (signum n))))
16136 (when (not (= 0 (setq rem (% m dm))))
16137 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16138 (setq m (+ m n)))
16139 (if (< m 0) (setq m (+ m 60) h (1- h)))
16140 (if (> m 59) (setq m (- m 60) h (1+ h)))
16141 (setq h (min 24 (max 0 h)))
16142 (setq ng 1 new (format "-%02d:%02d" h m)))
16143 ((org-pos-in-match-range pos 6)
16144 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16145 ((org-pos-in-match-range pos 5)
16146 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16148 ((org-pos-in-match-range pos 9)
16149 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16150 ((org-pos-in-match-range pos 8)
16151 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16153 (when ng
16154 (setq s (concat
16155 (substring s 0 (match-beginning ng))
16157 (substring s (match-end ng))))))
16160 (defun org-recenter-calendar (date)
16161 "If the calendar is visible, recenter it to DATE."
16162 (let ((cwin (get-buffer-window "*Calendar*" t)))
16163 (when cwin
16164 (let ((calendar-move-hook nil))
16165 (with-selected-window cwin
16166 (calendar-goto-date (if (listp date) date
16167 (calendar-gregorian-from-absolute date))))))))
16169 (defun org-goto-calendar (&optional arg)
16170 "Go to the Emacs calendar at the current date.
16171 If there is a time stamp in the current line, go to that date.
16172 A prefix ARG can be used to force the current date."
16173 (interactive "P")
16174 (let ((tsr org-ts-regexp) diff
16175 (calendar-move-hook nil)
16176 (calendar-view-holidays-initially-flag nil)
16177 (calendar-view-diary-initially-flag nil))
16178 (if (or (org-at-timestamp-p)
16179 (save-excursion
16180 (beginning-of-line 1)
16181 (looking-at (concat ".*" tsr))))
16182 (let ((d1 (time-to-days (current-time)))
16183 (d2 (time-to-days
16184 (org-time-string-to-time (match-string 1)))))
16185 (setq diff (- d2 d1))))
16186 (calendar)
16187 (calendar-goto-today)
16188 (if (and diff (not arg)) (calendar-forward-day diff))))
16190 (defun org-get-date-from-calendar ()
16191 "Return a list (month day year) of date at point in calendar."
16192 (with-current-buffer "*Calendar*"
16193 (save-match-data
16194 (calendar-cursor-to-date))))
16196 (defun org-date-from-calendar ()
16197 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16198 If there is already a time stamp at the cursor position, update it."
16199 (interactive)
16200 (if (org-at-timestamp-p t)
16201 (org-timestamp-change 0 'calendar)
16202 (let ((cal-date (org-get-date-from-calendar)))
16203 (org-insert-time-stamp
16204 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16206 (defun org-minutes-to-hh:mm-string (m)
16207 "Compute H:MM from a number of minutes."
16208 (let ((h (/ m 60)))
16209 (setq m (- m (* 60 h)))
16210 (format org-time-clocksum-format h m)))
16212 (defun org-hh:mm-string-to-minutes (s)
16213 "Convert a string H:MM to a number of minutes.
16214 If the string is just a number, interpret it as minutes.
16215 In fact, the first hh:mm or number in the string will be taken,
16216 there can be extra stuff in the string.
16217 If no number is found, the return value is 0."
16218 (cond
16219 ((integerp s) s)
16220 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16221 (+ (* (string-to-number (match-string 1 s)) 60)
16222 (string-to-number (match-string 2 s))))
16223 ((string-match "\\([0-9]+\\)" s)
16224 (string-to-number (match-string 1 s)))
16225 (t 0)))
16227 (defcustom org-effort-durations
16228 `(("h" . 60)
16229 ("d" . ,(* 60 8))
16230 ("w" . ,(* 60 8 5))
16231 ("m" . ,(* 60 8 5 4))
16232 ("y" . ,(* 60 8 5 40)))
16233 "Conversion factor to minutes for an effort modifier.
16235 Each entry has the form (MODIFIER . MINUTES).
16237 In an effort string, a number followed by MODIFIER is multiplied
16238 by the specified number of MINUTES to obtain an effort in
16239 minutes.
16241 For example, if the value of this variable is ((\"hours\" . 60)), then an
16242 effort string \"2hours\" is equivalent to 120 minutes."
16243 :group 'org-agenda
16244 :version "24.1"
16245 :type '(alist :key-type (string :tag "Modifier")
16246 :value-type (number :tag "Minutes")))
16248 (defun org-duration-string-to-minutes (s)
16249 "Convert a duration string S to minutes.
16251 A bare number is interpreted as minutes, modifiers can be set by
16252 customizing `org-effort-durations' (which see).
16254 Entries containing a colon are interpreted as H:MM by
16255 `org-hh:mm-string-to-minutes'."
16256 (let ((result 0)
16257 (re (concat "\\([0-9]+\\) *\\("
16258 (regexp-opt (mapcar 'car org-effort-durations))
16259 "\\)")))
16260 (while (string-match re s)
16261 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16262 (string-to-number (match-string 1 s))))
16263 (setq s (replace-match "" nil t s)))
16264 (incf result (org-hh:mm-string-to-minutes s))
16265 result))
16267 ;;;; Files
16269 (defun org-save-all-org-buffers ()
16270 "Save all Org-mode buffers without user confirmation."
16271 (interactive)
16272 (message "Saving all Org-mode buffers...")
16273 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16274 (when (featurep 'org-id) (org-id-locations-save))
16275 (message "Saving all Org-mode buffers... done"))
16277 (defun org-revert-all-org-buffers ()
16278 "Revert all Org-mode buffers.
16279 Prompt for confirmation when there are unsaved changes.
16280 Be sure you know what you are doing before letting this function
16281 overwrite your changes.
16283 This function is useful in a setup where one tracks org files
16284 with a version control system, to revert on one machine after pulling
16285 changes from another. I believe the procedure must be like this:
16287 1. M-x org-save-all-org-buffers
16288 2. Pull changes from the other machine, resolve conflicts
16289 3. M-x org-revert-all-org-buffers"
16290 (interactive)
16291 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16292 (error "Abort"))
16293 (save-excursion
16294 (save-window-excursion
16295 (mapc
16296 (lambda (b)
16297 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16298 (with-current-buffer b buffer-file-name))
16299 (org-pop-to-buffer-same-window b)
16300 (revert-buffer t 'no-confirm)))
16301 (buffer-list))
16302 (when (and (featurep 'org-id) org-id-track-globally)
16303 (org-id-locations-load)))))
16305 ;;;; Agenda files
16307 ;;;###autoload
16308 (defun org-switchb (&optional arg)
16309 "Switch between Org buffers.
16310 With one prefix argument, restrict available buffers to files.
16311 With two prefix arguments, restrict available buffers to agenda files.
16313 Defaults to `iswitchb' for buffer name completion.
16314 Set `org-completion-use-ido' to make it use ido instead."
16315 (interactive "P")
16316 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16317 ((equal arg '(16)) (org-buffer-list 'agenda))
16318 (t (org-buffer-list))))
16319 (org-completion-use-iswitchb org-completion-use-iswitchb)
16320 (org-completion-use-ido org-completion-use-ido))
16321 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16322 (setq org-completion-use-iswitchb t))
16323 (org-pop-to-buffer-same-window
16324 (org-icompleting-read "Org buffer: "
16325 (mapcar 'list (mapcar 'buffer-name blist))
16326 nil t))))
16328 ;;; Define some older names previously used for this functionality
16329 ;;;###autoload
16330 (defalias 'org-ido-switchb 'org-switchb)
16331 ;;;###autoload
16332 (defalias 'org-iswitchb 'org-switchb)
16334 (defun org-buffer-list (&optional predicate exclude-tmp)
16335 "Return a list of Org buffers.
16336 PREDICATE can be `export', `files' or `agenda'.
16338 export restrict the list to Export buffers.
16339 files restrict the list to buffers visiting Org files.
16340 agenda restrict the list to buffers visiting agenda files.
16342 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16343 (let* ((bfn nil)
16344 (agenda-files (and (eq predicate 'agenda)
16345 (mapcar 'file-truename (org-agenda-files t))))
16346 (filter
16347 (cond
16348 ((eq predicate 'files)
16349 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16350 ((eq predicate 'export)
16351 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16352 ((eq predicate 'agenda)
16353 (lambda (b)
16354 (with-current-buffer b
16355 (and (eq major-mode 'org-mode)
16356 (setq bfn (buffer-file-name b))
16357 (member (file-truename bfn) agenda-files)))))
16358 (t (lambda (b) (with-current-buffer b
16359 (or (eq major-mode 'org-mode)
16360 (string-match "\*Org .*Export"
16361 (buffer-name b)))))))))
16362 (delq nil
16363 (mapcar
16364 (lambda(b)
16365 (if (and (funcall filter b)
16366 (or (not exclude-tmp)
16367 (not (string-match "tmp" (buffer-name b)))))
16369 nil))
16370 (buffer-list)))))
16372 (defun org-agenda-files (&optional unrestricted archives)
16373 "Get the list of agenda files.
16374 Optional UNRESTRICTED means return the full list even if a restriction
16375 is currently in place.
16376 When ARCHIVES is t, include all archive files that are really being
16377 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16378 `org-agenda-archives-mode' is t."
16379 (let ((files
16380 (cond
16381 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16382 ((stringp org-agenda-files) (org-read-agenda-file-list))
16383 ((listp org-agenda-files) org-agenda-files)
16384 (t (error "Invalid value of `org-agenda-files'")))))
16385 (setq files (apply 'append
16386 (mapcar (lambda (f)
16387 (if (file-directory-p f)
16388 (directory-files
16389 f t org-agenda-file-regexp)
16390 (list f)))
16391 files)))
16392 (when org-agenda-skip-unavailable-files
16393 (setq files (delq nil
16394 (mapcar (function
16395 (lambda (file)
16396 (and (file-readable-p file) file)))
16397 files))))
16398 (when (or (eq archives t)
16399 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16400 (setq files (org-add-archive-files files)))
16401 files))
16403 (defun org-agenda-file-p (&optional file)
16404 "Return non-nil, if FILE is an agenda file.
16405 If FILE is omitted, use the file associated with the current
16406 buffer."
16407 (member (or file (buffer-file-name))
16408 (org-agenda-files t)))
16410 (defun org-edit-agenda-file-list ()
16411 "Edit the list of agenda files.
16412 Depending on setup, this either uses customize to edit the variable
16413 `org-agenda-files', or it visits the file that is holding the list. In the
16414 latter case, the buffer is set up in a way that saving it automatically kills
16415 the buffer and restores the previous window configuration."
16416 (interactive)
16417 (if (stringp org-agenda-files)
16418 (let ((cw (current-window-configuration)))
16419 (find-file org-agenda-files)
16420 (org-set-local 'org-window-configuration cw)
16421 (org-add-hook 'after-save-hook
16422 (lambda ()
16423 (set-window-configuration
16424 (prog1 org-window-configuration
16425 (kill-buffer (current-buffer))))
16426 (org-install-agenda-files-menu)
16427 (message "New agenda file list installed"))
16428 nil 'local)
16429 (message "%s" (substitute-command-keys
16430 "Edit list and finish with \\[save-buffer]")))
16431 (customize-variable 'org-agenda-files)))
16433 (defun org-store-new-agenda-file-list (list)
16434 "Set new value for the agenda file list and save it correctly."
16435 (if (stringp org-agenda-files)
16436 (let ((fe (org-read-agenda-file-list t)) b u)
16437 (while (setq b (find-buffer-visiting org-agenda-files))
16438 (kill-buffer b))
16439 (with-temp-file org-agenda-files
16440 (insert
16441 (mapconcat
16442 (lambda (f) ;; Keep un-expanded entries.
16443 (if (setq u (assoc f fe))
16444 (cdr u)
16446 list "\n")
16447 "\n")))
16448 (let ((org-mode-hook nil) (org-inhibit-startup t)
16449 (org-insert-mode-line-in-empty-file nil))
16450 (setq org-agenda-files list)
16451 (customize-save-variable 'org-agenda-files org-agenda-files))))
16453 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16454 "Read the list of agenda files from a file.
16455 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16456 filenames, used by `org-store-new-agenda-file-list' to write back
16457 un-expanded file names."
16458 (when (file-directory-p org-agenda-files)
16459 (error "`org-agenda-files' cannot be a single directory"))
16460 (when (stringp org-agenda-files)
16461 (with-temp-buffer
16462 (insert-file-contents org-agenda-files)
16463 (mapcar
16464 (lambda (f)
16465 (let ((e (expand-file-name (substitute-in-file-name f)
16466 org-directory)))
16467 (if pair-with-expansion
16468 (cons e f)
16469 e)))
16470 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16472 ;;;###autoload
16473 (defun org-cycle-agenda-files ()
16474 "Cycle through the files in `org-agenda-files'.
16475 If the current buffer visits an agenda file, find the next one in the list.
16476 If the current buffer does not, find the first agenda file."
16477 (interactive)
16478 (let* ((fs (org-agenda-files t))
16479 (files (append fs (list (car fs))))
16480 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16481 file)
16482 (unless files (error "No agenda files"))
16483 (catch 'exit
16484 (while (setq file (pop files))
16485 (if (equal (file-truename file) tcf)
16486 (when (car files)
16487 (find-file (car files))
16488 (throw 'exit t))))
16489 (find-file (car fs)))
16490 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16492 (defun org-agenda-file-to-front (&optional to-end)
16493 "Move/add the current file to the top of the agenda file list.
16494 If the file is not present in the list, it is added to the front. If it is
16495 present, it is moved there. With optional argument TO-END, add/move to the
16496 end of the list."
16497 (interactive "P")
16498 (let ((org-agenda-skip-unavailable-files nil)
16499 (file-alist (mapcar (lambda (x)
16500 (cons (file-truename x) x))
16501 (org-agenda-files t)))
16502 (ctf (file-truename buffer-file-name))
16503 x had)
16504 (setq x (assoc ctf file-alist) had x)
16506 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16507 (if to-end
16508 (setq file-alist (append (delq x file-alist) (list x)))
16509 (setq file-alist (cons x (delq x file-alist))))
16510 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16511 (org-install-agenda-files-menu)
16512 (message "File %s to %s of agenda file list"
16513 (if had "moved" "added") (if to-end "end" "front"))))
16515 (defun org-remove-file (&optional file)
16516 "Remove current file from the list of files in variable `org-agenda-files'.
16517 These are the files which are being checked for agenda entries.
16518 Optional argument FILE means use this file instead of the current."
16519 (interactive)
16520 (let* ((org-agenda-skip-unavailable-files nil)
16521 (file (or file buffer-file-name))
16522 (true-file (file-truename file))
16523 (afile (abbreviate-file-name file))
16524 (files (delq nil (mapcar
16525 (lambda (x)
16526 (if (equal true-file
16527 (file-truename x))
16528 nil x))
16529 (org-agenda-files t)))))
16530 (if (not (= (length files) (length (org-agenda-files t))))
16531 (progn
16532 (org-store-new-agenda-file-list files)
16533 (org-install-agenda-files-menu)
16534 (message "Removed file: %s" afile))
16535 (message "File was not in list: %s (not removed)" afile))))
16537 (defun org-file-menu-entry (file)
16538 (vector file (list 'find-file file) t))
16540 (defun org-check-agenda-file (file)
16541 "Make sure FILE exists. If not, ask user what to do."
16542 (when (not (file-exists-p file))
16543 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16544 (abbreviate-file-name file))
16545 (let ((r (downcase (read-char-exclusive))))
16546 (cond
16547 ((equal r ?r)
16548 (org-remove-file file)
16549 (throw 'nextfile t))
16550 (t (error "Abort"))))))
16552 (defun org-get-agenda-file-buffer (file)
16553 "Get a buffer visiting FILE. If the buffer needs to be created, add
16554 it to the list of buffers which might be released later."
16555 (let ((buf (org-find-base-buffer-visiting file)))
16556 (if buf
16557 buf ; just return it
16558 ;; Make a new buffer and remember it
16559 (setq buf (find-file-noselect file))
16560 (if buf (push buf org-agenda-new-buffers))
16561 buf)))
16563 (defun org-release-buffers (blist)
16564 "Release all buffers in list, asking the user for confirmation when needed.
16565 When a buffer is unmodified, it is just killed. When modified, it is saved
16566 \(if the user agrees) and then killed."
16567 (let (buf file)
16568 (while (setq buf (pop blist))
16569 (setq file (buffer-file-name buf))
16570 (when (and (buffer-modified-p buf)
16571 file
16572 (y-or-n-p (format "Save file %s? " file)))
16573 (with-current-buffer buf (save-buffer)))
16574 (kill-buffer buf))))
16576 (defun org-prepare-agenda-buffers (files)
16577 "Create buffers for all agenda files, protect archived trees and comments."
16578 (interactive)
16579 (let ((pa '(:org-archived t))
16580 (pc '(:org-comment t))
16581 (pall '(:org-archived t :org-comment t))
16582 (inhibit-read-only t)
16583 (rea (concat ":" org-archive-tag ":"))
16584 bmp file re)
16585 (save-excursion
16586 (save-restriction
16587 (while (setq file (pop files))
16588 (catch 'nextfile
16589 (if (bufferp file)
16590 (set-buffer file)
16591 (org-check-agenda-file file)
16592 (set-buffer (org-get-agenda-file-buffer file)))
16593 (widen)
16594 (setq bmp (buffer-modified-p))
16595 (org-refresh-category-properties)
16596 (setq org-todo-keywords-for-agenda
16597 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16598 (setq org-done-keywords-for-agenda
16599 (append org-done-keywords-for-agenda org-done-keywords))
16600 (setq org-todo-keyword-alist-for-agenda
16601 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16602 (setq org-drawers-for-agenda
16603 (append org-drawers-for-agenda org-drawers))
16604 (setq org-tag-alist-for-agenda
16605 (append org-tag-alist-for-agenda org-tag-alist))
16607 (save-excursion
16608 (remove-text-properties (point-min) (point-max) pall)
16609 (when org-agenda-skip-archived-trees
16610 (goto-char (point-min))
16611 (while (re-search-forward rea nil t)
16612 (if (org-at-heading-p t)
16613 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16614 (goto-char (point-min))
16615 (setq re (format org-heading-keyword-regexp-format
16616 org-comment-string))
16617 (while (re-search-forward re nil t)
16618 (add-text-properties
16619 (match-beginning 0) (org-end-of-subtree t) pc)))
16620 (set-buffer-modified-p bmp)))))
16621 (setq org-todo-keywords-for-agenda
16622 (org-uniquify org-todo-keywords-for-agenda))
16623 (setq org-todo-keyword-alist-for-agenda
16624 (org-uniquify org-todo-keyword-alist-for-agenda)
16625 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16627 ;;;; Embedded LaTeX
16629 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16630 "Keymap for the minor `org-cdlatex-mode'.")
16632 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16633 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16634 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16635 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16636 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16638 (defvar org-cdlatex-texmathp-advice-is-done nil
16639 "Flag remembering if we have applied the advice to texmathp already.")
16641 (define-minor-mode org-cdlatex-mode
16642 "Toggle the minor `org-cdlatex-mode'.
16643 This mode supports entering LaTeX environment and math in LaTeX fragments
16644 in Org-mode.
16645 \\{org-cdlatex-mode-map}"
16646 nil " OCDL" nil
16647 (when org-cdlatex-mode
16648 (require 'cdlatex)
16649 (run-hooks 'cdlatex-mode-hook)
16650 (cdlatex-compute-tables))
16651 (unless org-cdlatex-texmathp-advice-is-done
16652 (setq org-cdlatex-texmathp-advice-is-done t)
16653 (defadvice texmathp (around org-math-always-on activate)
16654 "Always return t in org-mode buffers.
16655 This is because we want to insert math symbols without dollars even outside
16656 the LaTeX math segments. If Orgmode thinks that point is actually inside
16657 an embedded LaTeX fragment, let texmathp do its job.
16658 \\[org-cdlatex-mode-map]"
16659 (interactive)
16660 (let (p)
16661 (cond
16662 ((not (eq major-mode 'org-mode)) ad-do-it)
16663 ((eq this-command 'cdlatex-math-symbol)
16664 (setq ad-return-value t
16665 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16667 (let ((p (org-inside-LaTeX-fragment-p)))
16668 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16669 (setq ad-return-value t
16670 texmathp-why '("Org-mode embedded math" . 0))
16671 (if p ad-do-it)))))))))
16673 (defun turn-on-org-cdlatex ()
16674 "Unconditionally turn on `org-cdlatex-mode'."
16675 (org-cdlatex-mode 1))
16677 (defun org-inside-LaTeX-fragment-p ()
16678 "Test if point is inside a LaTeX fragment.
16679 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16680 sequence appearing also before point.
16681 Even though the matchers for math are configurable, this function assumes
16682 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16683 delimiters are skipped when they have been removed by customization.
16684 The return value is nil, or a cons cell with the delimiter and the
16685 position of this delimiter.
16687 This function does a reasonably good job, but can locally be fooled by
16688 for example currency specifications. For example it will assume being in
16689 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16690 fragments that are properly closed, but during editing, we have to live
16691 with the uncertainty caused by missing closing delimiters. This function
16692 looks only before point, not after."
16693 (catch 'exit
16694 (let ((pos (point))
16695 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16696 (lim (progn
16697 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16698 (point)))
16699 dd-on str (start 0) m re)
16700 (goto-char pos)
16701 (when dodollar
16702 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16703 re (nth 1 (assoc "$" org-latex-regexps)))
16704 (while (string-match re str start)
16705 (cond
16706 ((= (match-end 0) (length str))
16707 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16708 ((= (match-end 0) (- (length str) 5))
16709 (throw 'exit nil))
16710 (t (setq start (match-end 0))))))
16711 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16712 (goto-char pos)
16713 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16714 (and (match-beginning 2) (throw 'exit nil))
16715 ;; count $$
16716 (while (re-search-backward "\\$\\$" lim t)
16717 (setq dd-on (not dd-on)))
16718 (goto-char pos)
16719 (if dd-on (cons "$$" m))))))
16721 (defun org-inside-latex-macro-p ()
16722 "Is point inside a LaTeX macro or its arguments?"
16723 (save-match-data
16724 (org-in-regexp
16725 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16727 (defun org-try-cdlatex-tab ()
16728 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16729 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16730 - inside a LaTeX fragment, or
16731 - after the first word in a line, where an abbreviation expansion could
16732 insert a LaTeX environment."
16733 (when org-cdlatex-mode
16734 (cond
16735 ;; Before any word on the line: No expansion possible.
16736 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16737 ;; Just after first word on the line: Expand it. Make sure it
16738 ;; cannot happen on headlines, though.
16739 ((save-excursion
16740 (skip-chars-backward "a-zA-Z0-9*")
16741 (skip-chars-backward " \t")
16742 (and (bolp) (not (org-at-heading-p))))
16743 (cdlatex-tab) t)
16744 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16746 (defun org-cdlatex-underscore-caret (&optional arg)
16747 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16748 Revert to the normal definition outside of these fragments."
16749 (interactive "P")
16750 (if (org-inside-LaTeX-fragment-p)
16751 (call-interactively 'cdlatex-sub-superscript)
16752 (let (org-cdlatex-mode)
16753 (call-interactively (key-binding (vector last-input-event))))))
16755 (defun org-cdlatex-math-modify (&optional arg)
16756 "Execute `cdlatex-math-modify' in LaTeX fragments.
16757 Revert to the normal definition outside of these fragments."
16758 (interactive "P")
16759 (if (org-inside-LaTeX-fragment-p)
16760 (call-interactively 'cdlatex-math-modify)
16761 (let (org-cdlatex-mode)
16762 (call-interactively (key-binding (vector last-input-event))))))
16764 (defvar org-latex-fragment-image-overlays nil
16765 "List of overlays carrying the images of latex fragments.")
16766 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16768 (defun org-remove-latex-fragment-image-overlays ()
16769 "Remove all overlays with LaTeX fragment images in current buffer."
16770 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16771 (setq org-latex-fragment-image-overlays nil))
16773 (defun org-preview-latex-fragment (&optional subtree)
16774 "Preview the LaTeX fragment at point, or all locally or globally.
16775 If the cursor is in a LaTeX fragment, create the image and overlay
16776 it over the source code. If there is no fragment at point, display
16777 all fragments in the current text, from one headline to the next. With
16778 prefix SUBTREE, display all fragments in the current subtree. With a
16779 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16780 the cursor is before the first headline,
16781 display all fragments in the buffer.
16782 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16783 (interactive "P")
16784 (unless buffer-file-name
16785 (error "Can't preview LaTeX fragment in a non-file buffer"))
16786 (org-remove-latex-fragment-image-overlays)
16787 (save-excursion
16788 (save-restriction
16789 (let (beg end at msg)
16790 (cond
16791 ((or (equal subtree '(16))
16792 (not (save-excursion
16793 (re-search-backward org-outline-regexp-bol nil t))))
16794 (setq beg (point-min) end (point-max)
16795 msg "Creating images for buffer...%s"))
16796 ((equal subtree '(4))
16797 (org-back-to-heading)
16798 (setq beg (point) end (org-end-of-subtree t)
16799 msg "Creating images for subtree...%s"))
16801 (if (setq at (org-inside-LaTeX-fragment-p))
16802 (goto-char (max (point-min) (- (cdr at) 2)))
16803 (org-back-to-heading))
16804 (setq beg (point) end (progn (outline-next-heading) (point))
16805 msg (if at "Creating image...%s"
16806 "Creating images for entry...%s"))))
16807 (message msg "")
16808 (narrow-to-region beg end)
16809 (goto-char beg)
16810 (org-format-latex
16811 (concat "ltxpng/" (file-name-sans-extension
16812 (file-name-nondirectory
16813 buffer-file-name)))
16814 default-directory 'overlays msg at 'forbuffer 'dvipng)
16815 (message msg "done. Use `C-c C-c' to remove images.")))))
16817 (defvar org-latex-regexps
16818 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16819 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16820 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16821 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16822 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16823 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16824 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16825 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16826 "Regular expressions for matching embedded LaTeX.")
16828 (defvar org-export-have-math nil) ;; dynamic scoping
16829 (defun org-format-latex (prefix &optional dir overlays msg at
16830 forbuffer processing-type)
16831 "Replace LaTeX fragments with links to an image, and produce images.
16832 Some of the options can be changed using the variable
16833 `org-format-latex-options'."
16834 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16835 (let* ((prefixnodir (file-name-nondirectory prefix))
16836 (absprefix (expand-file-name prefix dir))
16837 (todir (file-name-directory absprefix))
16838 (opt org-format-latex-options)
16839 (matchers (plist-get opt :matchers))
16840 (re-list org-latex-regexps)
16841 (org-format-latex-header-extra
16842 (plist-get (org-infile-export-plist) :latex-header-extra))
16843 (cnt 0) txt hash link beg end re e checkdir
16844 executables-checked string
16845 m n block-type block linkfile movefile ov)
16846 ;; Check the different regular expressions
16847 (while (setq e (pop re-list))
16848 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16849 block (if block-type "\n\n" ""))
16850 (when (member m matchers)
16851 (goto-char (point-min))
16852 (while (re-search-forward re nil t)
16853 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16854 (not (get-text-property (match-beginning n)
16855 'org-protected))
16856 (or (not overlays)
16857 (not (eq (get-char-property (match-beginning n)
16858 'org-overlay-type)
16859 'org-latex-overlay))))
16860 (setq org-export-have-math t)
16861 (cond
16862 ((eq processing-type 'verbatim)
16863 ;; Leave the text verbatim, just protect it
16864 (add-text-properties (match-beginning n) (match-end n)
16865 '(org-protected t)))
16866 ((eq processing-type 'mathjax)
16867 ;; Prepare for MathJax processing
16868 (setq string (match-string n))
16869 (if (member m '("$" "$1"))
16870 (save-excursion
16871 (delete-region (match-beginning n) (match-end n))
16872 (goto-char (match-beginning n))
16873 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16874 "\\)")
16875 '(org-protected t))))
16876 (add-text-properties (match-beginning n) (match-end n)
16877 '(org-protected t))))
16878 ((eq processing-type 'dvipng)
16879 ;; Process to an image
16880 (setq txt (match-string n)
16881 beg (match-beginning n) end (match-end n)
16882 cnt (1+ cnt))
16883 (let (print-length print-level) ; make sure full list is printed
16884 (setq hash (sha1 (prin1-to-string
16885 (list org-format-latex-header
16886 org-format-latex-header-extra
16887 org-export-latex-default-packages-alist
16888 org-export-latex-packages-alist
16889 org-format-latex-options
16890 forbuffer txt)))
16891 linkfile (format "%s_%s.png" prefix hash)
16892 movefile (format "%s_%s.png" absprefix hash)))
16893 (setq link (concat block "[[file:" linkfile "]]" block))
16894 (if msg (message msg cnt))
16895 (goto-char beg)
16896 (unless checkdir ; make sure the directory exists
16897 (setq checkdir t)
16898 (or (file-directory-p todir) (make-directory todir t)))
16900 (unless executables-checked
16901 (org-check-external-command
16902 "latex" "needed to convert LaTeX fragments to images")
16903 (org-check-external-command
16904 "dvipng" "needed to convert LaTeX fragments to images")
16905 (setq executables-checked t))
16907 (unless (file-exists-p movefile)
16908 (org-create-formula-image
16909 txt movefile opt forbuffer))
16910 (if overlays
16911 (progn
16912 (mapc (lambda (o)
16913 (if (eq (overlay-get o 'org-overlay-type)
16914 'org-latex-overlay)
16915 (delete-overlay o)))
16916 (overlays-in beg end))
16917 (setq ov (make-overlay beg end))
16918 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16919 (if (featurep 'xemacs)
16920 (progn
16921 (overlay-put ov 'invisible t)
16922 (overlay-put
16923 ov 'end-glyph
16924 (make-glyph (vector 'png :file movefile))))
16925 (overlay-put
16926 ov 'display
16927 (list 'image :type 'png :file movefile :ascent 'center)))
16928 (push ov org-latex-fragment-image-overlays)
16929 (goto-char end))
16930 (delete-region beg end)
16931 (insert (org-add-props link
16932 (list 'org-latex-src
16933 (replace-regexp-in-string
16934 "\"" "" txt)
16935 'org-latex-src-embed-type
16936 (if block-type 'paragraph 'character))))))
16937 ((eq processing-type 'mathml)
16938 ;; Process to MathML
16939 (unless executables-checked
16940 (unless (save-match-data (org-format-latex-mathml-available-p))
16941 (error "LaTeX to MathML converter not configured"))
16942 (setq executables-checked t))
16943 (setq txt (match-string n)
16944 beg (match-beginning n) end (match-end n)
16945 cnt (1+ cnt))
16946 (if msg (message msg cnt))
16947 (goto-char beg)
16948 (delete-region beg end)
16949 (insert (org-format-latex-as-mathml
16950 txt block-type prefix dir)))
16952 (error "Unknown conversion type %s for latex fragments"
16953 processing-type)))))))))
16955 (defun org-create-math-formula (latex-frag &optional mathml-file)
16956 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16957 Use `org-latex-to-mathml-convert-command'. If the conversion is
16958 sucessful, return the portion between \"<math...> </math>\"
16959 elements otherwise return nil. When MATHML-FILE is specified,
16960 write the results in to that file. When invoked as an
16961 interactive command, prompt for LATEX-FRAG, with initial value
16962 set to the current active region and echo the results for user
16963 inspection."
16964 (interactive (list (let ((frag (when (region-active-p)
16965 (buffer-substring-no-properties
16966 (region-beginning) (region-end)))))
16967 (read-string "LaTeX Fragment: " frag nil frag))))
16968 (unless latex-frag (error "Invalid latex-frag"))
16969 (let* ((tmp-in-file (file-relative-name
16970 (make-temp-name (expand-file-name "ltxmathml-in"))))
16971 (ignore (write-region latex-frag nil tmp-in-file))
16972 (tmp-out-file (file-relative-name
16973 (make-temp-name (expand-file-name "ltxmathml-out"))))
16974 (cmd (format-spec
16975 org-latex-to-mathml-convert-command
16976 `((?j . ,(shell-quote-argument
16977 (expand-file-name org-latex-to-mathml-jar-file)))
16978 (?I . ,(shell-quote-argument tmp-in-file))
16979 (?o . ,(shell-quote-argument tmp-out-file)))))
16980 mathml shell-command-output)
16981 (when (org-called-interactively-p 'any)
16982 (unless (org-format-latex-mathml-available-p)
16983 (error "LaTeX to MathML converter not configured")))
16984 (message "Running %s" cmd)
16985 (setq shell-command-output (shell-command-to-string cmd))
16986 (setq mathml
16987 (when (file-readable-p tmp-out-file)
16988 (with-current-buffer (find-file-noselect tmp-out-file t)
16989 (goto-char (point-min))
16990 (when (re-search-forward
16991 (concat
16992 (regexp-quote
16993 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16994 "\\(.\\|\n\\)*"
16995 (regexp-quote "</math>")) nil t)
16996 (prog1 (match-string 0) (kill-buffer))))))
16997 (cond
16998 (mathml
16999 (setq mathml
17000 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17001 (when mathml-file
17002 (write-region mathml nil mathml-file))
17003 (when (org-called-interactively-p 'any)
17004 (message mathml)))
17005 ((message "LaTeX to MathML conversion failed")
17006 (message shell-command-output)))
17007 (delete-file tmp-in-file)
17008 (when (file-exists-p tmp-out-file)
17009 (delete-file tmp-out-file))
17010 mathml))
17012 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17013 prefix &optional dir)
17014 "Use `org-create-math-formula' but check local cache first."
17015 (let* ((absprefix (expand-file-name prefix dir))
17016 (print-length nil) (print-level nil)
17017 (formula-id (concat
17018 "formula-"
17019 (sha1
17020 (prin1-to-string
17021 (list latex-frag
17022 org-latex-to-mathml-convert-command)))))
17023 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17024 (formula-cache-dir (file-name-directory formula-cache)))
17026 (unless (file-directory-p formula-cache-dir)
17027 (make-directory formula-cache-dir t))
17029 (unless (file-exists-p formula-cache)
17030 (org-create-math-formula latex-frag formula-cache))
17032 (if (file-exists-p formula-cache)
17033 ;; Successful conversion. Return the link to MathML file.
17034 (org-add-props
17035 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17036 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17037 'org-latex-src-embed-type (if latex-frag-type
17038 'paragraph 'character)))
17039 ;; Failed conversion. Return the LaTeX fragment verbatim
17040 (add-text-properties
17041 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17042 latex-frag)))
17044 ;; This function borrows from Ganesh Swami's latex2png.el
17045 (defun org-create-formula-image (string tofile options buffer)
17046 "This calls dvipng."
17047 (require 'org-latex)
17048 (let* ((tmpdir (if (featurep 'xemacs)
17049 (temp-directory)
17050 temporary-file-directory))
17051 (texfilebase (make-temp-name
17052 (expand-file-name "orgtex" tmpdir)))
17053 (texfile (concat texfilebase ".tex"))
17054 (dvifile (concat texfilebase ".dvi"))
17055 (pngfile (concat texfilebase ".png"))
17056 (fnh (if (featurep 'xemacs)
17057 (font-height (face-font 'default))
17058 (face-attribute 'default :height nil)))
17059 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17060 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17061 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17062 "Black"))
17063 (bg (or (plist-get options (if buffer :background :html-background))
17064 "Transparent")))
17065 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17066 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17067 (with-temp-file texfile
17068 (insert (org-splice-latex-header
17069 org-format-latex-header
17070 org-export-latex-default-packages-alist
17071 org-export-latex-packages-alist t
17072 org-format-latex-header-extra))
17073 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17074 (require 'org-latex)
17075 (org-export-latex-fix-inputenc))
17076 (let ((dir default-directory))
17077 (condition-case nil
17078 (progn
17079 (cd tmpdir)
17080 (call-process "latex" nil nil nil texfile))
17081 (error nil))
17082 (cd dir))
17083 (if (not (file-exists-p dvifile))
17084 (progn (message "Failed to create dvi file from %s" texfile) nil)
17085 (condition-case nil
17086 (if (featurep 'xemacs)
17087 (call-process "dvipng" nil nil nil
17088 "-fg" fg "-bg" bg
17089 "-T" "tight"
17090 "-o" pngfile
17091 dvifile)
17092 (call-process "dvipng" nil nil nil
17093 "-fg" fg "-bg" bg
17094 "-D" dpi
17095 ;;"-x" scale "-y" scale
17096 "-T" "tight"
17097 "-o" pngfile
17098 dvifile))
17099 (error nil))
17100 (if (not (file-exists-p pngfile))
17101 (if org-format-latex-signal-error
17102 (error "Failed to create png file from %s" texfile)
17103 (message "Failed to create png file from %s" texfile)
17104 nil)
17105 ;; Use the requested file name and clean up
17106 (copy-file pngfile tofile 'replace)
17107 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17108 (delete-file (concat texfilebase e)))
17109 pngfile))))
17111 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17112 "Fill a LaTeX header template TPL.
17113 In the template, the following place holders will be recognized:
17115 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17116 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17117 [PACKAGES] \\usepackage statements for PKG
17118 [NO-PACKAGES] do not include PKG
17119 [EXTRA] the string EXTRA
17120 [NO-EXTRA] do not include EXTRA
17122 For backward compatibility, if both the positive and the negative place
17123 holder is missing, the positive one (without the \"NO-\") will be
17124 assumed to be present at the end of the template.
17125 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17126 EXTRA is a string.
17127 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17128 (let (rpl (end ""))
17129 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17130 (setq rpl (if (or (match-end 1) (not def-pkg))
17131 "" (org-latex-packages-to-string def-pkg snippets-p t))
17132 tpl (replace-match rpl t t tpl))
17133 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17135 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17136 (setq rpl (if (or (match-end 1) (not pkg))
17137 "" (org-latex-packages-to-string pkg snippets-p t))
17138 tpl (replace-match rpl t t tpl))
17139 (if pkg (setq end
17140 (concat end "\n"
17141 (org-latex-packages-to-string pkg snippets-p)))))
17143 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17144 (setq rpl (if (or (match-end 1) (not extra))
17145 "" (concat extra "\n"))
17146 tpl (replace-match rpl t t tpl))
17147 (if (and extra (string-match "\\S-" extra))
17148 (setq end (concat end "\n" extra))))
17150 (if (string-match "\\S-" end)
17151 (concat tpl "\n" end)
17152 tpl)))
17154 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17155 "Turn an alist of packages into a string with the \\usepackage macros."
17156 (setq pkg (mapconcat (lambda(p)
17157 (cond
17158 ((stringp p) p)
17159 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17160 (format "%% Package %s omitted" (cadr p)))
17161 ((equal "" (car p))
17162 (format "\\usepackage{%s}" (cadr p)))
17164 (format "\\usepackage[%s]{%s}"
17165 (car p) (cadr p)))))
17167 "\n"))
17168 (if newline (concat pkg "\n") pkg))
17170 (defun org-dvipng-color (attr)
17171 "Return an rgb color specification for dvipng."
17172 (apply 'format "rgb %s %s %s"
17173 (mapcar 'org-normalize-color
17174 (if (featurep 'xemacs)
17175 (color-rgb-components
17176 (face-property 'default
17177 (cond ((eq attr :foreground) 'foreground)
17178 ((eq attr :background) 'background))))
17179 (color-values (face-attribute 'default attr nil))))))
17181 (defun org-normalize-color (value)
17182 "Return string to be used as color value for an RGB component."
17183 (format "%g" (/ value 65535.0)))
17185 ;; Image display
17188 (defvar org-inline-image-overlays nil)
17189 (make-variable-buffer-local 'org-inline-image-overlays)
17191 (defun org-toggle-inline-images (&optional include-linked)
17192 "Toggle the display of inline images.
17193 INCLUDE-LINKED is passed to `org-display-inline-images'."
17194 (interactive "P")
17195 (if org-inline-image-overlays
17196 (progn
17197 (org-remove-inline-images)
17198 (message "Inline image display turned off"))
17199 (org-display-inline-images include-linked)
17200 (if org-inline-image-overlays
17201 (message "%d images displayed inline"
17202 (length org-inline-image-overlays))
17203 (message "No images to display inline"))))
17205 (defun org-display-inline-images (&optional include-linked refresh beg end)
17206 "Display inline images.
17207 Normally only links without a description part are inlined, because this
17208 is how it will work for export. When INCLUDE-LINKED is set, also links
17209 with a description part will be inlined. This can be nice for a quick
17210 look at those images, but it does not reflect what exported files will look
17211 like.
17212 When REFRESH is set, refresh existing images between BEG and END.
17213 This will create new image displays only if necessary.
17214 BEG and END default to the buffer boundaries."
17215 (interactive "P")
17216 (unless refresh
17217 (org-remove-inline-images)
17218 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17219 (save-excursion
17220 (save-restriction
17221 (widen)
17222 (setq beg (or beg (point-min)) end (or end (point-max)))
17223 (goto-char beg)
17224 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17225 (substring (org-image-file-name-regexp) 0 -2)
17226 "\\)\\]" (if include-linked "" "\\]")))
17227 old file ov img)
17228 (while (re-search-forward re end t)
17229 (setq old (get-char-property-and-overlay (match-beginning 1)
17230 'org-image-overlay))
17231 (setq file (expand-file-name
17232 (concat (or (match-string 3) "") (match-string 4))))
17233 (when (file-exists-p file)
17234 (if (and (car-safe old) refresh)
17235 (image-refresh (overlay-get (cdr old) 'display))
17236 (setq img (save-match-data (create-image file)))
17237 (when img
17238 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17239 (overlay-put ov 'display img)
17240 (overlay-put ov 'face 'default)
17241 (overlay-put ov 'org-image-overlay t)
17242 (overlay-put ov 'modification-hooks
17243 (list 'org-display-inline-modification-hook))
17244 (push ov org-inline-image-overlays)))))))))
17246 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17247 "Remove inline-display overlay if a corresponding region is modified."
17248 (let ((inhibit-modification-hooks t))
17249 (when (and ov after)
17250 (delete ov org-inline-image-overlays)
17251 (delete-overlay ov))))
17253 (defun org-remove-inline-images ()
17254 "Remove inline display of images."
17255 (interactive)
17256 (mapc 'delete-overlay org-inline-image-overlays)
17257 (setq org-inline-image-overlays nil))
17259 ;;;; Key bindings
17261 ;; Outline functions from `outline-mode-prefix-map'
17262 ;; that can be remapped in Org:
17263 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17264 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17265 (define-key org-mode-map [remap outline-forward-same-level]
17266 'org-forward-same-level)
17267 (define-key org-mode-map [remap outline-backward-same-level]
17268 'org-backward-same-level)
17269 (define-key org-mode-map [remap show-branches]
17270 'org-kill-note-or-show-branches)
17271 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17272 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17273 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17275 ;; Outline functions from `outline-mode-prefix-map'
17276 ;; that can not be remapped in Org:
17277 ;; - the column "key binding" shows whether the Outline function is still
17278 ;; available in Org mode on the same key that it has been bound to in
17279 ;; Outline mode:
17280 ;; - "overridden": key used for a different functionality in Org mode
17281 ;; - else: key still bound to the same Outline function in Org mode
17282 ;; | Outline function | key binding | Org replacement |
17283 ;; |------------------------------------+-------------+-----------------------|
17284 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17285 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17286 ;; | `show-children' | `C-c C-i' | visibility cycling |
17287 ;; | `hide-subtree' | overridden | visibility cycling |
17288 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17289 ;; | `hide-body' | overridden | no replacement |
17290 ;; | `show-all' | overridden | no replacement |
17291 ;; | `hide-entry' | overridden | visibility cycling |
17292 ;; | `show-entry' | overridden | no replacement |
17293 ;; | `hide-leaves' | overridden | no replacement |
17294 ;; | `hide-sublevels' | overridden | no replacement |
17295 ;; | `hide-other' | overridden | no replacement |
17296 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17297 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17299 ;; Make `C-c C-x' a prefix key
17300 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17302 ;; TAB key with modifiers
17303 (org-defkey org-mode-map "\C-i" 'org-cycle)
17304 (org-defkey org-mode-map [(tab)] 'org-cycle)
17305 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17306 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17307 ;; The following line is necessary under Suse GNU/Linux
17308 (unless (featurep 'xemacs)
17309 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17310 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17311 (define-key org-mode-map [backtab] 'org-shifttab)
17313 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17314 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17315 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17317 ;; Cursor keys with modifiers
17318 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17319 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17320 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17321 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17323 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17324 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17325 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17326 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17328 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17329 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17330 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17331 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17333 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17334 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17335 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17336 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17338 ;; Babel keys
17339 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17340 (mapc (lambda (pair)
17341 (define-key org-babel-map (car pair) (cdr pair)))
17342 org-babel-key-bindings)
17344 ;;; Extra keys for tty access.
17345 ;; We only set them when really needed because otherwise the
17346 ;; menus don't show the simple keys
17348 (when (or org-use-extra-keys
17349 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17350 (not window-system))
17351 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17352 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17353 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17354 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17355 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17356 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17357 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17358 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17359 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17360 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17361 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17362 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17363 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17364 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17365 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17366 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17367 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17368 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17369 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17370 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17371 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17372 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17373 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17374 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17375 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17376 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17377 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17378 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17380 ;; All the other keys
17382 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17383 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17384 (if (boundp 'narrow-map)
17385 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17386 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17387 (if (boundp 'narrow-map)
17388 (org-defkey narrow-map "b" 'org-narrow-to-block)
17389 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17390 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17391 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17392 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17393 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17394 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17395 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17396 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17397 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17398 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17399 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17400 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17401 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17402 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17403 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17404 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17405 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17406 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17407 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17408 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17409 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17410 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17411 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17412 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17413 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17414 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17415 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17416 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17417 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17418 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17419 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17420 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17421 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17422 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17423 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17424 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17425 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17426 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17427 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17428 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17429 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17430 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17431 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17432 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17433 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17434 (org-defkey org-mode-map "\C-c^" 'org-sort)
17435 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17436 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17437 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17438 (org-defkey org-mode-map "\C-m" 'org-return)
17439 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17440 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17441 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17442 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17443 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17444 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17445 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17446 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17447 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17448 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17449 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17450 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17451 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17452 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17453 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17454 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17455 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17456 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17457 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17458 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17459 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17460 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17462 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17463 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17464 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17465 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17467 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17468 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17469 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17470 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17471 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17472 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17473 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17474 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17475 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17476 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17477 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17478 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17479 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17480 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17481 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17482 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17483 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17484 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17486 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17487 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17488 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17489 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17490 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17492 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17494 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17496 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17497 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17499 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17502 (when (featurep 'xemacs)
17503 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17506 (defconst org-speed-commands-default
17508 ("Outline Navigation")
17509 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17510 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17511 ("f" . (org-speed-move-safe 'org-forward-same-level))
17512 ("b" . (org-speed-move-safe 'org-backward-same-level))
17513 ("u" . (org-speed-move-safe 'outline-up-heading))
17514 ("j" . org-goto)
17515 ("g" . (org-refile t))
17516 ("Outline Visibility")
17517 ("c" . org-cycle)
17518 ("C" . org-shifttab)
17519 (" " . org-display-outline-path)
17520 ("Outline Structure Editing")
17521 ("U" . org-shiftmetaup)
17522 ("D" . org-shiftmetadown)
17523 ("r" . org-metaright)
17524 ("l" . org-metaleft)
17525 ("R" . org-shiftmetaright)
17526 ("L" . org-shiftmetaleft)
17527 ("i" . (progn (forward-char 1) (call-interactively
17528 'org-insert-heading-respect-content)))
17529 ("^" . org-sort)
17530 ("w" . org-refile)
17531 ("a" . org-archive-subtree-default-with-confirmation)
17532 ("." . org-mark-subtree)
17533 ("Clock Commands")
17534 ("I" . org-clock-in)
17535 ("O" . org-clock-out)
17536 ("Meta Data Editing")
17537 ("t" . org-todo)
17538 ("0" . (org-priority ?\ ))
17539 ("1" . (org-priority ?A))
17540 ("2" . (org-priority ?B))
17541 ("3" . (org-priority ?C))
17542 (";" . org-set-tags-command)
17543 ("e" . org-set-effort)
17544 ("Agenda Views etc")
17545 ("v" . org-agenda)
17546 ("/" . org-sparse-tree)
17547 ("Misc")
17548 ("o" . org-open-at-point)
17549 ("?" . org-speed-command-help)
17550 ("<" . (org-agenda-set-restriction-lock 'subtree))
17551 (">" . (org-agenda-remove-restriction-lock))
17553 "The default speed commands.")
17555 (defun org-print-speed-command (e)
17556 (if (> (length (car e)) 1)
17557 (progn
17558 (princ "\n")
17559 (princ (car e))
17560 (princ "\n")
17561 (princ (make-string (length (car e)) ?-))
17562 (princ "\n"))
17563 (princ (car e))
17564 (princ " ")
17565 (if (symbolp (cdr e))
17566 (princ (symbol-name (cdr e)))
17567 (prin1 (cdr e)))
17568 (princ "\n")))
17570 (defun org-speed-command-help ()
17571 "Show the available speed commands."
17572 (interactive)
17573 (if (not org-use-speed-commands)
17574 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17575 (with-output-to-temp-buffer "*Help*"
17576 (princ "User-defined Speed commands\n===========================\n")
17577 (mapc 'org-print-speed-command org-speed-commands-user)
17578 (princ "\n")
17579 (princ "Built-in Speed commands\n=======================\n")
17580 (mapc 'org-print-speed-command org-speed-commands-default))
17581 (with-current-buffer "*Help*"
17582 (setq truncate-lines t))))
17584 (defun org-speed-move-safe (cmd)
17585 "Execute CMD, but make sure that the cursor always ends up in a headline.
17586 If not, return to the original position and throw an error."
17587 (interactive)
17588 (let ((pos (point)))
17589 (call-interactively cmd)
17590 (unless (and (bolp) (org-at-heading-p))
17591 (goto-char pos)
17592 (error "Boundary reached while executing %s" cmd))))
17594 (defvar org-self-insert-command-undo-counter 0)
17596 (defvar org-table-auto-blank-field) ; defined in org-table.el
17597 (defvar org-speed-command nil)
17599 (defun org-speed-command-default-hook (keys)
17600 "Hook for activating single-letter speed commands.
17601 `org-speed-commands-default' specifies a minimal command set.
17602 Use `org-speed-commands-user' for further customization."
17603 (when (or (and (bolp) (looking-at org-outline-regexp))
17604 (and (functionp org-use-speed-commands)
17605 (funcall org-use-speed-commands)))
17606 (cdr (assoc keys (append org-speed-commands-user
17607 org-speed-commands-default)))))
17609 (defun org-babel-speed-command-hook (keys)
17610 "Hook for activating single-letter code block commands."
17611 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17612 (cdr (assoc keys org-babel-key-bindings))))
17614 (defcustom org-speed-command-hook
17615 '(org-speed-command-default-hook org-babel-speed-command-hook)
17616 "Hook for activating speed commands at strategic locations.
17617 Hook functions are called in sequence until a valid handler is
17618 found.
17620 Each hook takes a single argument, a user-pressed command key
17621 which is also a `self-insert-command' from the global map.
17623 Within the hook, examine the cursor position and the command key
17624 and return nil or a valid handler as appropriate. Handler could
17625 be one of an interactive command, a function, or a form.
17627 Set `org-use-speed-commands' to non-nil value to enable this
17628 hook. The default setting is `org-speed-command-default-hook'."
17629 :group 'org-structure
17630 :type 'hook)
17632 (defun org-self-insert-command (N)
17633 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17634 If the cursor is in a table looking at whitespace, the whitespace is
17635 overwritten, and the table is not marked as requiring realignment."
17636 (interactive "p")
17637 (org-check-before-invisible-edit 'insert)
17638 (cond
17639 ((and org-use-speed-commands
17640 (setq org-speed-command
17641 (run-hook-with-args-until-success
17642 'org-speed-command-hook (this-command-keys))))
17643 (cond
17644 ((commandp org-speed-command)
17645 (setq this-command org-speed-command)
17646 (call-interactively org-speed-command))
17647 ((functionp org-speed-command)
17648 (funcall org-speed-command))
17649 ((and org-speed-command (listp org-speed-command))
17650 (eval org-speed-command))
17651 (t (let (org-use-speed-commands)
17652 (call-interactively 'org-self-insert-command)))))
17653 ((and
17654 (org-table-p)
17655 (progn
17656 ;; check if we blank the field, and if that triggers align
17657 (and (featurep 'org-table) org-table-auto-blank-field
17658 (member last-command
17659 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17660 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17661 ;; got extra space, this field does not determine column width
17662 (let (org-table-may-need-update) (org-table-blank-field))
17663 ;; no extra space, this field may determine column width
17664 (org-table-blank-field)))
17666 (eq N 1)
17667 (looking-at "[^|\n]* |"))
17668 (let (org-table-may-need-update)
17669 (goto-char (1- (match-end 0)))
17670 (backward-delete-char 1)
17671 (goto-char (match-beginning 0))
17672 (self-insert-command N)))
17674 (setq org-table-may-need-update t)
17675 (self-insert-command N)
17676 (org-fix-tags-on-the-fly)
17677 (if org-self-insert-cluster-for-undo
17678 (if (not (eq last-command 'org-self-insert-command))
17679 (setq org-self-insert-command-undo-counter 1)
17680 (if (>= org-self-insert-command-undo-counter 20)
17681 (setq org-self-insert-command-undo-counter 1)
17682 (and (> org-self-insert-command-undo-counter 0)
17683 buffer-undo-list (listp buffer-undo-list)
17684 (not (cadr buffer-undo-list)) ; remove nil entry
17685 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17686 (setq org-self-insert-command-undo-counter
17687 (1+ org-self-insert-command-undo-counter))))))))
17689 (defun org-check-before-invisible-edit (kind)
17690 "Check is editing if kind KIND would be dangerous with invisible text around.
17691 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17692 ;; First, try to get out of here as quickly as possible, to reduce overhead
17693 (if (and org-catch-invisible-edits
17694 (or (not (boundp 'visible-mode)) (not visible-mode))
17695 (or (get-char-property (point) 'invisible)
17696 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17697 ;; OK, we need to take a closer look
17698 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17699 (invisible-before-point (if (bobp) nil (get-char-property
17700 (1- (point)) 'invisible)))
17701 (border-and-ok-direction
17703 ;; Check if we are acting predictably before invisible text
17704 (and invisible-at-point (not invisible-before-point)
17705 (memq kind '(insert delete-backward)))
17706 ;; Check if we are acting predictably after invisible text
17707 ;; This works not well, and I have turned it off. It seems
17708 ;; better to always show and stop after invisible text.
17709 ;; (and (not invisible-at-point) invisible-before-point
17710 ;; (memq kind '(insert delete)))
17713 (when (or (memq invisible-at-point '(outline org-hide-block))
17714 (memq invisible-before-point '(outline org-hide-block)))
17715 (if (eq org-catch-invisible-edits 'error)
17716 (error "Editing in invisible areas is prohibited - make visible first"))
17717 ;; Make the area visible
17718 (save-excursion
17719 (if invisible-before-point
17720 (goto-char (previous-single-char-property-change
17721 (point) 'invisible)))
17722 (org-cycle))
17723 (cond
17724 ((eq org-catch-invisible-edits 'show)
17725 ;; That's it, we do the edit after showing
17726 (message
17727 "Unfolding invisible region around point before editing")
17728 (sit-for 1))
17729 ((and (eq org-catch-invisible-edits 'smart)
17730 border-and-ok-direction)
17731 (message "Unfolding invisible region around point before editing"))
17733 ;; Don't do the edit, make the user repeat it in full visibility
17734 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17736 (defun org-fix-tags-on-the-fly ()
17737 (when (and (equal (char-after (point-at-bol)) ?*)
17738 (org-at-heading-p))
17739 (org-align-tags-here org-tags-column)))
17741 (defun org-delete-backward-char (N)
17742 "Like `delete-backward-char', insert whitespace at field end in tables.
17743 When deleting backwards, in tables this function will insert whitespace in
17744 front of the next \"|\" separator, to keep the table aligned. The table will
17745 still be marked for re-alignment if the field did fill the entire column,
17746 because, in this case the deletion might narrow the column."
17747 (interactive "p")
17748 (org-check-before-invisible-edit 'delete-backward)
17749 (if (and (org-table-p)
17750 (eq N 1)
17751 (string-match "|" (buffer-substring (point-at-bol) (point)))
17752 (looking-at ".*?|"))
17753 (let ((pos (point))
17754 (noalign (looking-at "[^|\n\r]* |"))
17755 (c org-table-may-need-update))
17756 (backward-delete-char N)
17757 (if (not overwrite-mode)
17758 (progn
17759 (skip-chars-forward "^|")
17760 (insert " ")
17761 (goto-char (1- pos))))
17762 ;; noalign: if there were two spaces at the end, this field
17763 ;; does not determine the width of the column.
17764 (if noalign (setq org-table-may-need-update c)))
17765 (backward-delete-char N)
17766 (org-fix-tags-on-the-fly)))
17768 (defun org-delete-char (N)
17769 "Like `delete-char', but insert whitespace at field end in tables.
17770 When deleting characters, in tables this function will insert whitespace in
17771 front of the next \"|\" separator, to keep the table aligned. The table will
17772 still be marked for re-alignment if the field did fill the entire column,
17773 because, in this case the deletion might narrow the column."
17774 (interactive "p")
17775 (org-check-before-invisible-edit 'delete)
17776 (if (and (org-table-p)
17777 (not (bolp))
17778 (not (= (char-after) ?|))
17779 (eq N 1))
17780 (if (looking-at ".*?|")
17781 (let ((pos (point))
17782 (noalign (looking-at "[^|\n\r]* |"))
17783 (c org-table-may-need-update))
17784 (replace-match (concat
17785 (substring (match-string 0) 1 -1)
17786 " |"))
17787 (goto-char pos)
17788 ;; noalign: if there were two spaces at the end, this field
17789 ;; does not determine the width of the column.
17790 (if noalign (setq org-table-may-need-update c)))
17791 (delete-char N))
17792 (delete-char N)
17793 (org-fix-tags-on-the-fly)))
17795 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17796 (put 'org-self-insert-command 'delete-selection t)
17797 (put 'orgtbl-self-insert-command 'delete-selection t)
17798 (put 'org-delete-char 'delete-selection 'supersede)
17799 (put 'org-delete-backward-char 'delete-selection 'supersede)
17800 (put 'org-yank 'delete-selection 'yank)
17802 ;; Make `flyspell-mode' delay after some commands
17803 (put 'org-self-insert-command 'flyspell-delayed t)
17804 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17805 (put 'org-delete-char 'flyspell-delayed t)
17806 (put 'org-delete-backward-char 'flyspell-delayed t)
17808 ;; Make pabbrev-mode expand after org-mode commands
17809 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17810 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17812 ;; How to do this: Measure non-white length of current string
17813 ;; If equal to column width, we should realign.
17815 (defun org-remap (map &rest commands)
17816 "In MAP, remap the functions given in COMMANDS.
17817 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17818 (let (new old)
17819 (while commands
17820 (setq old (pop commands) new (pop commands))
17821 (if (fboundp 'command-remapping)
17822 (org-defkey map (vector 'remap old) new)
17823 (substitute-key-definition old new map global-map)))))
17825 (when (eq org-enable-table-editor 'optimized)
17826 ;; If the user wants maximum table support, we need to hijack
17827 ;; some standard editing functions
17828 (org-remap org-mode-map
17829 'self-insert-command 'org-self-insert-command
17830 'delete-char 'org-delete-char
17831 'delete-backward-char 'org-delete-backward-char)
17832 (org-defkey org-mode-map "|" 'org-force-self-insert))
17834 (defvar org-ctrl-c-ctrl-c-hook nil
17835 "Hook for functions attaching themselves to `C-c C-c'.
17837 This can be used to add additional functionality to the C-c C-c
17838 key which executes context-dependent commands. This hook is run
17839 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17840 run after the last test.
17842 Each function will be called with no arguments. The function
17843 must check if the context is appropriate for it to act. If yes,
17844 it should do its thing and then return a non-nil value. If the
17845 context is wrong, just do nothing and return nil.")
17847 (defvar org-ctrl-c-ctrl-c-final-hook nil
17848 "Hook for functions attaching themselves to `C-c C-c'.
17850 This can be used to add additional functionality to the C-c C-c
17851 key which executes context-dependent commands. This hook is run
17852 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17853 before the first test.
17855 Each function will be called with no arguments. The function
17856 must check if the context is appropriate for it to act. If yes,
17857 it should do its thing and then return a non-nil value. If the
17858 context is wrong, just do nothing and return nil.")
17860 (defvar org-tab-first-hook nil
17861 "Hook for functions to attach themselves to TAB.
17862 See `org-ctrl-c-ctrl-c-hook' for more information.
17863 This hook runs as the first action when TAB is pressed, even before
17864 `org-cycle' messes around with the `outline-regexp' to cater for
17865 inline tasks and plain list item folding.
17866 If any function in this hook returns t, any other actions that
17867 would have been caused by TAB (such as table field motion or visibility
17868 cycling) will not occur.")
17870 (defvar org-tab-after-check-for-table-hook nil
17871 "Hook for functions to attach themselves to TAB.
17872 See `org-ctrl-c-ctrl-c-hook' for more information.
17873 This hook runs after it has been established that the cursor is not in a
17874 table, but before checking if the cursor is in a headline or if global cycling
17875 should be done.
17876 If any function in this hook returns t, not other actions like visibility
17877 cycling will be done.")
17879 (defvar org-tab-after-check-for-cycling-hook nil
17880 "Hook for functions to attach themselves to TAB.
17881 See `org-ctrl-c-ctrl-c-hook' for more information.
17882 This hook runs after it has been established that not table field motion and
17883 not visibility should be done because of current context. This is probably
17884 the place where a package like yasnippets can hook in.")
17886 (defvar org-tab-before-tab-emulation-hook nil
17887 "Hook for functions to attach themselves to TAB.
17888 See `org-ctrl-c-ctrl-c-hook' for more information.
17889 This hook runs after every other options for TAB have been exhausted, but
17890 before indentation and \t insertion takes place.")
17892 (defvar org-metaleft-hook nil
17893 "Hook for functions attaching themselves to `M-left'.
17894 See `org-ctrl-c-ctrl-c-hook' for more information.")
17895 (defvar org-metaright-hook nil
17896 "Hook for functions attaching themselves to `M-right'.
17897 See `org-ctrl-c-ctrl-c-hook' for more information.")
17898 (defvar org-metaup-hook nil
17899 "Hook for functions attaching themselves to `M-up'.
17900 See `org-ctrl-c-ctrl-c-hook' for more information.")
17901 (defvar org-metadown-hook nil
17902 "Hook for functions attaching themselves to `M-down'.
17903 See `org-ctrl-c-ctrl-c-hook' for more information.")
17904 (defvar org-shiftmetaleft-hook nil
17905 "Hook for functions attaching themselves to `M-S-left'.
17906 See `org-ctrl-c-ctrl-c-hook' for more information.")
17907 (defvar org-shiftmetaright-hook nil
17908 "Hook for functions attaching themselves to `M-S-right'.
17909 See `org-ctrl-c-ctrl-c-hook' for more information.")
17910 (defvar org-shiftmetaup-hook nil
17911 "Hook for functions attaching themselves to `M-S-up'.
17912 See `org-ctrl-c-ctrl-c-hook' for more information.")
17913 (defvar org-shiftmetadown-hook nil
17914 "Hook for functions attaching themselves to `M-S-down'.
17915 See `org-ctrl-c-ctrl-c-hook' for more information.")
17916 (defvar org-metareturn-hook nil
17917 "Hook for functions attaching themselves to `M-RET'.
17918 See `org-ctrl-c-ctrl-c-hook' for more information.")
17919 (defvar org-shiftup-hook nil
17920 "Hook for functions attaching themselves to `S-up'.
17921 See `org-ctrl-c-ctrl-c-hook' for more information.")
17922 (defvar org-shiftup-final-hook nil
17923 "Hook for functions attaching themselves to `S-up'.
17924 This one runs after all other options except shift-select have been excluded.
17925 See `org-ctrl-c-ctrl-c-hook' for more information.")
17926 (defvar org-shiftdown-hook nil
17927 "Hook for functions attaching themselves to `S-down'.
17928 See `org-ctrl-c-ctrl-c-hook' for more information.")
17929 (defvar org-shiftdown-final-hook nil
17930 "Hook for functions attaching themselves to `S-down'.
17931 This one runs after all other options except shift-select have been excluded.
17932 See `org-ctrl-c-ctrl-c-hook' for more information.")
17933 (defvar org-shiftleft-hook nil
17934 "Hook for functions attaching themselves to `S-left'.
17935 See `org-ctrl-c-ctrl-c-hook' for more information.")
17936 (defvar org-shiftleft-final-hook nil
17937 "Hook for functions attaching themselves to `S-left'.
17938 This one runs after all other options except shift-select have been excluded.
17939 See `org-ctrl-c-ctrl-c-hook' for more information.")
17940 (defvar org-shiftright-hook nil
17941 "Hook for functions attaching themselves to `S-right'.
17942 See `org-ctrl-c-ctrl-c-hook' for more information.")
17943 (defvar org-shiftright-final-hook nil
17944 "Hook for functions attaching themselves to `S-right'.
17945 This one runs after all other options except shift-select have been excluded.
17946 See `org-ctrl-c-ctrl-c-hook' for more information.")
17948 (defun org-modifier-cursor-error ()
17949 "Throw an error, a modified cursor command was applied in wrong context."
17950 (error "This command is active in special context like tables, headlines or items"))
17952 (defun org-shiftselect-error ()
17953 "Throw an error because Shift-Cursor command was applied in wrong context."
17954 (if (and (boundp 'shift-select-mode) shift-select-mode)
17955 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17956 (error "This command works only in special context like headlines or timestamps")))
17958 (defun org-call-for-shift-select (cmd)
17959 (let ((this-command-keys-shift-translated t))
17960 (call-interactively cmd)))
17962 (defun org-shifttab (&optional arg)
17963 "Global visibility cycling or move to previous table field.
17964 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17965 on context.
17966 See the individual commands for more information."
17967 (interactive "P")
17968 (cond
17969 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17970 ((integerp arg)
17971 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17972 (message "Content view to level: %d" arg)
17973 (org-content (prefix-numeric-value arg2))
17974 (setq org-cycle-global-status 'overview)))
17975 (t (call-interactively 'org-global-cycle))))
17977 (defun org-shiftmetaleft ()
17978 "Promote subtree or delete table column.
17979 Calls `org-promote-subtree', `org-outdent-item-tree', or
17980 `org-table-delete-column', depending on context. See the
17981 individual commands for more information."
17982 (interactive)
17983 (cond
17984 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17985 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17986 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17987 ((if (not (org-region-active-p)) (org-at-item-p)
17988 (save-excursion (goto-char (region-beginning))
17989 (org-at-item-p)))
17990 (call-interactively 'org-outdent-item-tree))
17991 (t (org-modifier-cursor-error))))
17993 (defun org-shiftmetaright ()
17994 "Demote subtree or insert table column.
17995 Calls `org-demote-subtree', `org-indent-item-tree', or
17996 `org-table-insert-column', depending on context. See the
17997 individual commands for more information."
17998 (interactive)
17999 (cond
18000 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18001 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18002 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18003 ((if (not (org-region-active-p)) (org-at-item-p)
18004 (save-excursion (goto-char (region-beginning))
18005 (org-at-item-p)))
18006 (call-interactively 'org-indent-item-tree))
18007 (t (org-modifier-cursor-error))))
18009 (defun org-shiftmetaup (&optional arg)
18010 "Move subtree up or kill table row.
18011 Calls `org-move-subtree-up' or `org-table-kill-row' or
18012 `org-move-item-up' depending on context. See the individual commands
18013 for more information."
18014 (interactive "P")
18015 (cond
18016 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18017 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18018 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18019 ((org-at-item-p) (call-interactively 'org-move-item-up))
18020 (t (org-modifier-cursor-error))))
18022 (defun org-shiftmetadown (&optional arg)
18023 "Move subtree down or insert table row.
18024 Calls `org-move-subtree-down' or `org-table-insert-row' or
18025 `org-move-item-down', depending on context. See the individual
18026 commands for more information."
18027 (interactive "P")
18028 (cond
18029 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18030 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18031 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18032 ((org-at-item-p) (call-interactively 'org-move-item-down))
18033 (t (org-modifier-cursor-error))))
18035 (defsubst org-hidden-tree-error ()
18036 (error
18037 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18039 (defun org-metaleft (&optional arg)
18040 "Promote heading or move table column to left.
18041 Calls `org-do-promote' or `org-table-move-column', depending on context.
18042 With no specific context, calls the Emacs default `backward-word'.
18043 See the individual commands for more information."
18044 (interactive "P")
18045 (cond
18046 ((run-hook-with-args-until-success 'org-metaleft-hook))
18047 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18048 ((org-with-limited-levels
18049 (or (org-at-heading-p)
18050 (and (org-region-active-p)
18051 (save-excursion
18052 (goto-char (region-beginning))
18053 (org-at-heading-p)))))
18054 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18055 (call-interactively 'org-do-promote))
18056 ;; At an inline task.
18057 ((org-at-heading-p)
18058 (call-interactively 'org-inlinetask-promote))
18059 ((or (org-at-item-p)
18060 (and (org-region-active-p)
18061 (save-excursion
18062 (goto-char (region-beginning))
18063 (org-at-item-p))))
18064 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18065 (call-interactively 'org-outdent-item))
18066 (t (call-interactively 'backward-word))))
18068 (defun org-metaright (&optional arg)
18069 "Demote subtree or move table column to right.
18070 Calls `org-do-demote' or `org-table-move-column', depending on context.
18071 With no specific context, calls the Emacs default `forward-word'.
18072 See the individual commands for more information."
18073 (interactive "P")
18074 (cond
18075 ((run-hook-with-args-until-success 'org-metaright-hook))
18076 ((org-at-table-p) (call-interactively 'org-table-move-column))
18077 ((org-with-limited-levels
18078 (or (org-at-heading-p)
18079 (and (org-region-active-p)
18080 (save-excursion
18081 (goto-char (region-beginning))
18082 (org-at-heading-p)))))
18083 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18084 (call-interactively 'org-do-demote))
18085 ;; At an inline task.
18086 ((org-at-heading-p)
18087 (call-interactively 'org-inlinetask-demote))
18088 ((or (org-at-item-p)
18089 (and (org-region-active-p)
18090 (save-excursion
18091 (goto-char (region-beginning))
18092 (org-at-item-p))))
18093 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18094 (call-interactively 'org-indent-item))
18095 (t (call-interactively 'forward-word))))
18097 (defun org-check-for-hidden (what)
18098 "Check if there are hidden headlines/items in the current visual line.
18099 WHAT can be either `headlines' or `items'. If the current line is
18100 an outline or item heading and it has a folded subtree below it,
18101 this function returns t, nil otherwise."
18102 (let ((re (cond
18103 ((eq what 'headlines) org-outline-regexp-bol)
18104 ((eq what 'items) (org-item-beginning-re))
18105 (t (error "This should not happen"))))
18106 beg end)
18107 (save-excursion
18108 (catch 'exit
18109 (unless (org-region-active-p)
18110 (setq beg (point-at-bol))
18111 (beginning-of-line 2)
18112 (while (and (not (eobp)) ;; this is like `next-line'
18113 (get-char-property (1- (point)) 'invisible))
18114 (beginning-of-line 2))
18115 (setq end (point))
18116 (goto-char beg)
18117 (goto-char (point-at-eol))
18118 (setq end (max end (point)))
18119 (while (re-search-forward re end t)
18120 (if (get-char-property (match-beginning 0) 'invisible)
18121 (throw 'exit t))))
18122 nil))))
18124 (defun org-metaup (&optional arg)
18125 "Move subtree up or move table row up.
18126 Calls `org-move-subtree-up' or `org-table-move-row' or
18127 `org-move-item-up', depending on context. See the individual commands
18128 for more information."
18129 (interactive "P")
18130 (cond
18131 ((run-hook-with-args-until-success 'org-metaup-hook))
18132 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18133 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18134 ((org-at-item-p) (call-interactively 'org-move-item-up))
18135 (t (transpose-lines 1) (beginning-of-line -1))))
18137 (defun org-metadown (&optional arg)
18138 "Move subtree down or move table row down.
18139 Calls `org-move-subtree-down' or `org-table-move-row' or
18140 `org-move-item-down', depending on context. See the individual
18141 commands for more information."
18142 (interactive "P")
18143 (cond
18144 ((run-hook-with-args-until-success 'org-metadown-hook))
18145 ((org-at-table-p) (call-interactively 'org-table-move-row))
18146 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18147 ((org-at-item-p) (call-interactively 'org-move-item-down))
18148 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18150 (defun org-shiftup (&optional arg)
18151 "Increase item in timestamp or increase priority of current headline.
18152 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18153 depending on context. See the individual commands for more information."
18154 (interactive "P")
18155 (cond
18156 ((run-hook-with-args-until-success 'org-shiftup-hook))
18157 ((and org-support-shift-select (org-region-active-p))
18158 (org-call-for-shift-select 'previous-line))
18159 ((org-at-timestamp-p t)
18160 (call-interactively (if org-edit-timestamp-down-means-later
18161 'org-timestamp-down 'org-timestamp-up)))
18162 ((and (not (eq org-support-shift-select 'always))
18163 org-enable-priority-commands
18164 (org-at-heading-p))
18165 (call-interactively 'org-priority-up))
18166 ((and (not org-support-shift-select) (org-at-item-p))
18167 (call-interactively 'org-previous-item))
18168 ((org-clocktable-try-shift 'up arg))
18169 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18170 (org-support-shift-select
18171 (org-call-for-shift-select 'previous-line))
18172 (t (org-shiftselect-error))))
18174 (defun org-shiftdown (&optional arg)
18175 "Decrease item in timestamp or decrease priority of current headline.
18176 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18177 depending on context. See the individual commands for more information."
18178 (interactive "P")
18179 (cond
18180 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18181 ((and org-support-shift-select (org-region-active-p))
18182 (org-call-for-shift-select 'next-line))
18183 ((org-at-timestamp-p t)
18184 (call-interactively (if org-edit-timestamp-down-means-later
18185 'org-timestamp-up 'org-timestamp-down)))
18186 ((and (not (eq org-support-shift-select 'always))
18187 org-enable-priority-commands
18188 (org-at-heading-p))
18189 (call-interactively 'org-priority-down))
18190 ((and (not org-support-shift-select) (org-at-item-p))
18191 (call-interactively 'org-next-item))
18192 ((org-clocktable-try-shift 'down arg))
18193 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18194 (org-support-shift-select
18195 (org-call-for-shift-select 'next-line))
18196 (t (org-shiftselect-error))))
18198 (defun org-shiftright (&optional arg)
18199 "Cycle the thing at point or in the current line, depending on context.
18200 Depending on context, this does one of the following:
18202 - switch a timestamp at point one day into the future
18203 - on a headline, switch to the next TODO keyword.
18204 - on an item, switch entire list to the next bullet type
18205 - on a property line, switch to the next allowed value
18206 - on a clocktable definition line, move time block into the future"
18207 (interactive "P")
18208 (cond
18209 ((run-hook-with-args-until-success 'org-shiftright-hook))
18210 ((and org-support-shift-select (org-region-active-p))
18211 (org-call-for-shift-select 'forward-char))
18212 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18213 ((and (not (eq org-support-shift-select 'always))
18214 (org-at-heading-p))
18215 (let ((org-inhibit-logging
18216 (not org-treat-S-cursor-todo-selection-as-state-change))
18217 (org-inhibit-blocking
18218 (not org-treat-S-cursor-todo-selection-as-state-change)))
18219 (org-call-with-arg 'org-todo 'right)))
18220 ((or (and org-support-shift-select
18221 (not (eq org-support-shift-select 'always))
18222 (org-at-item-bullet-p))
18223 (and (not org-support-shift-select) (org-at-item-p)))
18224 (org-call-with-arg 'org-cycle-list-bullet nil))
18225 ((and (not (eq org-support-shift-select 'always))
18226 (org-at-property-p))
18227 (call-interactively 'org-property-next-allowed-value))
18228 ((org-clocktable-try-shift 'right arg))
18229 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18230 (org-support-shift-select
18231 (org-call-for-shift-select 'forward-char))
18232 (t (org-shiftselect-error))))
18234 (defun org-shiftleft (&optional arg)
18235 "Cycle the thing at point or in the current line, depending on context.
18236 Depending on context, this does one of the following:
18238 - switch a timestamp at point one day into the past
18239 - on a headline, switch to the previous TODO keyword.
18240 - on an item, switch entire list to the previous bullet type
18241 - on a property line, switch to the previous allowed value
18242 - on a clocktable definition line, move time block into the past"
18243 (interactive "P")
18244 (cond
18245 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18246 ((and org-support-shift-select (org-region-active-p))
18247 (org-call-for-shift-select 'backward-char))
18248 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18249 ((and (not (eq org-support-shift-select 'always))
18250 (org-at-heading-p))
18251 (let ((org-inhibit-logging
18252 (not org-treat-S-cursor-todo-selection-as-state-change))
18253 (org-inhibit-blocking
18254 (not org-treat-S-cursor-todo-selection-as-state-change)))
18255 (org-call-with-arg 'org-todo 'left)))
18256 ((or (and org-support-shift-select
18257 (not (eq org-support-shift-select 'always))
18258 (org-at-item-bullet-p))
18259 (and (not org-support-shift-select) (org-at-item-p)))
18260 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18261 ((and (not (eq org-support-shift-select 'always))
18262 (org-at-property-p))
18263 (call-interactively 'org-property-previous-allowed-value))
18264 ((org-clocktable-try-shift 'left arg))
18265 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18266 (org-support-shift-select
18267 (org-call-for-shift-select 'backward-char))
18268 (t (org-shiftselect-error))))
18270 (defun org-shiftcontrolright ()
18271 "Switch to next TODO set."
18272 (interactive)
18273 (cond
18274 ((and org-support-shift-select (org-region-active-p))
18275 (org-call-for-shift-select 'forward-word))
18276 ((and (not (eq org-support-shift-select 'always))
18277 (org-at-heading-p))
18278 (org-call-with-arg 'org-todo 'nextset))
18279 (org-support-shift-select
18280 (org-call-for-shift-select 'forward-word))
18281 (t (org-shiftselect-error))))
18283 (defun org-shiftcontrolleft ()
18284 "Switch to previous TODO set."
18285 (interactive)
18286 (cond
18287 ((and org-support-shift-select (org-region-active-p))
18288 (org-call-for-shift-select 'backward-word))
18289 ((and (not (eq org-support-shift-select 'always))
18290 (org-at-heading-p))
18291 (org-call-with-arg 'org-todo 'previousset))
18292 (org-support-shift-select
18293 (org-call-for-shift-select 'backward-word))
18294 (t (org-shiftselect-error))))
18296 (defun org-shiftcontrolup ()
18297 "Change timestamps synchronously up 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-up))
18303 (t (org-shiftselect-error))))
18305 (defun org-shiftcontroldown ()
18306 "Change timestamps synchronously down in CLOCK log lines."
18307 (interactive)
18308 (cond ((and (not org-support-shift-select)
18309 (org-at-clock-log-p)
18310 (org-at-timestamp-p t))
18311 (org-clock-timestamps-down))
18312 (t (org-shiftselect-error))))
18314 (defun org-ctrl-c-ret ()
18315 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18316 (interactive)
18317 (cond
18318 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18319 (t (call-interactively 'org-insert-heading))))
18321 (defun org-find-visible ()
18322 (let ((s (point)))
18323 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18324 (get-char-property s 'invisible)))
18326 (defun org-find-invisible ()
18327 (let ((s (point)))
18328 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18329 (not (get-char-property s 'invisible))))
18332 (defun org-copy-visible (beg end)
18333 "Copy the visible parts of the region."
18334 (interactive "r")
18335 (let (snippets s)
18336 (save-excursion
18337 (save-restriction
18338 (narrow-to-region beg end)
18339 (setq s (goto-char (point-min)))
18340 (while (not (= (point) (point-max)))
18341 (goto-char (org-find-invisible))
18342 (push (buffer-substring s (point)) snippets)
18343 (setq s (goto-char (org-find-visible))))))
18344 (kill-new (apply 'concat (nreverse snippets)))))
18346 (defun org-copy-special ()
18347 "Copy region in table or copy current subtree.
18348 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18349 See the individual commands for more information."
18350 (interactive)
18351 (call-interactively
18352 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18354 (defun org-cut-special ()
18355 "Cut region in table or cut current subtree.
18356 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18357 See the individual commands for more information."
18358 (interactive)
18359 (call-interactively
18360 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18362 (defun org-paste-special (arg)
18363 "Paste rectangular region into table, or past subtree relative to level.
18364 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18365 See the individual commands for more information."
18366 (interactive "P")
18367 (if (org-at-table-p)
18368 (org-table-paste-rectangle)
18369 (org-paste-subtree arg)))
18371 (defun org-edit-special (&optional arg)
18372 "Call a special editor for the stuff at point.
18373 When at a table, call the formula editor with `org-table-edit-formulas'.
18374 When at the first line of an src example, call `org-edit-src-code'.
18375 When in an #+include line, visit the include file. Otherwise call
18376 `ffap' to visit the file at point."
18377 (interactive)
18378 ;; possibly prep session before editing source
18379 (when arg
18380 (let* ((info (org-babel-get-src-block-info))
18381 (lang (nth 0 info))
18382 (params (nth 2 info))
18383 (session (cdr (assoc :session params))))
18384 (when (and info session) ;; we are in a source-code block with a session
18385 (funcall
18386 (intern (concat "org-babel-prep-session:" lang)) session params))))
18387 (cond ;; proceed with `org-edit-special'
18388 ((save-excursion
18389 (beginning-of-line 1)
18390 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18391 (find-file (org-trim (match-string 1))))
18392 ((org-edit-src-code))
18393 ((org-edit-fixed-width-region))
18394 ((org-at-table.el-p)
18395 (org-edit-src-code))
18396 ((or (org-at-table-p)
18397 (save-excursion
18398 (beginning-of-line 1)
18399 (looking-at "[ \t]*#\\+TBLFM:")))
18400 (call-interactively 'org-table-edit-formulas))
18401 (t (call-interactively 'ffap))))
18403 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18404 (defun org-ctrl-c-ctrl-c (&optional arg)
18405 "Set tags in headline, or update according to changed information at point.
18407 This command does many different things, depending on context:
18409 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18410 this is what we do.
18412 - If the cursor is on a statistics cookie, update it.
18414 - If the cursor is in a headline, prompt for tags and insert them
18415 into the current line, aligned to `org-tags-column'. When called
18416 with prefix arg, realign all tags in the current buffer.
18418 - If the cursor is in one of the special #+KEYWORD lines, this
18419 triggers scanning the buffer for these lines and updating the
18420 information.
18422 - If the cursor is inside a table, realign the table. This command
18423 works even if the automatic table editor has been turned off.
18425 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18426 the entire table.
18428 - If the cursor is at a footnote reference or definition, jump to
18429 the corresponding definition or references, respectively.
18431 - If the cursor is a the beginning of a dynamic block, update it.
18433 - If the current buffer is a capture buffer, close note and file it.
18435 - If the cursor is on a <<<target>>>, update radio targets and
18436 corresponding links in this buffer.
18438 - If the cursor is on a numbered item in a plain list, renumber the
18439 ordered list.
18441 - If the cursor is on a checkbox, toggle it.
18443 - If the cursor is on a code block, evaluate it. The variable
18444 `org-confirm-babel-evaluate' can be used to control prompting
18445 before code block evaluation, by default every code block
18446 evaluation requires confirmation. Code block evaluation can be
18447 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18448 (interactive "P")
18449 (let ((org-enable-table-editor t))
18450 (cond
18451 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18452 org-occur-highlights
18453 org-latex-fragment-image-overlays)
18454 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18455 (org-remove-occur-highlights)
18456 (org-remove-latex-fragment-image-overlays)
18457 (message "Temporary highlights/overlays removed from current buffer"))
18458 ((and (local-variable-p 'org-finish-function (current-buffer))
18459 (fboundp org-finish-function))
18460 (funcall org-finish-function))
18461 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18462 ((org-in-regexp org-ts-regexp-both)
18463 (org-timestamp-change 0 'day))
18464 ((or (looking-at org-property-start-re)
18465 (org-at-property-p))
18466 (call-interactively 'org-property-action))
18467 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18468 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18469 (or (org-at-heading-p) (org-at-item-p)))
18470 (call-interactively 'org-update-statistics-cookies))
18471 ((org-at-heading-p) (call-interactively 'org-set-tags))
18472 ((org-at-table.el-p)
18473 (message "Use C-c ' to edit table.el tables"))
18474 ((org-at-table-p)
18475 (org-table-maybe-eval-formula)
18476 (if arg
18477 (call-interactively 'org-table-recalculate)
18478 (org-table-maybe-recalculate-line))
18479 (call-interactively 'org-table-align)
18480 (orgtbl-send-table 'maybe))
18481 ((or (org-footnote-at-reference-p)
18482 (org-footnote-at-definition-p))
18483 (call-interactively 'org-footnote-action))
18484 ((org-at-item-checkbox-p)
18485 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18486 ;; list only if at top item.
18487 (let* ((cbox (match-string 1))
18488 (struct (org-list-struct))
18489 (old-struct (copy-tree struct))
18490 (parents (org-list-parents-alist struct))
18491 (orderedp (org-entry-get nil "ORDERED"))
18492 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18493 block-item)
18494 ;; Use a light version of `org-toggle-checkbox' to avoid
18495 ;; computing list structure twice.
18496 (let ((new-box (cond
18497 ((equal arg '(16)) "[-]")
18498 ((equal arg '(4)) nil)
18499 ((equal "[X]" cbox) "[ ]")
18500 (t "[X]"))))
18501 (if (and firstp arg)
18502 ;; If at first item of sub-list, remove check-box from
18503 ;; every item at the same level.
18504 (mapc
18505 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18506 (org-list-get-all-items
18507 (point-at-bol) struct (org-list-prevs-alist struct)))
18508 (org-list-set-checkbox (point-at-bol) struct new-box)))
18509 ;; Replicate `org-list-write-struct', while grabbing a return
18510 ;; value from `org-list-struct-fix-box'.
18511 (org-list-struct-fix-ind struct parents 2)
18512 (org-list-struct-fix-item-end struct)
18513 (let ((prevs (org-list-prevs-alist struct)))
18514 (org-list-struct-fix-bul struct prevs)
18515 (org-list-struct-fix-ind struct parents)
18516 (setq block-item
18517 (org-list-struct-fix-box struct parents prevs orderedp)))
18518 (org-list-struct-apply-struct struct old-struct)
18519 (org-update-checkbox-count-maybe)
18520 (when block-item
18521 (message
18522 "Checkboxes were removed due to unchecked box at line %d"
18523 (org-current-line block-item)))
18524 (when firstp (org-list-send-list 'maybe))))
18525 ((org-at-item-p)
18526 ;; Cursor at an item: repair list. Do checkbox related actions
18527 ;; only if function was called with an argument. Send list only
18528 ;; if at top item.
18529 (let* ((struct (org-list-struct))
18530 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18531 old-struct)
18532 (when arg
18533 (setq old-struct (copy-tree struct))
18534 (if firstp
18535 ;; If at first item of sub-list, add check-box to every
18536 ;; item at the same level.
18537 (mapc
18538 (lambda (pos)
18539 (unless (org-list-get-checkbox pos struct)
18540 (org-list-set-checkbox pos struct "[ ]")))
18541 (org-list-get-all-items
18542 (point-at-bol) struct (org-list-prevs-alist struct)))
18543 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18544 (org-list-write-struct
18545 struct (org-list-parents-alist struct) old-struct)
18546 (when arg (org-update-checkbox-count-maybe))
18547 (when firstp (org-list-send-list 'maybe))))
18548 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18549 ;; Dynamic block
18550 (beginning-of-line 1)
18551 (save-excursion (org-update-dblock)))
18552 ((save-excursion
18553 (beginning-of-line 1)
18554 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18555 (cond
18556 ((equal (match-string 1) "TBLFM")
18557 ;; Recalculate the table before this line
18558 (save-excursion
18559 (beginning-of-line 1)
18560 (skip-chars-backward " \r\n\t")
18561 (if (org-at-table-p)
18562 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18564 (let ((org-inhibit-startup-visibility-stuff t)
18565 (org-startup-align-all-tables nil))
18566 (when (boundp 'org-table-coordinate-overlays)
18567 (mapc 'delete-overlay org-table-coordinate-overlays)
18568 (setq org-table-coordinate-overlays nil))
18569 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18570 (message "Local setup has been refreshed"))))
18571 ((org-clock-update-time-maybe))
18573 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18574 (error "C-c C-c can do nothing useful at this location"))))))
18576 (defun org-mode-restart ()
18577 "Restart Org-mode, to scan again for special lines.
18578 Also updates the keyword regular expressions."
18579 (interactive)
18580 (org-mode)
18581 (message "Org-mode restarted"))
18583 (defun org-kill-note-or-show-branches ()
18584 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18585 (interactive)
18586 (if (not org-finish-function)
18587 (progn
18588 (hide-subtree)
18589 (call-interactively 'show-branches))
18590 (let ((org-note-abort t))
18591 (funcall org-finish-function))))
18593 (defun org-return (&optional indent)
18594 "Goto next table row or insert a newline.
18595 Calls `org-table-next-row' or `newline', depending on context.
18596 See the individual commands for more information."
18597 (interactive)
18598 (cond
18599 ((bobp) (if indent (newline-and-indent) (newline)))
18600 ((org-at-table-p)
18601 (org-table-justify-field-maybe)
18602 (call-interactively 'org-table-next-row))
18603 ;; when `newline-and-indent' is called within a list, make sure
18604 ;; text moved stays inside the item.
18605 ((and (org-in-item-p) indent)
18606 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18607 (progn
18608 (save-match-data (newline))
18609 (org-indent-line-to (length (match-string 0))))
18610 (let ((ind (org-get-indentation)))
18611 (newline)
18612 (if (org-looking-back org-list-end-re)
18613 (org-indent-line-function)
18614 (org-indent-line-to ind)))))
18615 ((and org-return-follows-link
18616 (let ((tprop (get-text-property (point) 'face)))
18617 (or (eq tprop 'org-link)
18618 (and (listp tprop) (memq 'org-link tprop)))))
18619 (call-interactively 'org-open-at-point))
18620 ((and (org-at-heading-p)
18621 (looking-at
18622 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18623 (org-show-entry)
18624 (end-of-line 1)
18625 (newline))
18626 (t (if indent (newline-and-indent) (newline)))))
18628 (defun org-return-indent ()
18629 "Goto next table row or insert a newline and indent.
18630 Calls `org-table-next-row' or `newline-and-indent', depending on
18631 context. See the individual commands for more information."
18632 (interactive)
18633 (org-return t))
18635 (defun org-ctrl-c-star ()
18636 "Compute table, or change heading status of lines.
18637 Calls `org-table-recalculate' or `org-toggle-heading',
18638 depending on context."
18639 (interactive)
18640 (cond
18641 ((org-at-table-p)
18642 (call-interactively 'org-table-recalculate))
18644 ;; Convert all lines in region to list items
18645 (call-interactively 'org-toggle-heading))))
18647 (defun org-ctrl-c-minus ()
18648 "Insert separator line in table or modify bullet status of line.
18649 Also turns a plain line or a region of lines into list items.
18650 Calls `org-table-insert-hline', `org-toggle-item', or
18651 `org-cycle-list-bullet', depending on context."
18652 (interactive)
18653 (cond
18654 ((org-at-table-p)
18655 (call-interactively 'org-table-insert-hline))
18656 ((org-region-active-p)
18657 (call-interactively 'org-toggle-item))
18658 ((org-in-item-p)
18659 (call-interactively 'org-cycle-list-bullet))
18661 (call-interactively 'org-toggle-item))))
18663 (defun org-toggle-item (arg)
18664 "Convert headings or normal lines to items, items to normal lines.
18665 If there is no active region, only the current line is considered.
18667 If the first non blank line in the region is an headline, convert
18668 all headlines to items, shifting text accordingly.
18670 If it is an item, convert all items to normal lines.
18672 If it is normal text, change region into an item. With a prefix
18673 argument ARG, change each line in region into an item."
18674 (interactive "P")
18675 (let ((shift-text
18676 (function
18677 ;; Shift text in current section to IND, from point to END.
18678 ;; The function leaves point to END line.
18679 (lambda (ind end)
18680 (let ((min-i 1000) (end (copy-marker end)))
18681 ;; First determine the minimum indentation (MIN-I) of
18682 ;; the text.
18683 (save-excursion
18684 (catch 'exit
18685 (while (< (point) end)
18686 (let ((i (org-get-indentation)))
18687 (cond
18688 ;; Skip blank lines and inline tasks.
18689 ((looking-at "^[ \t]*$"))
18690 ((looking-at org-outline-regexp-bol))
18691 ;; We can't find less than 0 indentation.
18692 ((zerop i) (throw 'exit (setq min-i 0)))
18693 ((< i min-i) (setq min-i i))))
18694 (forward-line))))
18695 ;; Then indent each line so that a line indented to
18696 ;; MIN-I becomes indented to IND. Ignore blank lines
18697 ;; and inline tasks in the process.
18698 (let ((delta (- ind min-i)))
18699 (while (< (point) end)
18700 (unless (or (looking-at "^[ \t]*$")
18701 (looking-at org-outline-regexp-bol))
18702 (org-indent-line-to (+ (org-get-indentation) delta)))
18703 (forward-line)))))))
18704 (skip-blanks
18705 (function
18706 ;; Return beginning of first non-blank line, starting from
18707 ;; line at POS.
18708 (lambda (pos)
18709 (save-excursion
18710 (goto-char pos)
18711 (skip-chars-forward " \r\t\n")
18712 (point-at-bol)))))
18713 beg end)
18714 ;; Determine boundaries of changes.
18715 (if (org-region-active-p)
18716 (setq beg (funcall skip-blanks (region-beginning))
18717 end (copy-marker (region-end)))
18718 (setq beg (funcall skip-blanks (point-at-bol))
18719 end (copy-marker (point-at-eol))))
18720 ;; Depending on the starting line, choose an action on the text
18721 ;; between BEG and END.
18722 (org-with-limited-levels
18723 (save-excursion
18724 (goto-char beg)
18725 (cond
18726 ;; Case 1. Start at an item: de-itemize. Note that it only
18727 ;; happens when a region is active: `org-ctrl-c-minus'
18728 ;; would call `org-cycle-list-bullet' otherwise.
18729 ((org-at-item-p)
18730 (while (< (point) end)
18731 (when (org-at-item-p)
18732 (skip-chars-forward " \t")
18733 (delete-region (point) (match-end 0)))
18734 (forward-line)))
18735 ;; Case 2. Start at an heading: convert to items.
18736 ((org-at-heading-p)
18737 (let* ((bul (org-list-bullet-string "-"))
18738 (bul-len (length bul))
18739 ;; Indentation of the first heading. It should be
18740 ;; relative to the indentation of its parent, if any.
18741 (start-ind (save-excursion
18742 (cond
18743 ((not org-adapt-indentation) 0)
18744 ((not (outline-previous-heading)) 0)
18745 (t (length (match-string 0))))))
18746 ;; Level of first heading. Further headings will be
18747 ;; compared to it to determine hierarchy in the list.
18748 (ref-level (org-reduced-level (org-outline-level))))
18749 (while (< (point) end)
18750 (let* ((level (org-reduced-level (org-outline-level)))
18751 (delta (max 0 (- level ref-level))))
18752 ;; If current headline is less indented than the first
18753 ;; one, set it as reference, in order to preserve
18754 ;; subtrees.
18755 (when (< level ref-level) (setq ref-level level))
18756 (replace-match bul t t)
18757 (org-indent-line-to (+ start-ind (* delta bul-len)))
18758 ;; Ensure all text down to END (or SECTION-END) belongs
18759 ;; to the newly created item.
18760 (let ((section-end (save-excursion
18761 (or (outline-next-heading) (point)))))
18762 (forward-line)
18763 (funcall shift-text
18764 (+ start-ind (* (1+ delta) bul-len))
18765 (min end section-end)))))))
18766 ;; Case 3. Normal line with ARG: turn each non-item line into
18767 ;; an item.
18768 (arg
18769 (while (< (point) end)
18770 (unless (or (org-at-heading-p) (org-at-item-p))
18771 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18772 (replace-match
18773 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18774 (forward-line)))
18775 ;; Case 4. Normal line without ARG: make the first line of
18776 ;; region an item, and shift indentation of others
18777 ;; lines to set them as item's body.
18778 (t (let* ((bul (org-list-bullet-string "-"))
18779 (bul-len (length bul))
18780 (ref-ind (org-get-indentation)))
18781 (skip-chars-forward " \t")
18782 (insert bul)
18783 (forward-line)
18784 (while (< (point) end)
18785 ;; Ensure that lines less indented than first one
18786 ;; still get included in item body.
18787 (funcall shift-text
18788 (+ ref-ind bul-len)
18789 (min end (save-excursion (or (outline-next-heading)
18790 (point)))))
18791 (forward-line)))))))))
18793 (defun org-toggle-heading (&optional nstars)
18794 "Convert headings to normal text, or items or text to headings.
18795 If there is no active region, only the current line is considered.
18797 If the first non blank line is an headline, remove the stars from
18798 all headlines in the region.
18800 If it is a plain list item, turn all plain list items into headings.
18802 If it is a normal line, turn each and every normal line (i.e. not
18803 an heading or an item) in the region into a heading.
18805 When converting a line into a heading, the number of stars is chosen
18806 such that the lines become children of the current entry. However,
18807 when a prefix argument is given, its value determines the number of
18808 stars to add."
18809 (interactive "P")
18810 (let ((skip-blanks
18811 (function
18812 ;; Return beginning of first non-blank line, starting from
18813 ;; line at POS.
18814 (lambda (pos)
18815 (save-excursion
18816 (goto-char pos)
18817 (skip-chars-forward " \r\t\n")
18818 (point-at-bol)))))
18819 beg end)
18820 ;; Determine boundaries of changes. If region ends at a bol, do
18821 ;; not consider the last line to be in the region.
18822 (if (org-region-active-p)
18823 (setq beg (funcall skip-blanks (region-beginning))
18824 end (copy-marker (save-excursion
18825 (goto-char (region-end))
18826 (if (bolp) (point) (point-at-eol)))))
18827 (setq beg (funcall skip-blanks (point-at-bol))
18828 end (copy-marker (point-at-eol))))
18829 ;; Ensure inline tasks don't count as headings.
18830 (org-with-limited-levels
18831 (save-excursion
18832 (goto-char beg)
18833 (cond
18834 ;; Case 1. Started at an heading: de-star headings.
18835 ((org-at-heading-p)
18836 (while (< (point) end)
18837 (when (org-at-heading-p t)
18838 (looking-at org-outline-regexp) (replace-match ""))
18839 (forward-line)))
18840 ;; Case 2. Started at an item: change items into headlines.
18841 ;; One star will be added by `org-list-to-subtree'.
18842 ((org-at-item-p)
18843 (let* ((stars (make-string
18844 (if nstars
18845 ;; subtract the star that will be added again by
18846 ;; `org-list-to-subtree'
18847 (1- (prefix-numeric-value current-prefix-arg))
18848 (or (org-current-level) 0))
18849 ?*))
18850 (add-stars
18851 (cond (nstars "") ; stars from prefix only
18852 ((equal stars "") "") ; before first heading
18853 (org-odd-levels-only "*") ; inside heading, odd
18854 (t "")))) ; inside heading, oddeven
18855 (while (< (point) end)
18856 (when (org-at-item-p)
18857 ;; Pay attention to cases when region ends before list.
18858 (let* ((struct (org-list-struct))
18859 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18860 (save-restriction
18861 (narrow-to-region (point) list-end)
18862 (insert
18863 (org-list-to-subtree
18864 (org-list-parse-list t)
18865 '(:istart (concat stars add-stars (funcall get-stars depth))
18866 :icount (concat stars add-stars (funcall get-stars depth))))))))
18867 (forward-line))))
18868 ;; Case 3. Started at normal text: make every line an heading,
18869 ;; skipping headlines and items.
18870 (t (let* ((stars (make-string
18871 (if nstars
18872 (prefix-numeric-value current-prefix-arg)
18873 (or (org-current-level) 0))
18874 ?*))
18875 (add-stars
18876 (cond (nstars "") ; stars from prefix only
18877 ((equal stars "") "*") ; before first heading
18878 (org-odd-levels-only "**") ; inside heading, odd
18879 (t "*"))) ; inside heading, oddeven
18880 (rpl (concat stars add-stars " ")))
18881 (while (< (point) end)
18882 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18883 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18884 (replace-match (concat rpl (match-string 2))))
18885 (forward-line)))))))))
18887 (defun org-meta-return (&optional arg)
18888 "Insert a new heading or wrap a region in a table.
18889 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18890 See the individual commands for more information."
18891 (interactive "P")
18892 (cond
18893 ((run-hook-with-args-until-success 'org-metareturn-hook))
18894 ((org-at-table-p)
18895 (call-interactively 'org-table-wrap-region))
18896 (t (call-interactively 'org-insert-heading))))
18898 ;;; Menu entries
18900 ;; Define the Org-mode menus
18901 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18902 '("Tbl"
18903 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18904 ["Next Field" org-cycle (org-at-table-p)]
18905 ["Previous Field" org-shifttab (org-at-table-p)]
18906 ["Next Row" org-return (org-at-table-p)]
18907 "--"
18908 ["Blank Field" org-table-blank-field (org-at-table-p)]
18909 ["Edit Field" org-table-edit-field (org-at-table-p)]
18910 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18911 "--"
18912 ("Column"
18913 ["Move Column Left" org-metaleft (org-at-table-p)]
18914 ["Move Column Right" org-metaright (org-at-table-p)]
18915 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18916 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18917 ("Row"
18918 ["Move Row Up" org-metaup (org-at-table-p)]
18919 ["Move Row Down" org-metadown (org-at-table-p)]
18920 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18921 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18922 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18923 "--"
18924 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18925 ("Rectangle"
18926 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18927 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18928 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18929 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18930 "--"
18931 ("Calculate"
18932 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18933 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18934 ["Edit Formulas" org-edit-special (org-at-table-p)]
18935 "--"
18936 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18937 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18938 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18939 "--"
18940 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18941 "--"
18942 ["Sum Column/Rectangle" org-table-sum
18943 (or (org-at-table-p) (org-region-active-p))]
18944 ["Which Column?" org-table-current-column (org-at-table-p)])
18945 ["Debug Formulas"
18946 org-table-toggle-formula-debugger
18947 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18948 ["Show Col/Row Numbers"
18949 org-table-toggle-coordinate-overlays
18950 :style toggle
18951 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18952 "--"
18953 ["Create" org-table-create (and (not (org-at-table-p))
18954 org-enable-table-editor)]
18955 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18956 ["Import from File" org-table-import (not (org-at-table-p))]
18957 ["Export to File" org-table-export (org-at-table-p)]
18958 "--"
18959 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18961 (easy-menu-define org-org-menu org-mode-map "Org menu"
18962 '("Org"
18963 ("Show/Hide"
18964 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18965 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18966 ["Sparse Tree..." org-sparse-tree t]
18967 ["Reveal Context" org-reveal t]
18968 ["Show All" show-all t]
18969 "--"
18970 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18971 "--"
18972 ["New Heading" org-insert-heading t]
18973 ("Navigate Headings"
18974 ["Up" outline-up-heading t]
18975 ["Next" outline-next-visible-heading t]
18976 ["Previous" outline-previous-visible-heading t]
18977 ["Next Same Level" outline-forward-same-level t]
18978 ["Previous Same Level" outline-backward-same-level t]
18979 "--"
18980 ["Jump" org-goto t])
18981 ("Edit Structure"
18982 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18983 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18984 "--"
18985 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18986 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18987 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18988 "--"
18989 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18990 "--"
18991 ["Copy visible text" org-copy-visible t]
18992 "--"
18993 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18994 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18995 ["Demote Heading" org-metaright (not (org-at-table-p))]
18996 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18997 "--"
18998 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18999 "--"
19000 ["Convert to odd levels" org-convert-to-odd-levels t]
19001 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19002 ("Editing"
19003 ["Emphasis..." org-emphasize t]
19004 ["Edit Source Example" org-edit-special t]
19005 "--"
19006 ["Footnote new/jump" org-footnote-action t]
19007 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19008 ("Archive"
19009 ["Archive (default method)" org-archive-subtree-default t]
19010 "--"
19011 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19012 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19013 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19015 "--"
19016 ("Hyperlinks"
19017 ["Store Link (Global)" org-store-link t]
19018 ["Find existing link to here" org-occur-link-in-agenda-files t]
19019 ["Insert Link" org-insert-link t]
19020 ["Follow Link" org-open-at-point t]
19021 "--"
19022 ["Next link" org-next-link t]
19023 ["Previous link" org-previous-link t]
19024 "--"
19025 ["Descriptive Links"
19026 org-toggle-link-display
19027 :style radio
19028 :selected org-descriptive-links
19030 ["Literal Links"
19031 org-toggle-link-display
19032 :style radio
19033 :selected (not org-descriptive-links)])
19034 "--"
19035 ("TODO Lists"
19036 ["TODO/DONE/-" org-todo t]
19037 ("Select keyword"
19038 ["Next keyword" org-shiftright (org-at-heading-p)]
19039 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19040 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19041 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19042 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19043 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19044 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19045 "--"
19046 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19047 :selected org-enforce-todo-dependencies :style toggle :active t]
19048 "Settings for tree at point"
19049 ["Do Children sequentially" org-toggle-ordered-property :style radio
19050 :selected (org-entry-get nil "ORDERED")
19051 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19052 ["Do Children parallel" org-toggle-ordered-property :style radio
19053 :selected (not (org-entry-get nil "ORDERED"))
19054 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19055 "--"
19056 ["Set Priority" org-priority t]
19057 ["Priority Up" org-shiftup t]
19058 ["Priority Down" org-shiftdown t]
19059 "--"
19060 ["Get news from all feeds" org-feed-update-all t]
19061 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19062 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19063 ("TAGS and Properties"
19064 ["Set Tags" org-set-tags-command t]
19065 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19066 "--"
19067 ["Set property" org-set-property t]
19068 ["Column view of properties" org-columns t]
19069 ["Insert Column View DBlock" org-insert-columns-dblock t])
19070 ("Dates and Scheduling"
19071 ["Timestamp" org-time-stamp t]
19072 ["Timestamp (inactive)" org-time-stamp-inactive t]
19073 ("Change Date"
19074 ["1 Day Later" org-shiftright t]
19075 ["1 Day Earlier" org-shiftleft t]
19076 ["1 ... Later" org-shiftup t]
19077 ["1 ... Earlier" org-shiftdown t])
19078 ["Compute Time Range" org-evaluate-time-range t]
19079 ["Schedule Item" org-schedule t]
19080 ["Deadline" org-deadline t]
19081 "--"
19082 ["Custom time format" org-toggle-time-stamp-overlays
19083 :style radio :selected org-display-custom-times]
19084 "--"
19085 ["Goto Calendar" org-goto-calendar t]
19086 ["Date from Calendar" org-date-from-calendar t]
19087 "--"
19088 ["Start/Restart Timer" org-timer-start t]
19089 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19090 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19091 ["Insert Timer String" org-timer t]
19092 ["Insert Timer Item" org-timer-item t])
19093 ("Logging work"
19094 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19095 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19096 ["Clock out" org-clock-out t]
19097 ["Clock cancel" org-clock-cancel t]
19098 "--"
19099 ["Mark as default task" org-clock-mark-default-task t]
19100 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19101 ["Goto running clock" org-clock-goto t]
19102 "--"
19103 ["Display times" org-clock-display t]
19104 ["Create clock table" org-clock-report t]
19105 "--"
19106 ["Record DONE time"
19107 (progn (setq org-log-done (not org-log-done))
19108 (message "Switching to %s will %s record a timestamp"
19109 (car org-done-keywords)
19110 (if org-log-done "automatically" "not")))
19111 :style toggle :selected org-log-done])
19112 "--"
19113 ["Agenda Command..." org-agenda t]
19114 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19115 ("File List for Agenda")
19116 ("Special views current file"
19117 ["TODO Tree" org-show-todo-tree t]
19118 ["Check Deadlines" org-check-deadlines t]
19119 ["Timeline" org-timeline t]
19120 ["Tags/Property tree" org-match-sparse-tree t])
19121 "--"
19122 ["Export/Publish..." org-export t]
19123 ("LaTeX"
19124 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19125 :selected org-cdlatex-mode]
19126 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19127 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19128 ["Modify math symbol" org-cdlatex-math-modify
19129 (org-inside-LaTeX-fragment-p)]
19130 ["Insert citation" org-reftex-citation t]
19131 "--"
19132 ["Template for BEAMER" (progn (require 'org-beamer)
19133 (org-insert-beamer-options-template)) t])
19134 "--"
19135 ("MobileOrg"
19136 ["Push Files and Views" org-mobile-push t]
19137 ["Get Captured and Flagged" org-mobile-pull t]
19138 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19139 "--"
19140 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19141 "--"
19142 ("Documentation"
19143 ["Show Version" org-version t]
19144 ["Info Documentation" org-info t])
19145 ("Customize"
19146 ["Browse Org Group" org-customize t]
19147 "--"
19148 ["Expand This Menu" org-create-customize-menu
19149 (fboundp 'customize-menu-create)])
19150 ["Send bug report" org-submit-bug-report t]
19151 "--"
19152 ("Refresh/Reload"
19153 ["Refresh setup current buffer" org-mode-restart t]
19154 ["Reload Org (after update)" org-reload t]
19155 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19158 (defun org-info (&optional node)
19159 "Read documentation for Org-mode in the info system.
19160 With optional NODE, go directly to that node."
19161 (interactive)
19162 (info (format "(org)%s" (or node ""))))
19164 ;;;###autoload
19165 (defun org-submit-bug-report ()
19166 "Submit a bug report on Org-mode via mail.
19168 Don't hesitate to report any problems or inaccurate documentation.
19170 If you don't have setup sending mail from (X)Emacs, please copy the
19171 output buffer into your mail program, as it gives us important
19172 information about your Org-mode version and configuration."
19173 (interactive)
19174 (require 'reporter)
19175 (org-load-modules-maybe)
19176 (org-require-autoloaded-modules)
19177 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19178 (reporter-submit-bug-report
19179 "emacs-orgmode@gnu.org"
19180 (org-version)
19181 (let (list)
19182 (save-window-excursion
19183 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19184 (delete-other-windows)
19185 (erase-buffer)
19186 (insert "You are about to submit a bug report to the Org-mode mailing list.
19188 We would like to add your full Org-mode and Outline configuration to the
19189 bug report. This greatly simplifies the work of the maintainer and
19190 other experts on the mailing list.
19192 HOWEVER, some variables you have customized may contain private
19193 information. The names of customers, colleagues, or friends, might
19194 appear in the form of file names, tags, todo states, or search strings.
19195 If you answer yes to the prompt, you might want to check and remove
19196 such private information before sending the email.")
19197 (add-text-properties (point-min) (point-max) '(face org-warning))
19198 (when (yes-or-no-p "Include your Org-mode configuration ")
19199 (mapatoms
19200 (lambda (v)
19201 (and (boundp v)
19202 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19203 (or (and (symbol-value v)
19204 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19205 (and
19206 (get v 'custom-type) (get v 'standard-value)
19207 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19208 (push v list)))))
19209 (kill-buffer (get-buffer "*Warn about privacy*"))
19210 list))
19211 nil nil
19212 "Remember to cover the basics, that is, what you expected to happen and
19213 what in fact did happen. You don't know how to make a good report? See
19215 http://orgmode.org/manual/Feedback.html#Feedback
19217 Your bug report will be posted to the Org-mode mailing list.
19218 ------------------------------------------------------------------------")
19219 (save-excursion
19220 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19221 (replace-match "\\1Bug: \\3 [\\2]")))))
19224 (defun org-install-agenda-files-menu ()
19225 (let ((bl (buffer-list)))
19226 (save-excursion
19227 (while bl
19228 (set-buffer (pop bl))
19229 (if (eq major-mode 'org-mode) (setq bl nil)))
19230 (when (eq major-mode 'org-mode)
19231 (easy-menu-change
19232 '("Org") "File List for Agenda"
19233 (append
19234 (list
19235 ["Edit File List" (org-edit-agenda-file-list) t]
19236 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19237 ["Remove Current File from List" org-remove-file t]
19238 ["Cycle through agenda files" org-cycle-agenda-files t]
19239 ["Occur in all agenda files" org-occur-in-agenda-files t]
19240 "--")
19241 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19243 ;;;; Documentation
19245 ;;;###autoload
19246 (defun org-require-autoloaded-modules ()
19247 (interactive)
19248 (mapc 'require
19249 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19250 org-docbook org-exp org-html org-icalendar
19251 org-id org-latex
19252 org-publish org-remember org-table
19253 org-timer org-xoxo)))
19255 ;;;###autoload
19256 (defun org-reload (&optional uncompiled)
19257 "Reload all org lisp files.
19258 With prefix arg UNCOMPILED, load the uncompiled versions."
19259 (interactive "P")
19260 (require 'find-func)
19261 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19262 (dir-org (file-name-directory (org-find-library-name "org")))
19263 (dir-org-contrib (ignore-errors
19264 (file-name-directory
19265 (org-find-library-name "org-contribdir"))))
19266 (babel-files
19267 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19268 (append (list nil "comint" "eval" "exp" "keys"
19269 "lob" "ref" "table" "tangle")
19270 (delq nil
19271 (mapcar
19272 (lambda (lang)
19273 (when (cdr lang) (symbol-name (car lang))))
19274 org-babel-load-languages)))))
19275 (files
19276 (append (directory-files dir-org t file-re)
19277 babel-files
19278 (and dir-org-contrib
19279 (directory-files dir-org-contrib t file-re))))
19280 (remove-re (concat (if (featurep 'xemacs)
19281 "org-colview" "org-colview-xemacs")
19282 "\\'")))
19283 (setq files (mapcar 'file-name-sans-extension files))
19284 (setq files (mapcar
19285 (lambda (x) (if (string-match remove-re x) nil x))
19286 files))
19287 (setq files (delq nil files))
19288 (mapc
19289 (lambda (f)
19290 (when (featurep (intern (file-name-nondirectory f)))
19291 (if (and (not uncompiled)
19292 (file-exists-p (concat f ".elc")))
19293 (load (concat f ".elc") nil nil t)
19294 (load (concat f ".el") nil nil t))))
19295 files))
19296 (org-version))
19298 ;;;###autoload
19299 (defun org-customize ()
19300 "Call the customize function with org as argument."
19301 (interactive)
19302 (org-load-modules-maybe)
19303 (org-require-autoloaded-modules)
19304 (customize-browse 'org))
19306 (defun org-create-customize-menu ()
19307 "Create a full customization menu for Org-mode, insert it into the menu."
19308 (interactive)
19309 (org-load-modules-maybe)
19310 (org-require-autoloaded-modules)
19311 (if (fboundp 'customize-menu-create)
19312 (progn
19313 (easy-menu-change
19314 '("Org") "Customize"
19315 `(["Browse Org group" org-customize t]
19316 "--"
19317 ,(customize-menu-create 'org)
19318 ["Set" Custom-set t]
19319 ["Save" Custom-save t]
19320 ["Reset to Current" Custom-reset-current t]
19321 ["Reset to Saved" Custom-reset-saved t]
19322 ["Reset to Standard Settings" Custom-reset-standard t]))
19323 (message "\"Org\"-menu now contains full customization menu"))
19324 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19326 ;;;; Miscellaneous stuff
19328 ;;; Generally useful functions
19330 (defun org-get-at-bol (property)
19331 "Get text property PROPERTY at beginning of line."
19332 (get-text-property (point-at-bol) property))
19334 (defun org-find-text-property-in-string (prop s)
19335 "Return the first non-nil value of property PROP in string S."
19336 (or (get-text-property 0 prop s)
19337 (get-text-property (or (next-single-property-change 0 prop s) 0)
19338 prop s)))
19340 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19341 "Display the given MESSAGE as a warning."
19342 (if (fboundp 'display-warning)
19343 (display-warning 'org message
19344 (if (featurep 'xemacs) 'warning :warning))
19345 (let ((buf (get-buffer-create "*Org warnings*")))
19346 (with-current-buffer buf
19347 (goto-char (point-max))
19348 (insert "Warning (Org): " message)
19349 (unless (bolp)
19350 (newline)))
19351 (display-buffer buf)
19352 (sit-for 0))))
19354 (defun org-eval (form)
19355 "Eval FORM and return result."
19356 (condition-case error
19357 (eval form)
19358 (error (format "%%![Error: %s]" error))))
19360 (defun org-in-clocktable-p ()
19361 "Check if the cursor is in a clocktable."
19362 (let ((pos (point)) start)
19363 (save-excursion
19364 (end-of-line 1)
19365 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19366 (setq start (match-beginning 0))
19367 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19368 (>= (match-end 0) pos)
19369 start))))
19371 (defun org-in-commented-line ()
19372 "Is point in a line starting with `#'?"
19373 (equal (char-after (point-at-bol)) ?#))
19375 (defun org-in-indented-comment-line ()
19376 "Is point in a line starting with `#' after some white space?"
19377 (save-excursion
19378 (save-match-data
19379 (goto-char (point-at-bol))
19380 (looking-at "[ \t]*#"))))
19382 (defun org-in-verbatim-emphasis ()
19383 (save-match-data
19384 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19386 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19387 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19388 (if (and marker (marker-buffer marker)
19389 (buffer-live-p (marker-buffer marker)))
19390 (progn
19391 (org-pop-to-buffer-same-window (marker-buffer marker))
19392 (if (or (> marker (point-max)) (< marker (point-min)))
19393 (widen))
19394 (goto-char marker)
19395 (org-show-context 'org-goto))
19396 (if bookmark
19397 (bookmark-jump bookmark)
19398 (error "Cannot find location"))))
19400 (defun org-quote-csv-field (s)
19401 "Quote field for inclusion in CSV material."
19402 (if (string-match "[\",]" s)
19403 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19406 (defun org-force-self-insert (N)
19407 "Needed to enforce self-insert under remapping."
19408 (interactive "p")
19409 (self-insert-command N))
19411 (defun org-string-width (s)
19412 "Compute width of string, ignoring invisible characters.
19413 This ignores character with invisibility property `org-link', and also
19414 characters with property `org-cwidth', because these will become invisible
19415 upon the next fontification round."
19416 (let (b l)
19417 (when (or (eq t buffer-invisibility-spec)
19418 (assq 'org-link buffer-invisibility-spec))
19419 (while (setq b (text-property-any 0 (length s)
19420 'invisible 'org-link s))
19421 (setq s (concat (substring s 0 b)
19422 (substring s (or (next-single-property-change
19423 b 'invisible s) (length s)))))))
19424 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19425 (setq s (concat (substring s 0 b)
19426 (substring s (or (next-single-property-change
19427 b 'org-cwidth s) (length s))))))
19428 (setq l (string-width s) b -1)
19429 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19430 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19433 (defun org-shorten-string (s maxlength)
19434 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19435 If the string is shorter or has length MAXLENGTH, just return the
19436 original string. If it is longer, the functions finds a space in the
19437 string, breaks this string off at that locations and adds three dots
19438 as ellipsis. Including the ellipsis, the string will not be longer
19439 than MAXLENGTH. If finding a good breaking point in the string does
19440 not work, the string is just chopped off in the middle of a word
19441 if necessary."
19442 (if (<= (length s) maxlength)
19444 (let* ((n (max (- maxlength 4) 1))
19445 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19446 (if (string-match re s)
19447 (concat (match-string 1 s) "...")
19448 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19450 (defun org-get-indentation (&optional line)
19451 "Get the indentation of the current line, interpreting tabs.
19452 When LINE is given, assume it represents a line and compute its indentation."
19453 (if line
19454 (if (string-match "^ *" (org-remove-tabs line))
19455 (match-end 0))
19456 (save-excursion
19457 (beginning-of-line 1)
19458 (skip-chars-forward " \t")
19459 (current-column))))
19461 (defun org-get-string-indentation (s)
19462 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19463 (let ((n -1) (i 0) (w tab-width) c)
19464 (catch 'exit
19465 (while (< (setq n (1+ n)) (length s))
19466 (setq c (aref s n))
19467 (cond ((= c ?\ ) (setq i (1+ i)))
19468 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19469 (t (throw 'exit t)))))
19472 (defun org-remove-tabs (s &optional width)
19473 "Replace tabulators in S with spaces.
19474 Assumes that s is a single line, starting in column 0."
19475 (setq width (or width tab-width))
19476 (while (string-match "\t" s)
19477 (setq s (replace-match
19478 (make-string
19479 (- (* width (/ (+ (match-beginning 0) width) width))
19480 (match-beginning 0)) ?\ )
19481 t t s)))
19484 (defun org-fix-indentation (line ind)
19485 "Fix indentation in LINE.
19486 IND is a cons cell with target and minimum indentation.
19487 If the current indentation in LINE is smaller than the minimum,
19488 leave it alone. If it is larger than ind, set it to the target."
19489 (let* ((l (org-remove-tabs line))
19490 (i (org-get-indentation l))
19491 (i1 (car ind)) (i2 (cdr ind)))
19492 (if (>= i i2) (setq l (substring line i2)))
19493 (if (> i1 0)
19494 (concat (make-string i1 ?\ ) l)
19495 l)))
19497 (defun org-remove-indentation (code &optional n)
19498 "Remove the maximum common indentation from the lines in CODE.
19499 N may optionally be the number of spaces to remove."
19500 (with-temp-buffer
19501 (insert code)
19502 (org-do-remove-indentation n)
19503 (buffer-string)))
19505 (defun org-do-remove-indentation (&optional n)
19506 "Remove the maximum common indentation from the buffer."
19507 (untabify (point-min) (point-max))
19508 (let ((min 10000) re)
19509 (if n
19510 (setq min n)
19511 (goto-char (point-min))
19512 (while (re-search-forward "^ *[^ \n]" nil t)
19513 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19514 (unless (or (= min 0) (= min 10000))
19515 (setq re (format "^ \\{%d\\}" min))
19516 (goto-char (point-min))
19517 (while (re-search-forward re nil t)
19518 (replace-match "")
19519 (end-of-line 1))
19520 min)))
19522 (defun org-fill-template (template alist)
19523 "Find each %key of ALIST in TEMPLATE and replace it."
19524 (let ((case-fold-search nil)
19525 entry key value)
19526 (setq alist (sort (copy-sequence alist)
19527 (lambda (a b) (< (length (car a)) (length (car b))))))
19528 (while (setq entry (pop alist))
19529 (setq template
19530 (replace-regexp-in-string
19531 (concat "%" (regexp-quote (car entry)))
19532 (cdr entry) template t t)))
19533 template))
19535 (defun org-base-buffer (buffer)
19536 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19537 (if (not buffer)
19538 buffer
19539 (or (buffer-base-buffer buffer)
19540 buffer)))
19542 (defun org-trim (s)
19543 "Remove whitespace at beginning and end of string."
19544 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19545 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19548 (defun org-wrap (string &optional width lines)
19549 "Wrap string to either a number of lines, or a width in characters.
19550 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19551 that costs. If there is a word longer than WIDTH, the text is actually
19552 wrapped to the length of that word.
19553 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19554 many lines, whatever width that takes.
19555 The return value is a list of lines, without newlines at the end."
19556 (let* ((words (org-split-string string "[ \t\n]+"))
19557 (maxword (apply 'max (mapcar 'org-string-width words)))
19558 w ll)
19559 (cond (width
19560 (org-do-wrap words (max maxword width)))
19561 (lines
19562 (setq w maxword)
19563 (setq ll (org-do-wrap words maxword))
19564 (if (<= (length ll) lines)
19566 (setq ll words)
19567 (while (> (length ll) lines)
19568 (setq w (1+ w))
19569 (setq ll (org-do-wrap words w)))
19570 ll))
19571 (t (error "Cannot wrap this")))))
19573 (defun org-do-wrap (words width)
19574 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19575 (let (lines line)
19576 (while words
19577 (setq line (pop words))
19578 (while (and words (< (+ (length line) (length (car words))) width))
19579 (setq line (concat line " " (pop words))))
19580 (setq lines (push line lines)))
19581 (nreverse lines)))
19583 (defun org-split-string (string &optional separators)
19584 "Splits STRING into substrings at SEPARATORS.
19585 No empty strings are returned if there are matches at the beginning
19586 and end of string."
19587 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19588 (start 0)
19589 notfirst
19590 (list nil))
19591 (while (and (string-match rexp string
19592 (if (and notfirst
19593 (= start (match-beginning 0))
19594 (< start (length string)))
19595 (1+ start) start))
19596 (< (match-beginning 0) (length string)))
19597 (setq notfirst t)
19598 (or (eq (match-beginning 0) 0)
19599 (and (eq (match-beginning 0) (match-end 0))
19600 (eq (match-beginning 0) start))
19601 (setq list
19602 (cons (substring string start (match-beginning 0))
19603 list)))
19604 (setq start (match-end 0)))
19605 (or (eq start (length string))
19606 (setq list
19607 (cons (substring string start)
19608 list)))
19609 (nreverse list)))
19611 (defun org-quote-vert (s)
19612 "Replace \"|\" with \"\\vert\"."
19613 (while (string-match "|" s)
19614 (setq s (replace-match "\\vert" t t s)))
19617 (defun org-uuidgen-p (s)
19618 "Is S an ID created by UUIDGEN?"
19619 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19621 (defun org-context ()
19622 "Return a list of contexts of the current cursor position.
19623 If several contexts apply, all are returned.
19624 Each context entry is a list with a symbol naming the context, and
19625 two positions indicating start and end of the context. Possible
19626 contexts are:
19628 :headline anywhere in a headline
19629 :headline-stars on the leading stars in a headline
19630 :todo-keyword on a TODO keyword (including DONE) in a headline
19631 :tags on the TAGS in a headline
19632 :priority on the priority cookie in a headline
19633 :item on the first line of a plain list item
19634 :item-bullet on the bullet/number of a plain list item
19635 :checkbox on the checkbox in a plain list item
19636 :table in an org-mode table
19637 :table-special on a special filed in a table
19638 :table-table in a table.el table
19639 :link on a hyperlink
19640 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19641 :target on a <<target>>
19642 :radio-target on a <<<radio-target>>>
19643 :latex-fragment on a LaTeX fragment
19644 :latex-preview on a LaTeX fragment with overlaid preview image
19646 This function expects the position to be visible because it uses font-lock
19647 faces as a help to recognize the following contexts: :table-special, :link,
19648 and :keyword."
19649 (let* ((f (get-text-property (point) 'face))
19650 (faces (if (listp f) f (list f)))
19651 (p (point)) clist o)
19652 ;; First the large context
19653 (cond
19654 ((org-at-heading-p t)
19655 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19656 (when (progn
19657 (beginning-of-line 1)
19658 (looking-at org-todo-line-tags-regexp))
19659 (push (org-point-in-group p 1 :headline-stars) clist)
19660 (push (org-point-in-group p 2 :todo-keyword) clist)
19661 (push (org-point-in-group p 4 :tags) clist))
19662 (goto-char p)
19663 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19664 (if (looking-at "\\[#[A-Z0-9]\\]")
19665 (push (org-point-in-group p 0 :priority) clist)))
19667 ((org-at-item-p)
19668 (push (org-point-in-group p 2 :item-bullet) clist)
19669 (push (list :item (point-at-bol)
19670 (save-excursion (org-end-of-item) (point)))
19671 clist)
19672 (and (org-at-item-checkbox-p)
19673 (push (org-point-in-group p 0 :checkbox) clist)))
19675 ((org-at-table-p)
19676 (push (list :table (org-table-begin) (org-table-end)) clist)
19677 (if (memq 'org-formula faces)
19678 (push (list :table-special
19679 (previous-single-property-change p 'face)
19680 (next-single-property-change p 'face)) clist)))
19681 ((org-at-table-p 'any)
19682 (push (list :table-table) clist)))
19683 (goto-char p)
19685 ;; Now the small context
19686 (cond
19687 ((org-at-timestamp-p)
19688 (push (org-point-in-group p 0 :timestamp) clist))
19689 ((memq 'org-link faces)
19690 (push (list :link
19691 (previous-single-property-change p 'face)
19692 (next-single-property-change p 'face)) clist))
19693 ((memq 'org-special-keyword faces)
19694 (push (list :keyword
19695 (previous-single-property-change p 'face)
19696 (next-single-property-change p 'face)) clist))
19697 ((org-at-target-p)
19698 (push (org-point-in-group p 0 :target) clist)
19699 (goto-char (1- (match-beginning 0)))
19700 (if (looking-at org-radio-target-regexp)
19701 (push (org-point-in-group p 0 :radio-target) clist))
19702 (goto-char p))
19703 ((setq o (car (delq nil
19704 (mapcar
19705 (lambda (x)
19706 (if (memq x org-latex-fragment-image-overlays) x))
19707 (overlays-at (point))))))
19708 (push (list :latex-fragment
19709 (overlay-start o) (overlay-end o)) clist)
19710 (push (list :latex-preview
19711 (overlay-start o) (overlay-end o)) clist))
19712 ((org-inside-LaTeX-fragment-p)
19713 ;; FIXME: positions wrong.
19714 (push (list :latex-fragment (point) (point)) clist)))
19716 (setq clist (nreverse (delq nil clist)))
19717 clist))
19719 ;; FIXME: Compare with at-regexp-p Do we need both?
19720 (defun org-in-regexp (re &optional nlines visually)
19721 "Check if point is inside a match of regexp.
19722 Normally only the current line is checked, but you can include NLINES extra
19723 lines both before and after point into the search.
19724 If VISUALLY is set, require that the cursor is not after the match but
19725 really on, so that the block visually is on the match."
19726 (catch 'exit
19727 (let ((pos (point))
19728 (eol (point-at-eol (+ 1 (or nlines 0))))
19729 (inc (if visually 1 0)))
19730 (save-excursion
19731 (beginning-of-line (- 1 (or nlines 0)))
19732 (while (re-search-forward re eol t)
19733 (if (and (<= (match-beginning 0) pos)
19734 (>= (+ inc (match-end 0)) pos))
19735 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19737 (defun org-at-regexp-p (regexp)
19738 "Is point inside a match of REGEXP in the current line?"
19739 (catch 'exit
19740 (save-excursion
19741 (let ((pos (point)) (end (point-at-eol)))
19742 (beginning-of-line 1)
19743 (while (re-search-forward regexp end t)
19744 (if (and (<= (match-beginning 0) pos)
19745 (>= (match-end 0) pos))
19746 (throw 'exit t)))
19747 nil))))
19749 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19750 "Non-nil when point is between matches of START-RE and END-RE.
19752 Also return a non-nil value when point is on one of the matches.
19754 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19755 buffer positions. Default values are the positions of headlines
19756 surrounding the point.
19758 The functions returns a cons cell whose car (resp. cdr) is the
19759 position before START-RE (resp. after END-RE)."
19760 (save-match-data
19761 (let ((pos (point))
19762 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19763 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19764 beg end)
19765 (save-excursion
19766 ;; Point is on a block when on START-RE or if START-RE can be
19767 ;; found before it...
19768 (and (or (org-at-regexp-p start-re)
19769 (re-search-backward start-re limit-up t))
19770 (setq beg (match-beginning 0))
19771 ;; ... and END-RE after it...
19772 (goto-char (match-end 0))
19773 (re-search-forward end-re limit-down t)
19774 (> (setq end (match-end 0)) pos)
19775 ;; ... without another START-RE in-between.
19776 (goto-char (match-beginning 0))
19777 (not (re-search-backward start-re (1+ beg) t))
19778 ;; Return value.
19779 (cons beg end))))))
19781 (defun org-in-block-p (names)
19782 "Non-nil when point belongs to a block whose name belongs to NAMES.
19784 NAMES is a list of strings containing names of blocks.
19786 Return first block name matched, or nil. Beware that in case of
19787 nested blocks, the returned name may not belong to the closest
19788 block from point."
19789 (save-match-data
19790 (catch 'exit
19791 (let ((case-fold-search t)
19792 (lim-up (save-excursion (outline-previous-heading)))
19793 (lim-down (save-excursion (outline-next-heading))))
19794 (mapc (lambda (name)
19795 (let ((n (regexp-quote name)))
19796 (when (org-between-regexps-p
19797 (concat "^[ \t]*#\\+begin_" n)
19798 (concat "^[ \t]*#\\+end_" n)
19799 lim-up lim-down)
19800 (throw 'exit n))))
19801 names))
19802 nil)))
19804 (defun org-occur-in-agenda-files (regexp &optional nlines)
19805 "Call `multi-occur' with buffers for all agenda files."
19806 (interactive "sOrg-files matching: \np")
19807 (let* ((files (org-agenda-files))
19808 (tnames (mapcar 'file-truename files))
19809 (extra org-agenda-text-search-extra-files)
19811 (when (eq (car extra) 'agenda-archives)
19812 (setq extra (cdr extra))
19813 (setq files (org-add-archive-files files)))
19814 (while (setq f (pop extra))
19815 (unless (member (file-truename f) tnames)
19816 (add-to-list 'files f 'append)
19817 (add-to-list 'tnames (file-truename f) 'append)))
19818 (multi-occur
19819 (mapcar (lambda (x)
19820 (with-current-buffer
19821 (or (get-file-buffer x) (find-file-noselect x))
19822 (widen)
19823 (current-buffer)))
19824 files)
19825 regexp)))
19827 (if (boundp 'occur-mode-find-occurrence-hook)
19828 ;; Emacs 23
19829 (add-hook 'occur-mode-find-occurrence-hook
19830 (lambda ()
19831 (when (eq major-mode 'org-mode)
19832 (org-reveal))))
19833 ;; Emacs 22
19834 (defadvice occur-mode-goto-occurrence
19835 (after org-occur-reveal activate)
19836 (and (eq major-mode 'org-mode) (org-reveal)))
19837 (defadvice occur-mode-goto-occurrence-other-window
19838 (after org-occur-reveal activate)
19839 (and (eq major-mode 'org-mode) (org-reveal)))
19840 (defadvice occur-mode-display-occurrence
19841 (after org-occur-reveal activate)
19842 (when (eq major-mode 'org-mode)
19843 (let ((pos (occur-mode-find-occurrence)))
19844 (with-current-buffer (marker-buffer pos)
19845 (save-excursion
19846 (goto-char pos)
19847 (org-reveal)))))))
19849 (defun org-occur-link-in-agenda-files ()
19850 "Create a link and search for it in the agendas.
19851 The link is not stored in `org-stored-links', it is just created
19852 for the search purpose."
19853 (interactive)
19854 (let ((link (condition-case nil
19855 (org-store-link nil)
19856 (error "Unable to create a link to here"))))
19857 (org-occur-in-agenda-files (regexp-quote link))))
19859 (defun org-uniquify (list)
19860 "Remove duplicate elements from LIST."
19861 (let (res)
19862 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19863 res))
19865 (defun org-delete-all (elts list)
19866 "Remove all elements in ELTS from LIST."
19867 (while elts
19868 (setq list (delete (pop elts) list)))
19869 list)
19871 (defun org-count (cl-item cl-seq)
19872 "Count the number of occurrences of ITEM in SEQ.
19873 Taken from `count' in cl-seq.el with all keyword arguments removed."
19874 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19875 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19876 (while (< cl-start cl-end)
19877 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19878 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19879 (setq cl-start (1+ cl-start)))
19880 cl-count))
19882 (defun org-remove-if (predicate seq)
19883 "Remove everything from SEQ that fulfills PREDICATE."
19884 (let (res e)
19885 (while seq
19886 (setq e (pop seq))
19887 (if (not (funcall predicate e)) (push e res)))
19888 (nreverse res)))
19890 (defun org-remove-if-not (predicate seq)
19891 "Remove everything from SEQ that does not fulfill PREDICATE."
19892 (let (res e)
19893 (while seq
19894 (setq e (pop seq))
19895 (if (funcall predicate e) (push e res)))
19896 (nreverse res)))
19898 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19899 "Reduce two-argument FUNCTION across SEQ.
19900 Taken from `reduce' in cl-seq.el with all keyword arguments but
19901 \":initial-value\" removed."
19902 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19903 (cadr (memq :initial-value cl-keys)))
19904 (cl-seq (pop cl-seq))
19905 (t (funcall cl-func)))))
19906 (while cl-seq
19907 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19908 cl-accum))
19910 (defun org-back-over-empty-lines ()
19911 "Move backwards over whitespace, to the beginning of the first empty line.
19912 Returns the number of empty lines passed."
19913 (let ((pos (point)))
19914 (if (cdr (assoc 'heading org-blank-before-new-entry))
19915 (skip-chars-backward " \t\n\r")
19916 (unless (eobp)
19917 (forward-line -1)))
19918 (beginning-of-line 2)
19919 (goto-char (min (point) pos))
19920 (count-lines (point) pos)))
19922 (defun org-skip-whitespace ()
19923 (skip-chars-forward " \t\n\r"))
19925 (defun org-point-in-group (point group &optional context)
19926 "Check if POINT is in match-group GROUP.
19927 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19928 match. If the match group does not exist or point is not inside it,
19929 return nil."
19930 (and (match-beginning group)
19931 (>= point (match-beginning group))
19932 (<= point (match-end group))
19933 (if context
19934 (list context (match-beginning group) (match-end group))
19935 t)))
19937 (defun org-switch-to-buffer-other-window (&rest args)
19938 "Switch to buffer in a second window on the current frame.
19939 In particular, do not allow pop-up frames.
19940 Returns the newly created buffer."
19941 (let (pop-up-frames special-display-buffer-names special-display-regexps
19942 special-display-function)
19943 (apply 'switch-to-buffer-other-window args)))
19945 (defun org-combine-plists (&rest plists)
19946 "Create a single property list from all plists in PLISTS.
19947 The process starts by copying the first list, and then setting properties
19948 from the other lists. Settings in the last list are the most significant
19949 ones and overrule settings in the other lists."
19950 (let ((rtn (copy-sequence (pop plists)))
19951 p v ls)
19952 (while plists
19953 (setq ls (pop plists))
19954 (while ls
19955 (setq p (pop ls) v (pop ls))
19956 (setq rtn (plist-put rtn p v))))
19957 rtn))
19959 (defun org-move-line-down (arg)
19960 "Move the current line down. With prefix argument, move it past ARG lines."
19961 (interactive "p")
19962 (let ((col (current-column))
19963 beg end pos)
19964 (beginning-of-line 1) (setq beg (point))
19965 (beginning-of-line 2) (setq end (point))
19966 (beginning-of-line (+ 1 arg))
19967 (setq pos (move-marker (make-marker) (point)))
19968 (insert (delete-and-extract-region beg end))
19969 (goto-char pos)
19970 (org-move-to-column col)))
19972 (defun org-move-line-up (arg)
19973 "Move the current line up. With prefix argument, move it past ARG lines."
19974 (interactive "p")
19975 (let ((col (current-column))
19976 beg end pos)
19977 (beginning-of-line 1) (setq beg (point))
19978 (beginning-of-line 2) (setq end (point))
19979 (beginning-of-line (- arg))
19980 (setq pos (move-marker (make-marker) (point)))
19981 (insert (delete-and-extract-region beg end))
19982 (goto-char pos)
19983 (org-move-to-column col)))
19985 (defun org-replace-escapes (string table)
19986 "Replace %-escapes in STRING with values in TABLE.
19987 TABLE is an association list with keys like \"%a\" and string values.
19988 The sequences in STRING may contain normal field width and padding information,
19989 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19990 so values can contain further %-escapes if they are define later in TABLE."
19991 (let ((tbl (copy-alist table))
19992 (case-fold-search nil)
19993 (pchg 0)
19994 e re rpl)
19995 (while (setq e (pop tbl))
19996 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19997 (when (and (cdr e) (string-match re (cdr e)))
19998 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19999 (safe "SREF"))
20000 (add-text-properties 0 3 (list 'sref sref) safe)
20001 (setcdr e (replace-match safe t t (cdr e)))))
20002 (while (string-match re string)
20003 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20004 (cdr e)))
20005 (setq string (replace-match rpl t t string))))
20006 (while (setq pchg (next-property-change pchg string))
20007 (let ((sref (get-text-property pchg 'sref string)))
20008 (when (and sref (string-match "SREF" string pchg))
20009 (setq string (replace-match sref t t string)))))
20010 string))
20012 (defun org-sublist (list start end)
20013 "Return a section of LIST, from START to END.
20014 Counting starts at 1."
20015 (let (rtn (c start))
20016 (setq list (nthcdr (1- start) list))
20017 (while (and list (<= c end))
20018 (push (pop list) rtn)
20019 (setq c (1+ c)))
20020 (nreverse rtn)))
20022 (defun org-find-base-buffer-visiting (file)
20023 "Like `find-buffer-visiting' but always return the base buffer and
20024 not an indirect buffer."
20025 (let ((buf (or (get-file-buffer file)
20026 (find-buffer-visiting file))))
20027 (if buf
20028 (or (buffer-base-buffer buf) buf)
20029 nil)))
20031 (defun org-image-file-name-regexp (&optional extensions)
20032 "Return regexp matching the file names of images.
20033 If EXTENSIONS is given, only match these."
20034 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20035 (image-file-name-regexp)
20036 (let ((image-file-name-extensions
20037 (or extensions
20038 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20039 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20040 (concat "\\."
20041 (regexp-opt (nconc (mapcar 'upcase
20042 image-file-name-extensions)
20043 image-file-name-extensions)
20045 "\\'"))))
20047 (defun org-file-image-p (file &optional extensions)
20048 "Return non-nil if FILE is an image."
20049 (save-match-data
20050 (string-match (org-image-file-name-regexp extensions) file)))
20052 (defun org-get-cursor-date ()
20053 "Return the date at cursor in as a time.
20054 This works in the calendar and in the agenda, anywhere else it just
20055 returns the current time."
20056 (let (date day defd)
20057 (cond
20058 ((eq major-mode 'calendar-mode)
20059 (setq date (calendar-cursor-to-date)
20060 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20061 ((eq major-mode 'org-agenda-mode)
20062 (setq day (get-text-property (point) 'day))
20063 (if day
20064 (setq date (calendar-gregorian-from-absolute day)
20065 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20066 (nth 2 date))))))
20067 (or defd (current-time))))
20069 (defvar org-agenda-action-marker (make-marker)
20070 "Marker pointing to the entry for the next agenda action.")
20072 (defun org-mark-entry-for-agenda-action ()
20073 "Mark the current entry as target of an agenda action.
20074 Agenda actions are actions executed from the agenda with the key `k',
20075 which make use of the date at the cursor."
20076 (interactive)
20077 (move-marker org-agenda-action-marker
20078 (save-excursion (org-back-to-heading t) (point))
20079 (current-buffer))
20080 (message
20081 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20083 (defun org-mark-subtree ()
20084 "Mark the current subtree.
20085 This puts point at the start of the current subtree, and mark at the end.
20087 If point is in an inline task, mark that task instead."
20088 (interactive)
20089 (let ((inline-task-p
20090 (and (featurep 'org-inlinetask)
20091 (org-inlinetask-in-task-p)))
20092 (beg))
20093 ;; Get beginning of subtree
20094 (cond
20095 (inline-task-p (org-inlinetask-goto-beginning))
20096 ((org-at-heading-p) (beginning-of-line))
20097 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20098 (setq beg (point))
20099 ;; Get end of it
20100 (if inline-task-p
20101 (org-inlinetask-goto-end)
20102 (org-end-of-subtree))
20103 ;; Mark zone
20104 (push-mark (point) nil t)
20105 (goto-char beg)))
20107 ;;; Paragraph filling stuff.
20108 ;; We want this to be just right, so use the full arsenal.
20110 (defun org-indent-line-function ()
20111 "Indent line depending on context."
20112 (interactive)
20113 (let* ((pos (point))
20114 (itemp (org-at-item-p))
20115 (case-fold-search t)
20116 (org-drawer-regexp (or org-drawer-regexp "\000"))
20117 (inline-task-p (and (featurep 'org-inlinetask)
20118 (org-inlinetask-in-task-p)))
20119 (inline-re (and inline-task-p
20120 (org-inlinetask-outline-regexp)))
20121 column)
20122 (beginning-of-line 1)
20123 (cond
20124 ;; Comments
20125 ((looking-at "# ") (setq column 0))
20126 ;; Headings
20127 ((looking-at org-outline-regexp) (setq column 0))
20128 ;; Included files
20129 ((looking-at "#\\+include:") (setq column 0))
20130 ;; Footnote definition
20131 ((looking-at org-footnote-definition-re) (setq column 0))
20132 ;; Literal examples
20133 ((looking-at "[ \t]*:\\( \\|$\\)")
20134 (setq column (org-get-indentation))) ; do nothing
20135 ;; Lists
20136 ((ignore-errors (goto-char (org-in-item-p)))
20137 (setq column (if itemp
20138 (org-get-indentation)
20139 (org-list-item-body-column (point))))
20140 (goto-char pos))
20141 ;; Drawers
20142 ((and (looking-at "[ \t]*:END:")
20143 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20144 (save-excursion
20145 (goto-char (1- (match-beginning 1)))
20146 (setq column (current-column))))
20147 ;; Special blocks
20148 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20149 (save-excursion
20150 (re-search-backward
20151 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20152 (setq column (org-get-indentation (match-string 0))))
20153 ((and (not (looking-at "[ \t]*#\\+begin_"))
20154 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20155 (save-excursion
20156 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20157 (setq column
20158 (cond ((equal (downcase (match-string 1)) "src")
20159 ;; src blocks: let `org-edit-src-exit' handle them
20160 (org-get-indentation))
20161 ((equal (downcase (match-string 1)) "example")
20162 (max (org-get-indentation)
20163 (org-get-indentation (match-string 0))))
20165 (org-get-indentation (match-string 0))))))
20166 ;; This line has nothing special, look at the previous relevant
20167 ;; line to compute indentation
20169 (beginning-of-line 0)
20170 (while (and (not (bobp))
20171 (not (looking-at org-drawer-regexp))
20172 ;; When point started in an inline task, do not move
20173 ;; above task starting line.
20174 (not (and inline-task-p (looking-at inline-re)))
20175 ;; Skip drawers, blocks, empty lines, verbatim,
20176 ;; comments, tables, footnotes definitions, lists,
20177 ;; inline tasks.
20178 (or (and (looking-at "[ \t]*:END:")
20179 (re-search-backward org-drawer-regexp nil t))
20180 (and (looking-at "[ \t]*#\\+end_")
20181 (re-search-backward "[ \t]*#\\+begin_"nil t))
20182 (looking-at "[ \t]*[\n:#|]")
20183 (looking-at org-footnote-definition-re)
20184 (and (ignore-errors (goto-char (org-in-item-p)))
20185 (goto-char
20186 (org-list-get-top-point (org-list-struct))))
20187 (and (not inline-task-p)
20188 (featurep 'org-inlinetask)
20189 (org-inlinetask-in-task-p)
20190 (or (org-inlinetask-goto-beginning) t))))
20191 (beginning-of-line 0))
20192 (cond
20193 ;; There was an heading above.
20194 ((looking-at "\\*+[ \t]+")
20195 (if (not org-adapt-indentation)
20196 (setq column 0)
20197 (goto-char (match-end 0))
20198 (setq column (current-column))))
20199 ;; A drawer had started and is unfinished
20200 ((looking-at org-drawer-regexp)
20201 (goto-char (1- (match-beginning 1)))
20202 (setq column (current-column)))
20203 ;; Else, nothing noticeable found: get indentation and go on.
20204 (t (setq column (org-get-indentation))))))
20205 ;; Now apply indentation and move cursor accordingly
20206 (goto-char pos)
20207 (if (<= (current-column) (current-indentation))
20208 (org-indent-line-to column)
20209 (save-excursion (org-indent-line-to column)))
20210 ;; Special polishing for properties, see `org-property-format'
20211 (setq column (current-column))
20212 (beginning-of-line 1)
20213 (if (looking-at
20214 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20215 (replace-match (concat (match-string 1)
20216 (format org-property-format
20217 (match-string 2) (match-string 3)))
20218 t t))
20219 (org-move-to-column column)))
20221 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20222 "Variable to store copy of `adaptive-fill-regexp'.
20223 Since `adaptive-fill-regexp' is set to never match, we need to
20224 store a backup of its value before entering `org-mode' so that
20225 the functionality can be provided as a fall-back.")
20227 (defun org-set-autofill-regexps ()
20228 (interactive)
20229 ;; In the paragraph separator we include headlines, because filling
20230 ;; text in a line directly attached to a headline would otherwise
20231 ;; fill the headline as well.
20232 (org-set-local 'comment-start-skip "^#+[ \t]*")
20233 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20234 ;; The paragraph starter includes hand-formatted lists.
20235 (org-set-local
20236 'paragraph-start
20237 (concat
20238 "\f" "\\|"
20239 "[ ]*$" "\\|"
20240 org-outline-regexp "\\|"
20241 "[ \t]*#" "\\|"
20242 (org-item-re) "\\|"
20243 "[ \t]*[:|]" "\\|"
20244 "\\$\\$" "\\|"
20245 "\\\\\\(begin\\|end\\|[][]\\)"))
20246 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20247 ;; But only if the user has not turned off tables or fixed-width regions
20248 (org-set-local
20249 'auto-fill-inhibit-regexp
20250 (concat org-outline-regexp
20251 "\\|#\\+"
20252 "\\|[ \t]*" org-keyword-time-regexp
20253 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20254 (concat
20255 "\\|[ \t]*["
20256 (if org-enable-table-editor "|" "")
20257 (if org-enable-fixed-width-editor ":" "")
20258 "]"))))
20259 ;; We use our own fill-paragraph function, to make sure that tables
20260 ;; and fixed-width regions are not wrapped. That function will pass
20261 ;; through to `fill-paragraph' when appropriate.
20262 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20263 ;; Prevent auto-fill from inserting unwanted new items.
20264 (if (boundp 'fill-nobreak-predicate)
20265 (org-set-local 'fill-nobreak-predicate
20266 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20267 fill-nobreak-predicate
20268 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20269 ;; Adaptive filling: To get full control, first make sure that
20270 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20271 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20272 (org-set-local 'org-adaptive-fill-regexp-backup
20273 adaptive-fill-regexp))
20274 (org-set-local 'adaptive-fill-regexp "\000")
20275 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20276 (org-set-local 'adaptive-fill-function
20277 'org-adaptive-fill-function)
20278 (org-set-local
20279 'align-mode-rules-list
20280 '((org-in-buffer-settings
20281 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20282 (modes . '(org-mode))))))
20284 (defun org-fill-item-nobreak-p ()
20285 "Non-nil when a line break at point would insert a new item."
20286 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20288 (defun org-fill-paragraph (&optional justify)
20289 "Re-align a table, pass through to fill-paragraph if no table."
20290 (let ((table-p (org-at-table-p))
20291 (table.el-p (org-at-table.el-p))
20292 (itemp (org-in-item-p)))
20293 (cond ((and (equal (char-after (point-at-bol)) ?*)
20294 (save-excursion (goto-char (point-at-bol))
20295 (looking-at org-outline-regexp)))
20296 t) ; skip headlines
20297 (table.el-p t) ; skip table.el tables
20298 (table-p (org-table-align) t) ; align Org tables
20299 (itemp ; align text in items
20300 (let* ((struct (save-excursion (goto-char itemp)
20301 (org-list-struct)))
20302 (parents (org-list-parents-alist struct))
20303 (children (org-list-get-children itemp struct parents))
20304 beg end prev next prefix)
20305 ;; Determine in which part of item point is: before
20306 ;; first child, after last child, between two
20307 ;; sub-lists, or simply in item if there's no child.
20308 (cond
20309 ((not children)
20310 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20311 beg itemp
20312 end (org-list-get-item-end itemp struct)))
20313 ((< (point) (setq next (car children)))
20314 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20315 beg itemp
20316 end next))
20317 ((> (point) (setq prev (car (last children))))
20318 (setq beg (org-list-get-item-end prev struct)
20319 end (org-list-get-item-end itemp struct)
20320 prefix (save-excursion
20321 (goto-char beg)
20322 (skip-chars-forward " \t")
20323 (make-string (current-column) ?\ ))))
20324 (t (catch 'exit
20325 (while (setq next (pop children))
20326 (if (> (point) next)
20327 (setq prev next)
20328 (setq beg (org-list-get-item-end prev struct)
20329 end next
20330 prefix (save-excursion
20331 (goto-char beg)
20332 (skip-chars-forward " \t")
20333 (make-string (current-column) ?\ )))
20334 (throw 'exit nil))))))
20335 ;; Use `fill-paragraph' with buffer narrowed to item
20336 ;; without any child, and with our computed PREFIX.
20337 (flet ((fill-context-prefix (from to &optional flr) prefix))
20338 (save-restriction
20339 (narrow-to-region beg end)
20340 (save-excursion (fill-paragraph justify)))) t))
20341 ;; Special case where point is not in a list but is on
20342 ;; a paragraph adjacent to a list: make sure this paragraph
20343 ;; doesn't get merged with the end of the list by narrowing
20344 ;; buffer first.
20345 ((save-excursion (forward-paragraph -1)
20346 (setq itemp (org-in-item-p)))
20347 (let ((struct (save-excursion (goto-char itemp)
20348 (org-list-struct))))
20349 (save-restriction
20350 (narrow-to-region (org-list-get-bottom-point struct)
20351 (save-excursion (forward-paragraph 1)
20352 (point)))
20353 (fill-paragraph justify) t)))
20354 ;; Else simply call `fill-paragraph'.
20355 (t nil))))
20357 ;; For reference, this is the default value of adaptive-fill-regexp
20358 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20360 (defun org-adaptive-fill-function ()
20361 "Return a fill prefix for org-mode files."
20362 (let (itemp)
20363 (save-excursion
20364 (cond
20365 ;; Comment line
20366 ((looking-at "#[ \t]+")
20367 (match-string-no-properties 0))
20368 ;; Plain list item
20369 ((org-at-item-p)
20370 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20371 ;; Point is in a list after `backward-paragraph': original
20372 ;; point wasn't in the list, or filling would have been taken
20373 ;; care of by `org-auto-fill-function', but the list and the
20374 ;; real paragraph are not separated by a blank line. Thus, move
20375 ;; point after the list to go back to real paragraph and
20376 ;; determine fill-prefix.
20377 ((setq itemp (org-in-item-p))
20378 (goto-char itemp)
20379 (let* ((struct (org-list-struct))
20380 (bottom (org-list-get-bottom-point struct)))
20381 (goto-char bottom)
20382 (make-string (org-get-indentation) ?\ )))
20383 ;; Other text
20384 ((looking-at org-adaptive-fill-regexp-backup)
20385 (match-string-no-properties 0))))))
20387 (defun org-auto-fill-function ()
20388 "Auto-fill function."
20389 (let (itemp prefix)
20390 ;; When in a list, compute an appropriate fill-prefix and make
20391 ;; sure it will be used by `do-auto-fill'.
20392 (if (setq itemp (org-in-item-p))
20393 (progn
20394 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20395 (flet ((fill-context-prefix (from to &optional flr) prefix))
20396 (do-auto-fill)))
20397 ;; Else just use `do-auto-fill'.
20398 (do-auto-fill))))
20400 ;;; Other stuff.
20402 (defun org-toggle-fixed-width-section (arg)
20403 "Toggle the fixed-width export.
20404 If there is no active region, the QUOTE keyword at the current headline is
20405 inserted or removed. When present, it causes the text between this headline
20406 and the next to be exported as fixed-width text, and unmodified.
20407 If there is an active region, this command adds or removes a colon as the
20408 first character of this line. If the first character of a line is a colon,
20409 this line is also exported in fixed-width font."
20410 (interactive "P")
20411 (let* ((cc 0)
20412 (regionp (org-region-active-p))
20413 (beg (if regionp (region-beginning) (point)))
20414 (end (if regionp (region-end)))
20415 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20416 (case-fold-search nil)
20417 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20418 off)
20419 (if regionp
20420 (save-excursion
20421 (goto-char beg)
20422 (setq cc (current-column))
20423 (beginning-of-line 1)
20424 (setq off (looking-at re))
20425 (while (> nlines 0)
20426 (setq nlines (1- nlines))
20427 (beginning-of-line 1)
20428 (cond
20429 (arg
20430 (org-move-to-column cc t)
20431 (insert ": \n")
20432 (forward-line -1))
20433 ((and off (looking-at re))
20434 (replace-match "" t t nil 1))
20435 ((not off) (org-move-to-column cc t) (insert ": ")))
20436 (forward-line 1)))
20437 (save-excursion
20438 (org-back-to-heading)
20439 (cond
20440 ((looking-at (format org-heading-keyword-regexp-format
20441 org-quote-string))
20442 (goto-char (match-end 1))
20443 (looking-at (concat " +" org-quote-string))
20444 (replace-match "" t t)
20445 (when (eolp) (insert " ")))
20446 ((looking-at org-outline-regexp)
20447 (goto-char (match-end 0))
20448 (insert org-quote-string " ")))))))
20450 (defun org-reftex-citation ()
20451 "Use reftex-citation to insert a citation into the buffer.
20452 This looks for a line like
20454 #+BIBLIOGRAPHY: foo plain option:-d
20456 and derives from it that foo.bib is the bibliography file relevant
20457 for this document. It then installs the necessary environment for RefTeX
20458 to work in this buffer and calls `reftex-citation' to insert a citation
20459 into the buffer.
20461 Export of such citations to both LaTeX and HTML is handled by the contributed
20462 package org-exp-bibtex by Taru Karttunen."
20463 (interactive)
20464 (let ((reftex-docstruct-symbol 'rds)
20465 (reftex-cite-format "\\cite{%l}")
20466 rds bib)
20467 (save-excursion
20468 (save-restriction
20469 (widen)
20470 (let ((case-fold-search t)
20471 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20472 (if (not (save-excursion
20473 (or (re-search-forward re nil t)
20474 (re-search-backward re nil t))))
20475 (error "No bibliography defined in file")
20476 (setq bib (concat (match-string 1) ".bib")
20477 rds (list (list 'bib bib)))))))
20478 (call-interactively 'reftex-citation)))
20480 ;;;; Functions extending outline functionality
20482 (defun org-beginning-of-line (&optional arg)
20483 "Go to the beginning of the current line. If that is invisible, continue
20484 to a visible line beginning. This makes the function of C-a more intuitive.
20485 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20486 first attempt, and only move to after the tags when the cursor is already
20487 beyond the end of the headline."
20488 (interactive "P")
20489 (let ((pos (point))
20490 (special (if (consp org-special-ctrl-a/e)
20491 (car org-special-ctrl-a/e)
20492 org-special-ctrl-a/e))
20493 refpos)
20494 (if (org-bound-and-true-p line-move-visual)
20495 (beginning-of-visual-line 1)
20496 (beginning-of-line 1))
20497 (if (and arg (fboundp 'move-beginning-of-line))
20498 (call-interactively 'move-beginning-of-line)
20499 (if (bobp)
20501 (backward-char 1)
20502 (if (org-truely-invisible-p)
20503 (while (and (not (bobp)) (org-truely-invisible-p))
20504 (backward-char 1)
20505 (beginning-of-line 1))
20506 (forward-char 1))))
20507 (when special
20508 (cond
20509 ((and (looking-at org-complex-heading-regexp)
20510 (= (char-after (match-end 1)) ?\ ))
20511 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20512 (point-at-eol)))
20513 (goto-char
20514 (if (eq special t)
20515 (cond ((> pos refpos) refpos)
20516 ((= pos (point)) refpos)
20517 (t (point)))
20518 (cond ((> pos (point)) (point))
20519 ((not (eq last-command this-command)) (point))
20520 (t refpos)))))
20521 ((org-at-item-p)
20522 ;; Being at an item and not looking at an the item means point
20523 ;; was previously moved to beginning of a visual line, which
20524 ;; doesn't contain the item. Therefore, do nothing special,
20525 ;; just stay here.
20526 (when (looking-at org-list-full-item-re)
20527 ;; Set special position at first white space character after
20528 ;; bullet, and check-box, if any.
20529 (let ((after-bullet
20530 (let ((box (match-end 3)))
20531 (if (not box) (match-end 1)
20532 (let ((after (char-after box)))
20533 (if (and after (= after ? )) (1+ box) box))))))
20534 ;; Special case: Move point to special position when
20535 ;; currently after it or at beginning of line.
20536 (if (eq special t)
20537 (when (or (> pos after-bullet) (= (point) pos))
20538 (goto-char after-bullet))
20539 ;; Reversed case: Move point to special position when
20540 ;; point was already at beginning of line and command is
20541 ;; repeated.
20542 (when (and (= (point) pos) (eq last-command this-command))
20543 (goto-char after-bullet))))))))
20544 (org-no-warnings
20545 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20547 (defun org-end-of-line (&optional arg)
20548 "Go to the end of the line.
20549 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20550 first attempt, and only move to after the tags when the cursor is already
20551 beyond the end of the headline."
20552 (interactive "P")
20553 (let ((special (if (consp org-special-ctrl-a/e)
20554 (cdr org-special-ctrl-a/e)
20555 org-special-ctrl-a/e)))
20556 (cond
20557 ((or (not special) arg
20558 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20559 (call-interactively
20560 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20561 ((fboundp 'move-end-of-line) 'move-end-of-line)
20562 (t 'end-of-line))))
20563 ((org-at-heading-p)
20564 (let ((pos (point)))
20565 (beginning-of-line 1)
20566 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20567 (if (eq special t)
20568 (if (or (< pos (match-beginning 1))
20569 (= pos (match-end 0)))
20570 (goto-char (match-beginning 1))
20571 (goto-char (match-end 0)))
20572 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20573 (goto-char (match-end 0))
20574 (goto-char (match-beginning 1))))
20575 (call-interactively (if (fboundp 'move-end-of-line)
20576 'move-end-of-line
20577 'end-of-line)))))
20578 ((org-at-drawer-p)
20579 (move-end-of-line 1)
20580 (when (overlays-at (1- (point))) (backward-char 1)))
20581 ;; At an item: Move before any hidden text.
20582 (t (call-interactively
20583 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20584 ((fboundp 'move-end-of-line) 'move-end-of-line)
20585 (t 'end-of-line)))))
20586 (org-no-warnings
20587 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20589 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20590 (define-key org-mode-map "\C-e" 'org-end-of-line)
20592 (defun org-backward-sentence (&optional arg)
20593 "Go to beginning of sentence, or beginning of table field.
20594 This will call `backward-sentence' or `org-table-beginning-of-field',
20595 depending on context."
20596 (interactive "P")
20597 (cond
20598 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20599 (t (call-interactively 'backward-sentence))))
20601 (defun org-forward-sentence (&optional arg)
20602 "Go to end of sentence, or end of table field.
20603 This will call `forward-sentence' or `org-table-end-of-field',
20604 depending on context."
20605 (interactive "P")
20606 (cond
20607 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20608 (t (call-interactively 'forward-sentence))))
20610 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20611 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20613 (defun org-kill-line (&optional arg)
20614 "Kill line, to tags or end of line."
20615 (interactive "P")
20616 (cond
20617 ((or (not org-special-ctrl-k)
20618 (bolp)
20619 (not (org-at-heading-p)))
20620 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20621 org-ctrl-k-protect-subtree)
20622 (if (or (eq org-ctrl-k-protect-subtree 'error)
20623 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20624 (error "C-k aborted - would kill hidden subtree")))
20625 (call-interactively 'kill-line))
20626 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20627 (kill-region (point) (match-beginning 1))
20628 (org-set-tags nil t))
20629 (t (kill-region (point) (point-at-eol)))))
20631 (define-key org-mode-map "\C-k" 'org-kill-line)
20633 (defun org-yank (&optional arg)
20634 "Yank. If the kill is a subtree, treat it specially.
20635 This command will look at the current kill and check if is a single
20636 subtree, or a series of subtrees[1]. If it passes the test, and if the
20637 cursor is at the beginning of a line or after the stars of a currently
20638 empty headline, then the yank is handled specially. How exactly depends
20639 on the value of the following variables, both set by default.
20641 org-yank-folded-subtrees
20642 When set, the subtree(s) will be folded after insertion, but only
20643 if doing so would now swallow text after the yanked text.
20645 org-yank-adjusted-subtrees
20646 When set, the subtree will be promoted or demoted in order to
20647 fit into the local outline tree structure, which means that the level
20648 will be adjusted so that it becomes the smaller one of the two
20649 *visible* surrounding headings.
20651 Any prefix to this command will cause `yank' to be called directly with
20652 no special treatment. In particular, a simple \\[universal-argument] prefix \
20653 will just
20654 plainly yank the text as it is.
20656 \[1] The test checks if the first non-white line is a heading
20657 and if there are no other headings with fewer stars."
20658 (interactive "P")
20659 (org-yank-generic 'yank arg))
20661 (defun org-yank-generic (command arg)
20662 "Perform some yank-like command.
20664 This function implements the behavior described in the `org-yank'
20665 documentation. However, it has been generalized to work for any
20666 interactive command with similar behavior."
20668 ;; pretend to be command COMMAND
20669 (setq this-command command)
20671 (if arg
20672 (call-interactively command)
20674 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20675 (and (org-kill-is-subtree-p)
20676 (or (bolp)
20677 (and (looking-at "[ \t]*$")
20678 (string-match
20679 "\\`\\*+\\'"
20680 (buffer-substring (point-at-bol) (point)))))))
20681 swallowp)
20682 (cond
20683 ((and subtreep org-yank-folded-subtrees)
20684 (let ((beg (point))
20685 end)
20686 (if (and subtreep org-yank-adjusted-subtrees)
20687 (org-paste-subtree nil nil 'for-yank)
20688 (call-interactively command))
20690 (setq end (point))
20691 (goto-char beg)
20692 (when (and (bolp) subtreep
20693 (not (setq swallowp
20694 (org-yank-folding-would-swallow-text beg end))))
20695 (org-with-limited-levels
20696 (or (looking-at org-outline-regexp)
20697 (re-search-forward org-outline-regexp-bol end t))
20698 (while (and (< (point) end) (looking-at org-outline-regexp))
20699 (hide-subtree)
20700 (org-cycle-show-empty-lines 'folded)
20701 (condition-case nil
20702 (outline-forward-same-level 1)
20703 (error (goto-char end))))))
20704 (when swallowp
20705 (message
20706 "Inserted text not folded because that would swallow text"))
20708 (goto-char end)
20709 (skip-chars-forward " \t\n\r")
20710 (beginning-of-line 1)
20711 (push-mark beg 'nomsg)))
20712 ((and subtreep org-yank-adjusted-subtrees)
20713 (let ((beg (point-at-bol)))
20714 (org-paste-subtree nil nil 'for-yank)
20715 (push-mark beg 'nomsg)))
20717 (call-interactively command))))))
20719 (defun org-yank-folding-would-swallow-text (beg end)
20720 "Would hide-subtree at BEG swallow any text after END?"
20721 (let (level)
20722 (org-with-limited-levels
20723 (save-excursion
20724 (goto-char beg)
20725 (when (or (looking-at org-outline-regexp)
20726 (re-search-forward org-outline-regexp-bol end t))
20727 (setq level (org-outline-level)))
20728 (goto-char end)
20729 (skip-chars-forward " \t\r\n\v\f")
20730 (if (or (eobp)
20731 (and (bolp) (looking-at org-outline-regexp)
20732 (<= (org-outline-level) level)))
20733 nil ; Nothing would be swallowed
20734 t))))) ; something would swallow
20736 (define-key org-mode-map "\C-y" 'org-yank)
20738 (defun org-truely-invisible-p ()
20739 "Check if point is at a character currently not visible.
20740 This version does not only check the character property, but also
20741 `visible-mode'."
20742 ;; Early versions of noutline don't have `outline-invisible-p'.
20743 (if (org-bound-and-true-p visible-mode)
20745 (outline-invisible-p)))
20747 (defun org-invisible-p2 ()
20748 "Check if point is at a character currently not visible."
20749 (save-excursion
20750 (if (and (eolp) (not (bobp))) (backward-char 1))
20751 ;; Early versions of noutline don't have `outline-invisible-p'.
20752 (outline-invisible-p)))
20754 (defun org-back-to-heading (&optional invisible-ok)
20755 "Call `outline-back-to-heading', but provide a better error message."
20756 (condition-case nil
20757 (outline-back-to-heading invisible-ok)
20758 (error (error "Before first headline at position %d in buffer %s"
20759 (point) (current-buffer)))))
20761 (defun org-beginning-of-defun ()
20762 "Go to the beginning of the subtree, i.e. back to the heading."
20763 (org-back-to-heading))
20764 (defun org-end-of-defun ()
20765 "Go to the end of the subtree."
20766 (org-end-of-subtree nil t))
20768 (defun org-before-first-heading-p ()
20769 "Before first heading?"
20770 (save-excursion
20771 (end-of-line)
20772 (null (re-search-backward org-outline-regexp-bol nil t))))
20774 (defun org-at-heading-p (&optional ignored)
20775 (outline-on-heading-p t))
20776 ;; Compatibility alias with Org versions < 7.8.03
20777 (defalias 'org-on-heading-p 'org-at-heading-p)
20779 (defun org-at-drawer-p nil
20780 "Whether point is at a drawer."
20781 (save-excursion
20782 (move-beginning-of-line 1)
20783 (looking-at org-drawer-regexp)))
20785 (defun org-point-at-end-of-empty-headline ()
20786 "If point is at the end of an empty headline, return t, else nil.
20787 If the heading only contains a TODO keyword, it is still still considered
20788 empty."
20789 (and (looking-at "[ \t]*$")
20790 (when org-todo-line-regexp
20791 (save-excursion
20792 (beginning-of-line 1)
20793 (let ((case-fold-search nil))
20794 (looking-at org-todo-line-regexp)
20795 (string= (match-string 3) ""))))))
20797 (defun org-at-heading-or-item-p ()
20798 (or (org-at-heading-p) (org-at-item-p)))
20800 (defun org-at-target-p ()
20801 (or (org-in-regexp org-radio-target-regexp)
20802 (org-in-regexp org-target-regexp)))
20803 ;; Compatibility alias with Org versions < 7.8.03
20804 (defalias 'org-on-target-p 'org-at-target-p)
20806 (defun org-up-heading-all (arg)
20807 "Move to the heading line of which the present line is a subheading.
20808 This function considers both visible and invisible heading lines.
20809 With argument, move up ARG levels."
20810 (if (fboundp 'outline-up-heading-all)
20811 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20812 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20814 (defun org-up-heading-safe ()
20815 "Move to the heading line of which the present line is a subheading.
20816 This version will not throw an error. It will return the level of the
20817 headline found, or nil if no higher level is found.
20819 Also, this function will be a lot faster than `outline-up-heading',
20820 because it relies on stars being the outline starters. This can really
20821 make a significant difference in outlines with very many siblings."
20822 (let (start-level re)
20823 (org-back-to-heading t)
20824 (setq start-level (funcall outline-level))
20825 (if (equal start-level 1)
20827 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20828 (if (re-search-backward re nil t)
20829 (funcall outline-level)))))
20831 (defun org-first-sibling-p ()
20832 "Is this heading the first child of its parents?"
20833 (interactive)
20834 (let ((re org-outline-regexp-bol)
20835 level l)
20836 (unless (org-at-heading-p t)
20837 (error "Not at a heading"))
20838 (setq level (funcall outline-level))
20839 (save-excursion
20840 (if (not (re-search-backward re nil t))
20842 (setq l (funcall outline-level))
20843 (< l level)))))
20845 (defun org-goto-sibling (&optional previous)
20846 "Goto the next sibling, even if it is invisible.
20847 When PREVIOUS is set, go to the previous sibling instead. Returns t
20848 when a sibling was found. When none is found, return nil and don't
20849 move point."
20850 (let ((fun (if previous 're-search-backward 're-search-forward))
20851 (pos (point))
20852 (re org-outline-regexp-bol)
20853 level l)
20854 (when (condition-case nil (org-back-to-heading t) (error nil))
20855 (setq level (funcall outline-level))
20856 (catch 'exit
20857 (or previous (forward-char 1))
20858 (while (funcall fun re nil t)
20859 (setq l (funcall outline-level))
20860 (when (< l level) (goto-char pos) (throw 'exit nil))
20861 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20862 (goto-char pos)
20863 nil))))
20865 (defun org-show-siblings ()
20866 "Show all siblings of the current headline."
20867 (save-excursion
20868 (while (org-goto-sibling) (org-flag-heading nil)))
20869 (save-excursion
20870 (while (org-goto-sibling 'previous)
20871 (org-flag-heading nil))))
20873 (defun org-goto-first-child ()
20874 "Goto the first child, even if it is invisible.
20875 Return t when a child was found. Otherwise don't move point and
20876 return nil."
20877 (let (level (pos (point)) (re org-outline-regexp-bol))
20878 (when (condition-case nil (org-back-to-heading t) (error nil))
20879 (setq level (outline-level))
20880 (forward-char 1)
20881 (if (and (re-search-forward re nil t) (> (outline-level) level))
20882 (progn (goto-char (match-beginning 0)) t)
20883 (goto-char pos) nil))))
20885 (defun org-show-hidden-entry ()
20886 "Show an entry where even the heading is hidden."
20887 (save-excursion
20888 (org-show-entry)))
20890 (defun org-flag-heading (flag &optional entry)
20891 "Flag the current heading. FLAG non-nil means make invisible.
20892 When ENTRY is non-nil, show the entire entry."
20893 (save-excursion
20894 (org-back-to-heading t)
20895 ;; Check if we should show the entire entry
20896 (if entry
20897 (progn
20898 (org-show-entry)
20899 (save-excursion
20900 (and (outline-next-heading)
20901 (org-flag-heading nil))))
20902 (outline-flag-region (max (point-min) (1- (point)))
20903 (save-excursion (outline-end-of-heading) (point))
20904 flag))))
20906 (defun org-get-next-sibling ()
20907 "Move to next heading of the same level, and return point.
20908 If there is no such heading, return nil.
20909 This is like outline-next-sibling, but invisible headings are ok."
20910 (let ((level (funcall outline-level)))
20911 (outline-next-heading)
20912 (while (and (not (eobp)) (> (funcall outline-level) level))
20913 (outline-next-heading))
20914 (if (or (eobp) (< (funcall outline-level) level))
20916 (point))))
20918 (defun org-get-last-sibling ()
20919 "Move to previous heading of the same level, and return point.
20920 If there is no such heading, return nil."
20921 (let ((opoint (point))
20922 (level (funcall outline-level)))
20923 (outline-previous-heading)
20924 (when (and (/= (point) opoint) (outline-on-heading-p t))
20925 (while (and (> (funcall outline-level) level)
20926 (not (bobp)))
20927 (outline-previous-heading))
20928 (if (< (funcall outline-level) level)
20930 (point)))))
20932 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20933 ;; This contains an exact copy of the original function, but it uses
20934 ;; `org-back-to-heading', to make it work also in invisible
20935 ;; trees. And is uses an invisible-OK argument.
20936 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20937 ;; Furthermore, when used inside Org, finding the end of a large subtree
20938 ;; with many children and grandchildren etc, this can be much faster
20939 ;; than the outline version.
20940 (org-back-to-heading invisible-OK)
20941 (let ((first t)
20942 (level (funcall outline-level)))
20943 (if (and (eq major-mode 'org-mode) (< level 1000))
20944 ;; A true heading (not a plain list item), in Org-mode
20945 ;; This means we can easily find the end by looking
20946 ;; only for the right number of stars. Using a regexp to do
20947 ;; this is so much faster than using a Lisp loop.
20948 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20949 (forward-char 1)
20950 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20951 ;; something else, do it the slow way
20952 (while (and (not (eobp))
20953 (or first (> (funcall outline-level) level)))
20954 (setq first nil)
20955 (outline-next-heading)))
20956 (unless to-heading
20957 (if (memq (preceding-char) '(?\n ?\^M))
20958 (progn
20959 ;; Go to end of line before heading
20960 (forward-char -1)
20961 (if (memq (preceding-char) '(?\n ?\^M))
20962 ;; leave blank line before heading
20963 (forward-char -1))))))
20964 (point))
20966 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20967 "Use Org version in org-mode, for dramatic speed-up."
20968 (if (eq major-mode 'org-mode)
20969 (progn
20970 (org-end-of-subtree nil t)
20971 (unless (eobp) (backward-char 1)))
20972 ad-do-it))
20974 (defun org-end-of-meta-data-and-drawers ()
20975 "Jump to the first text after meta data and drawers in the current entry.
20976 This will move over empty lines, lines with planning time stamps,
20977 clocking lines, and drawers."
20978 (org-back-to-heading t)
20979 (let ((end (save-excursion (outline-next-heading) (point)))
20980 (re (concat "\\(" org-drawer-regexp "\\)"
20981 "\\|" "[ \t]*" org-keyword-time-regexp)))
20982 (forward-line 1)
20983 (while (re-search-forward re end t)
20984 (if (not (match-end 1))
20985 ;; empty or planning line
20986 (forward-line 1)
20987 ;; a drawer, find the end
20988 (re-search-forward "^[ \t]*:END:" end 'move)
20989 (forward-line 1)))
20990 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20991 (point)))
20993 (defun org-forward-same-level (arg &optional invisible-ok)
20994 "Move forward to the arg'th subheading at same level as this one.
20995 Stop at the first and last subheadings of a superior heading.
20996 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20997 it wil also look at invisible ones."
20998 (interactive "p")
20999 (org-back-to-heading invisible-ok)
21000 (org-at-heading-p)
21001 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21002 (re (format "^\\*\\{1,%d\\} " level))
21004 (forward-char 1)
21005 (while (> arg 0)
21006 (while (and (re-search-forward re nil 'move)
21007 (setq l (- (match-end 0) (match-beginning 0) 1))
21008 (= l level)
21009 (not invisible-ok)
21010 (progn (backward-char 1) (outline-invisible-p)))
21011 (if (< l level) (setq arg 1)))
21012 (setq arg (1- arg)))
21013 (beginning-of-line 1)))
21015 (defun org-backward-same-level (arg &optional invisible-ok)
21016 "Move backward to the arg'th subheading at same level as this one.
21017 Stop at the first and last subheadings of a superior heading."
21018 (interactive "p")
21019 (org-back-to-heading)
21020 (org-at-heading-p)
21021 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21022 (re (format "^\\*\\{1,%d\\} " level))
21024 (while (> arg 0)
21025 (while (and (re-search-backward re nil 'move)
21026 (setq l (- (match-end 0) (match-beginning 0) 1))
21027 (= l level)
21028 (not invisible-ok)
21029 (outline-invisible-p))
21030 (if (< l level) (setq arg 1)))
21031 (setq arg (1- arg)))))
21033 (defun org-show-subtree ()
21034 "Show everything after this heading at deeper levels."
21035 (interactive)
21036 (outline-flag-region
21037 (point)
21038 (save-excursion
21039 (org-end-of-subtree t t))
21040 nil))
21042 (defun org-show-entry ()
21043 "Show the body directly following this heading.
21044 Show the heading too, if it is currently invisible."
21045 (interactive)
21046 (save-excursion
21047 (condition-case nil
21048 (progn
21049 (org-back-to-heading t)
21050 (outline-flag-region
21051 (max (point-min) (1- (point)))
21052 (save-excursion
21053 (if (re-search-forward
21054 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21055 (match-beginning 1)
21056 (point-max)))
21057 nil)
21058 (org-cycle-hide-drawers 'children))
21059 (error nil))))
21061 (defun org-make-options-regexp (kwds &optional extra)
21062 "Make a regular expression for keyword lines."
21063 (concat
21065 "#?[ \t]*\\+\\("
21066 (mapconcat 'regexp-quote kwds "\\|")
21067 (if extra (concat "\\|" extra))
21068 "\\):[ \t]*"
21069 "\\(.*\\)"))
21071 ;; Make isearch reveal the necessary context
21072 (defun org-isearch-end ()
21073 "Reveal context after isearch exits."
21074 (when isearch-success ; only if search was successful
21075 (if (featurep 'xemacs)
21076 ;; Under XEmacs, the hook is run in the correct place,
21077 ;; we directly show the context.
21078 (org-show-context 'isearch)
21079 ;; In Emacs the hook runs *before* restoring the overlays.
21080 ;; So we have to use a one-time post-command-hook to do this.
21081 ;; (Emacs 22 has a special variable, see function `org-mode')
21082 (unless (and (boundp 'isearch-mode-end-hook-quit)
21083 isearch-mode-end-hook-quit)
21084 ;; Only when the isearch was not quitted.
21085 (org-add-hook 'post-command-hook 'org-isearch-post-command
21086 'append 'local)))))
21088 (defun org-isearch-post-command ()
21089 "Remove self from hook, and show context."
21090 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21091 (org-show-context 'isearch))
21094 ;;;; Integration with and fixes for other packages
21096 ;;; Imenu support
21098 (defvar org-imenu-markers nil
21099 "All markers currently used by Imenu.")
21100 (make-variable-buffer-local 'org-imenu-markers)
21102 (defun org-imenu-new-marker (&optional pos)
21103 "Return a new marker for use by Imenu, and remember the marker."
21104 (let ((m (make-marker)))
21105 (move-marker m (or pos (point)))
21106 (push m org-imenu-markers)
21109 (defun org-imenu-get-tree ()
21110 "Produce the index for Imenu."
21111 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21112 (setq org-imenu-markers nil)
21113 (let* ((n org-imenu-depth)
21114 (re (concat "^" (org-get-limited-outline-regexp)))
21115 (subs (make-vector (1+ n) nil))
21116 (last-level 0)
21117 m level head)
21118 (save-excursion
21119 (save-restriction
21120 (widen)
21121 (goto-char (point-max))
21122 (while (re-search-backward re nil t)
21123 (setq level (org-reduced-level (funcall outline-level)))
21124 (when (and (<= level n)
21125 (looking-at org-complex-heading-regexp))
21126 (setq head (org-link-display-format
21127 (org-match-string-no-properties 4))
21128 m (org-imenu-new-marker))
21129 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21130 (if (>= level last-level)
21131 (push (cons head m) (aref subs level))
21132 (push (cons head (aref subs (1+ level))) (aref subs level))
21133 (loop for i from (1+ level) to n do (aset subs i nil)))
21134 (setq last-level level)))))
21135 (aref subs 1)))
21137 (eval-after-load "imenu"
21138 '(progn
21139 (add-hook 'imenu-after-jump-hook
21140 (lambda ()
21141 (if (eq major-mode 'org-mode)
21142 (org-show-context 'org-goto))))))
21144 (defun org-link-display-format (link)
21145 "Replace a link with either the description, or the link target
21146 if no description is present"
21147 (save-match-data
21148 (if (string-match org-bracket-link-analytic-regexp link)
21149 (replace-match (if (match-end 5)
21150 (match-string 5 link)
21151 (concat (match-string 1 link)
21152 (match-string 3 link)))
21153 nil t link)
21154 link)))
21156 (defun org-toggle-link-display ()
21157 "Toggle the literal or descriptive display of links."
21158 (interactive)
21159 (if org-descriptive-links
21160 (progn (org-remove-from-invisibility-spec '(org-link))
21161 (org-restart-font-lock)
21162 (setq org-descriptive-links nil))
21163 (progn (add-to-invisibility-spec '(org-link))
21164 (org-restart-font-lock)
21165 (setq org-descriptive-links t))))
21167 ;; Speedbar support
21169 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21170 "Overlay marking the agenda restriction line in speedbar.")
21171 (overlay-put org-speedbar-restriction-lock-overlay
21172 'face 'org-agenda-restriction-lock)
21173 (overlay-put org-speedbar-restriction-lock-overlay
21174 'help-echo "Agendas are currently limited to this item.")
21175 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21177 (defun org-speedbar-set-agenda-restriction ()
21178 "Restrict future agenda commands to the location at point in speedbar.
21179 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21180 (interactive)
21181 (require 'org-agenda)
21182 (let (p m tp np dir txt)
21183 (cond
21184 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21185 'org-imenu t))
21186 (setq m (get-text-property p 'org-imenu-marker))
21187 (with-current-buffer (marker-buffer m)
21188 (goto-char m)
21189 (org-agenda-set-restriction-lock 'subtree)))
21190 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21191 'speedbar-function 'speedbar-find-file))
21192 (setq tp (previous-single-property-change
21193 (1+ p) 'speedbar-function)
21194 np (next-single-property-change
21195 tp 'speedbar-function)
21196 dir (speedbar-line-directory)
21197 txt (buffer-substring-no-properties (or tp (point-min))
21198 (or np (point-max))))
21199 (with-current-buffer (find-file-noselect
21200 (let ((default-directory dir))
21201 (expand-file-name txt)))
21202 (unless (eq major-mode 'org-mode)
21203 (error "Cannot restrict to non-Org-mode file"))
21204 (org-agenda-set-restriction-lock 'file)))
21205 (t (error "Don't know how to restrict Org-mode's agenda")))
21206 (move-overlay org-speedbar-restriction-lock-overlay
21207 (point-at-bol) (point-at-eol))
21208 (setq current-prefix-arg nil)
21209 (org-agenda-maybe-redo)))
21211 (eval-after-load "speedbar"
21212 '(progn
21213 (speedbar-add-supported-extension ".org")
21214 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21215 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21216 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21217 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21218 (add-hook 'speedbar-visiting-tag-hook
21219 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21221 ;;; Fixes and Hacks for problems with other packages
21223 ;; Make flyspell not check words in links, to not mess up our keymap
21224 (defun org-mode-flyspell-verify ()
21225 "Don't let flyspell put overlays at active buttons, or on
21226 {todo,all-time,additional-option-like}-keywords."
21227 (let ((pos (max (1- (point)) (point-min)))
21228 (word (thing-at-point 'word)))
21229 (and (not (get-text-property pos 'keymap))
21230 (not (get-text-property pos 'org-no-flyspell))
21231 (not (member word org-todo-keywords-1))
21232 (not (member word org-all-time-keywords))
21233 (not (member word org-additional-option-like-keywords)))))
21235 (defun org-remove-flyspell-overlays-in (beg end)
21236 "Remove flyspell overlays in region."
21237 (and (org-bound-and-true-p flyspell-mode)
21238 (fboundp 'flyspell-delete-region-overlays)
21239 (flyspell-delete-region-overlays beg end))
21240 (add-text-properties beg end '(org-no-flyspell t)))
21242 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21243 (eval-after-load "bookmark"
21244 '(if (boundp 'bookmark-after-jump-hook)
21245 ;; We can use the hook
21246 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21247 ;; Hook not available, use advice
21248 (defadvice bookmark-jump (after org-make-visible activate)
21249 "Make the position visible."
21250 (org-bookmark-jump-unhide))))
21252 ;; Make sure saveplace shows the location if it was hidden
21253 (eval-after-load "saveplace"
21254 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21255 "Make the position visible."
21256 (org-bookmark-jump-unhide)))
21258 ;; Make sure ecb shows the location if it was hidden
21259 (eval-after-load "ecb"
21260 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21261 "Make hierarchy visible when jumping into location from ECB tree buffer."
21262 (if (eq major-mode 'org-mode)
21263 (org-show-context))))
21265 (defun org-bookmark-jump-unhide ()
21266 "Unhide the current position, to show the bookmark location."
21267 (and (eq major-mode 'org-mode)
21268 (or (outline-invisible-p)
21269 (save-excursion (goto-char (max (point-min) (1- (point))))
21270 (outline-invisible-p)))
21271 (org-show-context 'bookmark-jump)))
21273 ;; Make session.el ignore our circular variable
21274 (eval-after-load "session"
21275 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21277 ;;;; Experimental code
21279 (defun org-closed-in-range ()
21280 "Sparse tree of items closed in a certain time range.
21281 Still experimental, may disappear in the future."
21282 (interactive)
21283 ;; Get the time interval from the user.
21284 (let* ((time1 (org-float-time
21285 (org-read-date nil 'to-time nil "Starting date: ")))
21286 (time2 (org-float-time
21287 (org-read-date nil 'to-time nil "End date:")))
21288 ;; callback function
21289 (callback (lambda ()
21290 (let ((time
21291 (org-float-time
21292 (apply 'encode-time
21293 (org-parse-time-string
21294 (match-string 1))))))
21295 ;; check if time in interval
21296 (and (>= time time1) (<= time time2))))))
21297 ;; make tree, check each match with the callback
21298 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21300 ;;;; Finish up
21302 (provide 'org)
21304 (run-hooks 'org-load-hook)
21306 ;;; org.el ends here