Manually revert back to commit e85080.
[org-mode.git] / lisp / org.el
blobfbfac28943938a4f826a9f850be8ce87beefaa2a
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 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.03
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Fortran" fortran)
168 (const :tag "Gnuplot" gnuplot)
169 (const :tag "Haskell" haskell)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "Latex" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :group 'org-id)
204 ;;; Version
206 (defconst org-version "7.8.03"
207 "The version number of the file org.el.")
209 ;;;###autoload
210 (defun org-version (&optional here)
211 "Show the org-mode version in the echo area.
212 With prefix arg HERE, insert it at point."
213 (interactive "P")
214 (let* ((origin default-directory)
215 (version org-version)
216 (git-version)
217 (dir (concat (file-name-directory (locate-library "org")) "../" )))
218 (when (and (file-exists-p (expand-file-name ".git" dir))
219 (executable-find "git"))
220 (unwind-protect
221 (progn
222 (cd dir)
223 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
224 (with-current-buffer "*Shell Command Output*"
225 (goto-char (point-min))
226 (setq git-version (buffer-substring (point) (point-at-eol))))
227 (subst-char-in-string ?- ?. git-version t)
228 (when (string-match "\\S-"
229 (shell-command-to-string
230 "git diff-index --name-only HEAD --"))
231 (setq git-version (concat git-version ".dirty")))
232 (setq version (concat version " (" git-version ")"))))
233 (cd origin)))
234 (setq version (format "Org-mode version %s" version))
235 (if here (insert version))
236 (message version)))
238 ;;; Compatibility constants
240 ;;; The custom variables
242 (defgroup org nil
243 "Outline-based notes management and organizer."
244 :tag "Org"
245 :group 'outlines
246 :group 'calendar)
248 (defcustom org-mode-hook nil
249 "Mode hook for Org-mode, run after the mode was turned on."
250 :group 'org
251 :type 'hook)
253 (defcustom org-load-hook nil
254 "Hook that is run after org.el has been loaded."
255 :group 'org
256 :type 'hook)
258 (defcustom org-log-buffer-setup-hook nil
259 "Hook that is run after an Org log buffer is created."
260 :group 'org
261 :type 'hook)
263 (defvar org-modules) ; defined below
264 (defvar org-modules-loaded nil
265 "Have the modules been loaded already?")
267 (defun org-load-modules-maybe (&optional force)
268 "Load all extensions listed in `org-modules'."
269 (when (or force (not org-modules-loaded))
270 (mapc (lambda (ext)
271 (condition-case nil (require ext)
272 (error (message "Problems while trying to load feature `%s'" ext))))
273 org-modules)
274 (setq org-modules-loaded t)))
276 (defun org-set-modules (var value)
277 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
278 (set var value)
279 (when (featurep 'org)
280 (org-load-modules-maybe 'force)))
282 (when (org-bound-and-true-p org-modules)
283 (let ((a (member 'org-infojs org-modules)))
284 (and a (setcar a 'org-jsinfo))))
286 (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)
287 "Modules that should always be loaded together with org.el.
288 If a description starts with <C>, the file is not part of Emacs
289 and loading it will require that you have downloaded and properly installed
290 the org-mode distribution.
292 You can also use this system to load external packages (i.e. neither Org
293 core modules, nor modules from the CONTRIB directory). Just add symbols
294 to the end of the list. If the package is called org-xyz.el, then you need
295 to add the symbol `xyz', and the package must have a call to
297 (provide 'org-xyz)"
298 :group 'org
299 :set 'org-set-modules
300 :type
301 '(set :greedy t
302 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
303 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
304 (const :tag " crypt: Encryption of subtrees" org-crypt)
305 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
306 (const :tag " docview: Links to doc-view buffers" org-docview)
307 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
308 (const :tag " id: Global IDs for identifying entries" org-id)
309 (const :tag " info: Links to Info nodes" org-info)
310 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
311 (const :tag " habit: Track your consistency with habits" org-habit)
312 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
313 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
314 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
315 (const :tag " mew Links to Mew folders/messages" org-mew)
316 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
317 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
318 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
319 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
320 (const :tag " vm: Links to VM folders/messages" org-vm)
321 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
322 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
323 (const :tag " mouse: Additional mouse support" org-mouse)
324 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
326 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
327 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
328 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
329 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
330 (const :tag "C collector: Collect properties into tables" org-collector)
331 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
332 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
333 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
334 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
335 (const :tag "C eval: Include command output as text" org-eval)
336 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
337 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
338 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
339 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
340 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
342 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
344 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
345 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
346 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
347 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
348 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
349 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
350 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
351 (const :tag "C mtags: Support for muse-like tags" org-mtags)
352 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
353 (const :tag "C registry: A registry for Org-mode links" org-registry)
354 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
355 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
356 (const :tag "C secretary: Team management with org-mode" org-secretary)
357 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
358 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
359 (const :tag "C track: Keep up with Org-mode development" org-track)
360 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
361 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
362 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
364 (defcustom org-support-shift-select nil
365 "Non-nil means make shift-cursor commands select text when possible.
367 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
368 start selecting a region, or enlarge regions started in this way.
369 In Org-mode, in special contexts, these same keys are used for
370 other purposes, important enough to compete with shift selection.
371 Org tries to balance these needs by supporting `shift-select-mode'
372 outside these special contexts, under control of this variable.
374 The default of this variable is nil, to avoid confusing behavior. Shifted
375 cursor keys will then execute Org commands in the following contexts:
376 - on a headline, changing TODO state (left/right) and priority (up/down)
377 - on a time stamp, changing the time
378 - in a plain list item, changing the bullet type
379 - in a property definition line, switching between allowed values
380 - in the BEGIN line of a clock table (changing the time block).
381 Outside these contexts, the commands will throw an error.
383 When this variable is t and the cursor is not in a special
384 context, Org-mode will support shift-selection for making and
385 enlarging regions. To make this more effective, the bullet
386 cycling will no longer happen anywhere in an item line, but only
387 if the cursor is exactly on the bullet.
389 If you set this variable to the symbol `always', then the keys
390 will not be special in headlines, property lines, and item lines,
391 to make shift selection work there as well. If this is what you
392 want, you can use the following alternative commands: `C-c C-t'
393 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
394 can be used to switch TODO sets, `C-c -' to cycle item bullet
395 types, and properties can be edited by hand or in column view.
397 However, when the cursor is on a timestamp, shift-cursor commands
398 will still edit the time stamp - this is just too good to give up.
400 XEmacs user should have this variable set to nil, because
401 `shift-select-mode' is in Emacs 23 or later only."
402 :group 'org
403 :type '(choice
404 (const :tag "Never" nil)
405 (const :tag "When outside special context" t)
406 (const :tag "Everywhere except timestamps" always)))
408 (defcustom org-loop-over-headlines-in-active-region nil
409 "Shall some commands act upon headlines in the active region?
411 When set to `t', some commands will be performed in all headlines
412 within the active region.
414 When set to `start-level', some commands will be performed in all
415 headlines within the active region, provided that these headlines
416 are of the same level than the first one.
418 When set to a string, those commands will be performed on the
419 matching headlines within the active region. Such string must be
420 a tags/property/todo match as it is used in the agenda tags view.
422 The list of commands is: `org-schedule', `org-deadline',
423 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
424 `org-archive-to-archive-sibling'. The archiving commands skip
425 already archived entries."
426 :type '(choice (const :tag "Don't loop" nil)
427 (const :tag "All headlines in active region" t)
428 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
429 (string :tag "Tags/Property/Todo matcher"))
430 :group 'org-todo
431 :group 'org-archive)
433 (defgroup org-startup nil
434 "Options concerning startup of Org-mode."
435 :tag "Org Startup"
436 :group 'org)
438 (defcustom org-startup-folded t
439 "Non-nil means entering Org-mode will switch to OVERVIEW.
440 This can also be configured on a per-file basis by adding one of
441 the following lines anywhere in the buffer:
443 #+STARTUP: fold (or `overview', this is equivalent)
444 #+STARTUP: nofold (or `showall', this is equivalent)
445 #+STARTUP: content
446 #+STARTUP: showeverything"
447 :group 'org-startup
448 :type '(choice
449 (const :tag "nofold: show all" nil)
450 (const :tag "fold: overview" t)
451 (const :tag "content: all headlines" content)
452 (const :tag "show everything, even drawers" showeverything)))
454 (defcustom org-startup-truncated t
455 "Non-nil means entering Org-mode will set `truncate-lines'.
456 This is useful since some lines containing links can be very long and
457 uninteresting. Also tables look terrible when wrapped."
458 :group 'org-startup
459 :type 'boolean)
461 (defcustom org-startup-indented nil
462 "Non-nil means turn on `org-indent-mode' on startup.
463 This can also be configured on a per-file basis by adding one of
464 the following lines anywhere in the buffer:
466 #+STARTUP: indent
467 #+STARTUP: noindent"
468 :group 'org-structure
469 :type '(choice
470 (const :tag "Not" nil)
471 (const :tag "Globally (slow on startup in large files)" t)))
473 (defcustom org-use-sub-superscripts t
474 "Non-nil means interpret \"_\" and \"^\" for export.
475 When this option is turned on, you can use TeX-like syntax for sub- and
476 superscripts. Several characters after \"_\" or \"^\" will be
477 considered as a single item - so grouping with {} is normally not
478 needed. For example, the following things will be parsed as single
479 sub- or superscripts.
481 10^24 or 10^tau several digits will be considered 1 item.
482 10^-12 or 10^-tau a leading sign with digits or a word
483 x^2-y^3 will be read as x^2 - y^3, because items are
484 terminated by almost any nonword/nondigit char.
485 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
487 Still, ambiguity is possible - so when in doubt use {} to enclose the
488 sub/superscript. If you set this variable to the symbol `{}',
489 the braces are *required* in order to trigger interpretations as
490 sub/superscript. This can be helpful in documents that need \"_\"
491 frequently in plain text.
493 Not all export backends support this, but HTML does.
495 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
496 :group 'org-startup
497 :group 'org-export-translation
498 :type '(choice
499 (const :tag "Always interpret" t)
500 (const :tag "Only with braces" {})
501 (const :tag "Never interpret" nil)))
503 (if (fboundp 'defvaralias)
504 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
507 (defcustom org-startup-with-beamer-mode nil
508 "Non-nil means turn on `org-beamer-mode' on startup.
509 This can also be configured on a per-file basis by adding one of
510 the following lines anywhere in the buffer:
512 #+STARTUP: beamer"
513 :group 'org-startup
514 :type 'boolean)
516 (defcustom org-startup-align-all-tables nil
517 "Non-nil means align all tables when visiting a file.
518 This is useful when the column width in tables is forced with <N> cookies
519 in table fields. Such tables will look correct only after the first re-align.
520 This can also be configured on a per-file basis by adding one of
521 the following lines anywhere in the buffer:
522 #+STARTUP: align
523 #+STARTUP: noalign"
524 :group 'org-startup
525 :type 'boolean)
527 (defcustom org-startup-with-inline-images nil
528 "Non-nil means show inline images when loading a new Org file.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: inlineimages
532 #+STARTUP: noinlineimages"
533 :group 'org-startup
534 :type 'boolean)
536 (defcustom org-insert-mode-line-in-empty-file nil
537 "Non-nil means insert the first line setting Org-mode in empty files.
538 When the function `org-mode' is called interactively in an empty file, this
539 normally means that the file name does not automatically trigger Org-mode.
540 To ensure that the file will always be in Org-mode in the future, a
541 line enforcing Org-mode will be inserted into the buffer, if this option
542 has been set."
543 :group 'org-startup
544 :type 'boolean)
546 (defcustom org-replace-disputed-keys nil
547 "Non-nil means use alternative key bindings for some keys.
548 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
549 These keys are also used by other packages like shift-selection-mode'
550 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
551 If you want to use Org-mode together with one of these other modes,
552 or more generally if you would like to move some Org-mode commands to
553 other keys, set this variable and configure the keys with the variable
554 `org-disputed-keys'.
556 This option is only relevant at load-time of Org-mode, and must be set
557 *before* org.el is loaded. Changing it requires a restart of Emacs to
558 become effective."
559 :group 'org-startup
560 :type 'boolean)
562 (defcustom org-use-extra-keys nil
563 "Non-nil means use extra key sequence definitions for certain commands.
564 This happens automatically if you run XEmacs or if `window-system'
565 is nil. This variable lets you do the same manually. You must
566 set it before loading org.
568 Example: on Carbon Emacs 22 running graphically, with an external
569 keyboard on a Powerbook, the default way of setting M-left might
570 not work for either Alt or ESC. Setting this variable will make
571 it work for ESC."
572 :group 'org-startup
573 :type 'boolean)
575 (if (fboundp 'defvaralias)
576 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
578 (defcustom org-disputed-keys
579 '(([(shift up)] . [(meta p)])
580 ([(shift down)] . [(meta n)])
581 ([(shift left)] . [(meta -)])
582 ([(shift right)] . [(meta +)])
583 ([(control shift right)] . [(meta shift +)])
584 ([(control shift left)] . [(meta shift -)]))
585 "Keys for which Org-mode and other modes compete.
586 This is an alist, cars are the default keys, second element specifies
587 the alternative to use when `org-replace-disputed-keys' is t.
589 Keys can be specified in any syntax supported by `define-key'.
590 The value of this option takes effect only at Org-mode's startup,
591 therefore you'll have to restart Emacs to apply it after changing."
592 :group 'org-startup
593 :type 'alist)
595 (defun org-key (key)
596 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
597 Or return the original if not disputed.
598 Also apply the translations defined in `org-xemacs-key-equivalents'."
599 (when org-replace-disputed-keys
600 (let* ((nkey (key-description key))
601 (x (org-find-if (lambda (x)
602 (equal (key-description (car x)) nkey))
603 org-disputed-keys)))
604 (setq key (if x (cdr x) key))))
605 (when (featurep 'xemacs)
606 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
607 key)
609 (defun org-find-if (predicate seq)
610 (catch 'exit
611 (while seq
612 (if (funcall predicate (car seq))
613 (throw 'exit (car seq))
614 (pop seq)))))
616 (defun org-defkey (keymap key def)
617 "Define a key, possibly translated, as returned by `org-key'."
618 (define-key keymap (org-key key) def))
620 (defcustom org-ellipsis nil
621 "The ellipsis to use in the Org-mode outline.
622 When nil, just use the standard three dots. When a string, use that instead,
623 When a face, use the standard 3 dots, but with the specified face.
624 The change affects only Org-mode (which will then use its own display table).
625 Changing this requires executing `M-x org-mode' in a buffer to become
626 effective."
627 :group 'org-startup
628 :type '(choice (const :tag "Default" nil)
629 (face :tag "Face" :value org-warning)
630 (string :tag "String" :value "...#")))
632 (defvar org-display-table nil
633 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
635 (defgroup org-keywords nil
636 "Keywords in Org-mode."
637 :tag "Org Keywords"
638 :group 'org)
640 (defcustom org-deadline-string "DEADLINE:"
641 "String to mark deadline entries.
642 A deadline is this string, followed by a time stamp. Should be a word,
643 terminated by a colon. You can insert a schedule keyword and
644 a timestamp with \\[org-deadline].
645 Changes become only effective after restarting Emacs."
646 :group 'org-keywords
647 :type 'string)
649 (defcustom org-scheduled-string "SCHEDULED:"
650 "String to mark scheduled TODO entries.
651 A schedule is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-schedule].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-closed-string "CLOSED:"
659 "String used as the prefix for timestamps logging closing a TODO entry."
660 :group 'org-keywords
661 :type 'string)
663 (defcustom org-clock-string "CLOCK:"
664 "String used as prefix for timestamps clocking work hours on an item."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-comment-string "COMMENT"
669 "Entries starting with this keyword will never be exported.
670 An entry can be toggled between COMMENT and normal with
671 \\[org-toggle-comment].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-quote-string "QUOTE"
677 "Entries starting with this keyword will be exported in fixed-width font.
678 Quoting applies only to the text in the entry following the headline, and does
679 not extend beyond the next headline, even if that is lower level.
680 An entry can be toggled between QUOTE and normal with
681 \\[org-toggle-fixed-width-section]."
682 :group 'org-keywords
683 :type 'string)
685 (defconst org-repeat-re
686 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
687 "Regular expression for specifying repeated events.
688 After a match, group 1 contains the repeat expression.")
690 (defgroup org-structure nil
691 "Options concerning the general structure of Org-mode files."
692 :tag "Org Structure"
693 :group 'org)
695 (defgroup org-reveal-location nil
696 "Options about how to make context of a location visible."
697 :tag "Org Reveal Location"
698 :group 'org-structure)
700 (defconst org-context-choice
701 '(choice
702 (const :tag "Always" t)
703 (const :tag "Never" nil)
704 (repeat :greedy t :tag "Individual contexts"
705 (cons
706 (choice :tag "Context"
707 (const agenda)
708 (const org-goto)
709 (const occur-tree)
710 (const tags-tree)
711 (const link-search)
712 (const mark-goto)
713 (const bookmark-jump)
714 (const isearch)
715 (const default))
716 (boolean))))
717 "Contexts for the reveal options.")
719 (defcustom org-show-hierarchy-above '((default . t))
720 "Non-nil means show full hierarchy when revealing a location.
721 Org-mode often shows locations in an org-mode file which might have
722 been invisible before. When this is set, the hierarchy of headings
723 above the exposed location is shown.
724 Turning this off for example for sparse trees makes them very compact.
725 Instead of t, this can also be an alist specifying this option for different
726 contexts. Valid contexts are
727 agenda when exposing an entry from the agenda
728 org-goto when using the command `org-goto' on key C-c C-j
729 occur-tree when using the command `org-occur' on key C-c /
730 tags-tree when constructing a sparse tree based on tags matches
731 link-search when exposing search matches associated with a link
732 mark-goto when exposing the jump goal of a mark
733 bookmark-jump when exposing a bookmark location
734 isearch when exiting from an incremental search
735 default default for all contexts not set explicitly"
736 :group 'org-reveal-location
737 :type org-context-choice)
739 (defcustom org-show-following-heading '((default . nil))
740 "Non-nil means show following heading when revealing a location.
741 Org-mode often shows locations in an org-mode file which might have
742 been invisible before. When this is set, the heading following the
743 match is shown.
744 Turning this off for example for sparse trees makes them very compact,
745 but makes it harder to edit the location of the match. In such a case,
746 use the command \\[org-reveal] to show more context.
747 Instead of t, this can also be an alist specifying this option for different
748 contexts. See `org-show-hierarchy-above' for valid contexts."
749 :group 'org-reveal-location
750 :type org-context-choice)
752 (defcustom org-show-siblings '((default . nil) (isearch t))
753 "Non-nil means show all sibling heading when revealing a location.
754 Org-mode often shows locations in an org-mode file which might have
755 been invisible before. When this is set, the sibling of the current entry
756 heading are all made visible. If `org-show-hierarchy-above' is t,
757 the same happens on each level of the hierarchy above the current entry.
759 By default this is on for the isearch context, off for all other contexts.
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group 'org-reveal-location
766 :type org-context-choice)
768 (defcustom org-show-entry-below '((default . nil))
769 "Non-nil means show the entry below a headline when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the text below the headline that is
772 exposed is also shown.
774 By default this is off for all contexts.
775 Instead of t, this can also be an alist specifying this option for different
776 contexts. See `org-show-hierarchy-above' for valid contexts."
777 :group 'org-reveal-location
778 :type org-context-choice)
780 (defcustom org-indirect-buffer-display 'other-window
781 "How should indirect tree buffers be displayed?
782 This applies to indirect buffers created with the commands
783 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
784 Valid values are:
785 current-window Display in the current window
786 other-window Just display in another window.
787 dedicated-frame Create one new frame, and re-use it each time.
788 new-frame Make a new frame each time. Note that in this case
789 previously-made indirect buffers are kept, and you need to
790 kill these buffers yourself."
791 :group 'org-structure
792 :group 'org-agenda-windows
793 :type '(choice
794 (const :tag "In current window" current-window)
795 (const :tag "In current frame, other window" other-window)
796 (const :tag "Each time a new frame" new-frame)
797 (const :tag "One dedicated frame" dedicated-frame)))
799 (defcustom org-use-speed-commands nil
800 "Non-nil means activate single letter commands at beginning of a headline.
801 This may also be a function to test for appropriate locations where speed
802 commands should be active."
803 :group 'org-structure
804 :type '(choice
805 (const :tag "Never" nil)
806 (const :tag "At beginning of headline stars" t)
807 (function)))
809 (defcustom org-speed-commands-user nil
810 "Alist of additional speed commands.
811 This list will be checked before `org-speed-commands-default'
812 when the variable `org-use-speed-commands' is non-nil
813 and when the cursor is at the beginning of a headline.
814 The car if each entry is a string with a single letter, which must
815 be assigned to `self-insert-command' in the global map.
816 The cdr is either a command to be called interactively, a function
817 to be called, or a form to be evaluated.
818 An entry that is just a list with a single string will be interpreted
819 as a descriptive headline that will be added when listing the speed
820 commands in the Help buffer using the `?' speed command."
821 :group 'org-structure
822 :type '(repeat :value ("k" . ignore)
823 (choice :value ("k" . ignore)
824 (list :tag "Descriptive Headline" (string :tag "Headline"))
825 (cons :tag "Letter and Command"
826 (string :tag "Command letter")
827 (choice
828 (function)
829 (sexp))))))
831 (defgroup org-cycle nil
832 "Options concerning visibility cycling in Org-mode."
833 :tag "Org Cycle"
834 :group 'org-structure)
836 (defcustom org-cycle-skip-children-state-if-no-children t
837 "Non-nil means skip CHILDREN state in entries that don't have any."
838 :group 'org-cycle
839 :type 'boolean)
841 (defcustom org-cycle-max-level nil
842 "Maximum level which should still be subject to visibility cycling.
843 Levels higher than this will, for cycling, be treated as text, not a headline.
844 When `org-odd-levels-only' is set, a value of N in this variable actually
845 means 2N-1 stars as the limiting headline.
846 When nil, cycle all levels.
847 Note that the limiting level of cycling is also influenced by
848 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
849 `org-inlinetask-min-level' is, cycling will be limited to levels one less
850 than its value."
851 :group 'org-cycle
852 :type '(choice
853 (const :tag "No limit" nil)
854 (integer :tag "Maximum level")))
856 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
857 "Names of drawers. Drawers are not opened by cycling on the headline above.
858 Drawers only open with a TAB on the drawer line itself. A drawer looks like
859 this:
860 :DRAWERNAME:
861 .....
862 :END:
863 The drawer \"PROPERTIES\" is special for capturing properties through
864 the property API.
866 Drawers can be defined on the per-file basis with a line like:
868 #+DRAWERS: HIDDEN STATE PROPERTIES"
869 :group 'org-structure
870 :group 'org-cycle
871 :type '(repeat (string :tag "Drawer Name")))
873 (defcustom org-hide-block-startup nil
874 "Non-nil means entering Org-mode will fold all blocks.
875 This can also be set in on a per-file basis with
877 #+STARTUP: hideblocks
878 #+STARTUP: showblocks"
879 :group 'org-startup
880 :group 'org-cycle
881 :type 'boolean)
883 (defcustom org-cycle-global-at-bob nil
884 "Cycle globally if cursor is at beginning of buffer and not at a headline.
885 This makes it possible to do global cycling without having to use S-TAB or
886 \\[universal-argument] TAB. For this special case to work, the first line \
887 of the buffer
888 must not be a headline - it may be empty or some other text. When used in
889 this way, `org-cycle-hook' is disables temporarily, to make sure the
890 cursor stays at the beginning of the buffer.
891 When this option is nil, don't do anything special at the beginning
892 of the buffer."
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-level-after-item/entry-creation t
897 "Non-nil means cycle entry level or item indentation in new empty entries.
899 When the cursor is at the end of an empty headline, i.e with only stars
900 and maybe a TODO keyword, TAB will then switch the entry to become a child,
901 and then all possible ancestor states, before returning to the original state.
902 This makes data entry extremely fast: M-RET to create a new headline,
903 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
905 When the cursor is at the end of an empty plain list item, one TAB will
906 make it a subitem, two or more tabs will back up to make this an item
907 higher up in the item hierarchy."
908 :group 'org-cycle
909 :type 'boolean)
911 (defcustom org-cycle-emulate-tab t
912 "Where should `org-cycle' emulate TAB.
913 nil Never
914 white Only in completely white lines
915 whitestart Only at the beginning of lines, before the first non-white char
916 t Everywhere except in headlines
917 exc-hl-bol Everywhere except at the start of a headline
918 If TAB is used in a place where it does not emulate TAB, the current subtree
919 visibility is cycled."
920 :group 'org-cycle
921 :type '(choice (const :tag "Never" nil)
922 (const :tag "Only in completely white lines" white)
923 (const :tag "Before first char in a line" whitestart)
924 (const :tag "Everywhere except in headlines" t)
925 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
928 (defcustom org-cycle-separator-lines 2
929 "Number of empty lines needed to keep an empty line between collapsed trees.
930 If you leave an empty line between the end of a subtree and the following
931 headline, this empty line is hidden when the subtree is folded.
932 Org-mode will leave (exactly) one empty line visible if the number of
933 empty lines is equal or larger to the number given in this variable.
934 So the default 2 means at least 2 empty lines after the end of a subtree
935 are needed to produce free space between a collapsed subtree and the
936 following headline.
938 If the number is negative, and the number of empty lines is at least -N,
939 all empty lines are shown.
941 Special case: when 0, never leave empty lines in collapsed view."
942 :group 'org-cycle
943 :type 'integer)
944 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
946 (defcustom org-pre-cycle-hook nil
947 "Hook that is run before visibility cycling is happening.
948 The function(s) in this hook must accept a single argument which indicates
949 the new state that will be set right after running this hook. The
950 argument is a symbol. Before a global state change, it can have the values
951 `overview', `content', or `all'. Before a local state change, it can have
952 the values `folded', `children', or `subtree'."
953 :group 'org-cycle
954 :type 'hook)
956 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
957 org-cycle-hide-drawers
958 org-cycle-show-empty-lines
959 org-optimize-window-after-visibility-change)
960 "Hook that is run after `org-cycle' has changed the buffer visibility.
961 The function(s) in this hook must accept a single argument which indicates
962 the new state that was set by the most recent `org-cycle' command. The
963 argument is a symbol. After a global state change, it can have the values
964 `overview', `content', or `all'. After a local state change, it can have
965 the values `folded', `children', or `subtree'."
966 :group 'org-cycle
967 :type 'hook)
969 (defgroup org-edit-structure nil
970 "Options concerning structure editing in Org-mode."
971 :tag "Org Edit Structure"
972 :group 'org-structure)
974 (defcustom org-odd-levels-only nil
975 "Non-nil means skip even levels and only use odd levels for the outline.
976 This has the effect that two stars are being added/taken away in
977 promotion/demotion commands. It also influences how levels are
978 handled by the exporters.
979 Changing it requires restart of `font-lock-mode' to become effective
980 for fontification also in regions already fontified.
981 You may also set this on a per-file basis by adding one of the following
982 lines to the buffer:
984 #+STARTUP: odd
985 #+STARTUP: oddeven"
986 :group 'org-edit-structure
987 :group 'org-appearance
988 :type 'boolean)
990 (defcustom org-adapt-indentation t
991 "Non-nil means adapt indentation to outline node level.
993 When this variable is set, Org assumes that you write outlines by
994 indenting text in each node to align with the headline (after the stars).
995 The following issues are influenced by this variable:
997 - When this is set and the *entire* text in an entry is indented, the
998 indentation is increased by one space in a demotion command, and
999 decreased by one in a promotion command. If any line in the entry
1000 body starts with text at column 0, indentation is not changed at all.
1002 - Property drawers and planning information is inserted indented when
1003 this variable s set. When nil, they will not be indented.
1005 - TAB indents a line relative to context. The lines below a headline
1006 will be indented when this variable is set.
1008 Note that this is all about true indentation, by adding and removing
1009 space characters. See also `org-indent.el' which does level-dependent
1010 indentation in a virtual way, i.e. at display time in Emacs."
1011 :group 'org-edit-structure
1012 :type 'boolean)
1014 (defcustom org-special-ctrl-a/e nil
1015 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1017 When t, `C-a' will bring back the cursor to the beginning of the
1018 headline text, i.e. after the stars and after a possible TODO keyword.
1019 In an item, this will be the position after the bullet.
1020 When the cursor is already at that position, another `C-a' will bring
1021 it to the beginning of the line.
1023 `C-e' will jump to the end of the headline, ignoring the presence of tags
1024 in the headline. A second `C-e' will then jump to the true end of the
1025 line, after any tags. This also means that, when this variable is
1026 non-nil, `C-e' also will never jump beyond the end of the heading of a
1027 folded section, i.e. not after the ellipses.
1029 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1030 going to the true line boundary first. Only a directly following, identical
1031 keypress will bring the cursor to the special positions.
1033 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1034 set separately."
1035 :group 'org-edit-structure
1036 :type '(choice
1037 (const :tag "off" nil)
1038 (const :tag "on: after stars/bullet and before tags first" t)
1039 (const :tag "reversed: true line boundary first" reversed)
1040 (cons :tag "Set C-a and C-e separately"
1041 (choice :tag "Special C-a"
1042 (const :tag "off" nil)
1043 (const :tag "on: after stars/bullet first" t)
1044 (const :tag "reversed: before stars/bullet first" reversed))
1045 (choice :tag "Special C-e"
1046 (const :tag "off" nil)
1047 (const :tag "on: before tags first" t)
1048 (const :tag "reversed: after tags first" reversed)))))
1049 (if (fboundp 'defvaralias)
1050 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1052 (defcustom org-special-ctrl-k nil
1053 "Non-nil means `C-k' will behave specially in headlines.
1054 When nil, `C-k' will call the default `kill-line' command.
1055 When t, the following will happen while the cursor is in the headline:
1057 - When the cursor is at the beginning of a headline, kill the entire
1058 line and possible the folded subtree below the line.
1059 - When in the middle of the headline text, kill the headline up to the tags.
1060 - When after the headline text, kill the tags."
1061 :group 'org-edit-structure
1062 :type 'boolean)
1064 (defcustom org-ctrl-k-protect-subtree nil
1065 "Non-nil means, do not delete a hidden subtree with C-k.
1066 When set to the symbol `error', simply throw an error when C-k is
1067 used to kill (part-of) a headline that has hidden text behind it.
1068 Any other non-nil value will result in a query to the user, if it is
1069 OK to kill that hidden subtree. When nil, kill without remorse."
1070 :group 'org-edit-structure
1071 :type '(choice
1072 (const :tag "Do not protect hidden subtrees" nil)
1073 (const :tag "Protect hidden subtrees with a security query" t)
1074 (const :tag "Never kill a hidden subtree with C-k" error)))
1076 (defcustom org-catch-invisible-edits nil
1077 "Check if in invisible region before inserting or deleting a character.
1078 Valid values are:
1080 nil Do not check, so just do invisible edits.
1081 error Throw an error and do nothing.
1082 show Make point visible, and do the requested edit.
1083 show-and-error Make point visible, then throw an error and abort the edit.
1084 smart Make point visible, and do insertion/deletion if it is
1085 adjacent to visible text and the change feels predictable.
1086 Never delete a previously invisible character or add in the
1087 middle or right after an invisible region. Basically, this
1088 allows insertion and backward-delete right before ellipses.
1089 FIXME: maybe in this case we should not even show?"
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "Do not check" nil)
1093 (const :tag "Throw error when trying to edit" error)
1094 (const :tag "Unhide, but do not do the edit" show-and-error)
1095 (const :tag "Show invisible part and do the edit" show)
1096 (const :tag "Be smart and do the right thing" smart)))
1098 (defcustom org-yank-folded-subtrees t
1099 "Non-nil means when yanking subtrees, fold them.
1100 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1101 it starts with a heading and all other headings in it are either children
1102 or siblings, then fold all the subtrees. However, do this only if no
1103 text after the yank would be swallowed into a folded tree by this action."
1104 :group 'org-edit-structure
1105 :type 'boolean)
1107 (defcustom org-yank-adjusted-subtrees nil
1108 "Non-nil means when yanking subtrees, adjust the level.
1109 With this setting, `org-paste-subtree' is used to insert the subtree, see
1110 this function for details."
1111 :group 'org-edit-structure
1112 :type 'boolean)
1114 (defcustom org-M-RET-may-split-line '((default . t))
1115 "Non-nil means M-RET will split the line at the cursor position.
1116 When nil, it will go to the end of the line before making a
1117 new line.
1118 You may also set this option in a different way for different
1119 contexts. Valid contexts are:
1121 headline when creating a new headline
1122 item when creating a new item
1123 table in a table field
1124 default the value to be used for all contexts not explicitly
1125 customized"
1126 :group 'org-structure
1127 :group 'org-table
1128 :type '(choice
1129 (const :tag "Always" t)
1130 (const :tag "Never" nil)
1131 (repeat :greedy t :tag "Individual contexts"
1132 (cons
1133 (choice :tag "Context"
1134 (const headline)
1135 (const item)
1136 (const table)
1137 (const default))
1138 (boolean)))))
1141 (defcustom org-insert-heading-respect-content nil
1142 "Non-nil means insert new headings after the current subtree.
1143 When nil, the new heading is created directly after the current line.
1144 The commands \\[org-insert-heading-respect-content] and
1145 \\[org-insert-todo-heading-respect-content] turn this variable on
1146 for the duration of the command."
1147 :group 'org-structure
1148 :type 'boolean)
1150 (defcustom org-blank-before-new-entry '((heading . auto)
1151 (plain-list-item . auto))
1152 "Should `org-insert-heading' leave a blank line before new heading/item?
1153 The value is an alist, with `heading' and `plain-list-item' as CAR,
1154 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1155 which case Org will look at the surrounding headings/items and try to
1156 make an intelligent decision whether to insert a blank line or not.
1158 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1159 set, the setting here is ignored and no empty line is inserted, to avoid
1160 breaking the list structure."
1161 :group 'org-edit-structure
1162 :type '(list
1163 (cons (const heading)
1164 (choice (const :tag "Never" nil)
1165 (const :tag "Always" t)
1166 (const :tag "Auto" auto)))
1167 (cons (const plain-list-item)
1168 (choice (const :tag "Never" nil)
1169 (const :tag "Always" t)
1170 (const :tag "Auto" auto)))))
1172 (defcustom org-insert-heading-hook nil
1173 "Hook being run after inserting a new heading."
1174 :group 'org-edit-structure
1175 :type 'hook)
1177 (defcustom org-enable-fixed-width-editor t
1178 "Non-nil means lines starting with \":\" are treated as fixed-width.
1179 This currently only means they are never auto-wrapped.
1180 When nil, such lines will be treated like ordinary lines.
1181 See also the QUOTE keyword."
1182 :group 'org-edit-structure
1183 :type 'boolean)
1185 (defcustom org-goto-auto-isearch t
1186 "Non-nil means typing characters in `org-goto' starts incremental search."
1187 :group 'org-edit-structure
1188 :type 'boolean)
1190 (defgroup org-sparse-trees nil
1191 "Options concerning sparse trees in Org-mode."
1192 :tag "Org Sparse Trees"
1193 :group 'org-structure)
1195 (defcustom org-highlight-sparse-tree-matches t
1196 "Non-nil means highlight all matches that define a sparse tree.
1197 The highlights will automatically disappear the next time the buffer is
1198 changed by an edit command."
1199 :group 'org-sparse-trees
1200 :type 'boolean)
1202 (defcustom org-remove-highlights-with-change t
1203 "Non-nil means any change to the buffer will remove temporary highlights.
1204 Such highlights are created by `org-occur' and `org-clock-display'.
1205 When nil, `C-c C-c needs to be used to get rid of the highlights.
1206 The highlights created by `org-preview-latex-fragment' always need
1207 `C-c C-c' to be removed."
1208 :group 'org-sparse-trees
1209 :group 'org-time
1210 :type 'boolean)
1213 (defcustom org-occur-hook '(org-first-headline-recenter)
1214 "Hook that is run after `org-occur' has constructed a sparse tree.
1215 This can be used to recenter the window to show as much of the structure
1216 as possible."
1217 :group 'org-sparse-trees
1218 :type 'hook)
1220 (defgroup org-imenu-and-speedbar nil
1221 "Options concerning imenu and speedbar in Org-mode."
1222 :tag "Org Imenu and Speedbar"
1223 :group 'org-structure)
1225 (defcustom org-imenu-depth 2
1226 "The maximum level for Imenu access to Org-mode headlines.
1227 This also applied for speedbar access."
1228 :group 'org-imenu-and-speedbar
1229 :type 'integer)
1231 (defgroup org-table nil
1232 "Options concerning tables in Org-mode."
1233 :tag "Org Table"
1234 :group 'org)
1236 (defcustom org-enable-table-editor 'optimized
1237 "Non-nil means lines starting with \"|\" are handled by the table editor.
1238 When nil, such lines will be treated like ordinary lines.
1240 When equal to the symbol `optimized', the table editor will be optimized to
1241 do the following:
1242 - Automatic overwrite mode in front of whitespace in table fields.
1243 This makes the structure of the table stay in tact as long as the edited
1244 field does not exceed the column width.
1245 - Minimize the number of realigns. Normally, the table is aligned each time
1246 TAB or RET are pressed to move to another field. With optimization this
1247 happens only if changes to a field might have changed the column width.
1248 Optimization requires replacing the functions `self-insert-command',
1249 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1250 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1251 very good at guessing when a re-align will be necessary, but you can always
1252 force one with \\[org-ctrl-c-ctrl-c].
1254 If you would like to use the optimized version in Org-mode, but the
1255 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1257 This variable can be used to turn on and off the table editor during a session,
1258 but in order to toggle optimization, a restart is required.
1260 See also the variable `org-table-auto-blank-field'."
1261 :group 'org-table
1262 :type '(choice
1263 (const :tag "off" nil)
1264 (const :tag "on" t)
1265 (const :tag "on, optimized" optimized)))
1267 (defcustom org-self-insert-cluster-for-undo t
1268 "Non-nil means cluster self-insert commands for undo when possible.
1269 If this is set, then, like in the Emacs command loop, 20 consecutive
1270 characters will be undone together.
1271 This is configurable, because there is some impact on typing performance."
1272 :group 'org-table
1273 :type 'boolean)
1275 (defcustom org-table-tab-recognizes-table.el t
1276 "Non-nil means TAB will automatically notice a table.el table.
1277 When it sees such a table, it moves point into it and - if necessary -
1278 calls `table-recognize-table'."
1279 :group 'org-table-editing
1280 :type 'boolean)
1282 (defgroup org-link nil
1283 "Options concerning links in Org-mode."
1284 :tag "Org Link"
1285 :group 'org)
1287 (defvar org-link-abbrev-alist-local nil
1288 "Buffer-local version of `org-link-abbrev-alist', which see.
1289 The value of this is taken from the #+LINK lines.")
1290 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1292 (defcustom org-link-abbrev-alist nil
1293 "Alist of link abbreviations.
1294 The car of each element is a string, to be replaced at the start of a link.
1295 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1296 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1298 [[linkkey:tag][description]]
1300 The 'linkkey' must be a word word, starting with a letter, followed
1301 by letters, numbers, '-' or '_'.
1303 If REPLACE is a string, the tag will simply be appended to create the link.
1304 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1305 the placeholder \"%h\" will cause a url-encoded version of the tag to
1306 be inserted at that point (see the function `url-hexify-string').
1308 REPLACE may also be a function that will be called with the tag as the
1309 only argument to create the link, which should be returned as a string.
1311 See the manual for examples."
1312 :group 'org-link
1313 :type '(repeat
1314 (cons
1315 (string :tag "Protocol")
1316 (choice
1317 (string :tag "Format")
1318 (function)))))
1320 (defcustom org-descriptive-links t
1321 "Non-nil means Org will display descriptive links.
1322 E.g. [[http://orgmode.org][Org website]] will be displayed as
1323 \"Org Website\", hiding the link itself and just displaying its
1324 description. When set to `nil', Org will display the full links
1325 literally.
1327 You can interactively set the value of this variable by calling
1328 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1329 :group 'org-link
1330 :type 'boolean)
1332 (defcustom org-link-file-path-type 'adaptive
1333 "How the path name in file links should be stored.
1334 Valid values are:
1336 relative Relative to the current directory, i.e. the directory of the file
1337 into which the link is being inserted.
1338 absolute Absolute path, if possible with ~ for home directory.
1339 noabbrev Absolute path, no abbreviation of home directory.
1340 adaptive Use relative path for files in the current directory and sub-
1341 directories of it. For other files, use an absolute path."
1342 :group 'org-link
1343 :type '(choice
1344 (const relative)
1345 (const absolute)
1346 (const noabbrev)
1347 (const adaptive)))
1349 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1350 "Types of links that should be activated in Org-mode files.
1351 This is a list of symbols, each leading to the activation of a certain link
1352 type. In principle, it does not hurt to turn on most link types - there may
1353 be a small gain when turning off unused link types. The types are:
1355 bracket The recommended [[link][description]] or [[link]] links with hiding.
1356 angle Links in angular brackets that may contain whitespace like
1357 <bbdb:Carsten Dominik>.
1358 plain Plain links in normal text, no whitespace, like http://google.com.
1359 radio Text that is matched by a radio target, see manual for details.
1360 tag Tag settings in a headline (link to tag search).
1361 date Time stamps (link to calendar).
1362 footnote Footnote labels.
1364 Changing this variable requires a restart of Emacs to become effective."
1365 :group 'org-link
1366 :type '(set :greedy t
1367 (const :tag "Double bracket links" bracket)
1368 (const :tag "Angular bracket links" angle)
1369 (const :tag "Plain text links" plain)
1370 (const :tag "Radio target matches" radio)
1371 (const :tag "Tags" tag)
1372 (const :tag "Timestamps" date)
1373 (const :tag "Footnotes" footnote)))
1375 (defcustom org-make-link-description-function nil
1376 "Function to use to generate link descriptions from links.
1377 If nil the link location will be used. This function must take
1378 two parameters; the first is the link and the second the
1379 description `org-insert-link' has generated, and should return the
1380 description to use."
1381 :group 'org-link
1382 :type 'function)
1384 (defgroup org-link-store nil
1385 "Options concerning storing links in Org-mode."
1386 :tag "Org Store Link"
1387 :group 'org-link)
1389 (defcustom org-email-link-description-format "Email %c: %.30s"
1390 "Format of the description part of a link to an email or usenet message.
1391 The following %-escapes will be replaced by corresponding information:
1393 %F full \"From\" field
1394 %f name, taken from \"From\" field, address if no name
1395 %T full \"To\" field
1396 %t first name in \"To\" field, address if no name
1397 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1398 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1399 %s subject
1400 %d date
1401 %m message-id.
1403 You may use normal field width specification between the % and the letter.
1404 This is for example useful to limit the length of the subject.
1406 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1407 :group 'org-link-store
1408 :type 'string)
1410 (defcustom org-from-is-user-regexp
1411 (let (r1 r2)
1412 (when (and user-mail-address (not (string= user-mail-address "")))
1413 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1414 (when (and user-full-name (not (string= user-full-name "")))
1415 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1416 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1417 "Regexp matched against the \"From:\" header of an email or usenet message.
1418 It should match if the message is from the user him/herself."
1419 :group 'org-link-store
1420 :type 'regexp)
1422 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1423 "Non-nil means storing a link to an Org file will use entry IDs.
1425 Note that before this variable is even considered, org-id must be loaded,
1426 so please customize `org-modules' and turn it on.
1428 The variable can have the following values:
1430 t Create an ID if needed to make a link to the current entry.
1432 create-if-interactive
1433 If `org-store-link' is called directly (interactively, as a user
1434 command), do create an ID to support the link. But when doing the
1435 job for remember, only use the ID if it already exists. The
1436 purpose of this setting is to avoid proliferation of unwanted
1437 IDs, just because you happen to be in an Org file when you
1438 call `org-remember' that automatically and preemptively
1439 creates a link. If you do want to get an ID link in a remember
1440 template to an entry not having an ID, create it first by
1441 explicitly creating a link to it, using `C-c C-l' first.
1443 create-if-interactive-and-no-custom-id
1444 Like create-if-interactive, but do not create an ID if there is
1445 a CUSTOM_ID property defined in the entry. This is the default.
1447 use-existing
1448 Use existing ID, do not create one.
1450 nil Never use an ID to make a link, instead link using a text search for
1451 the headline text."
1452 :group 'org-link-store
1453 :type '(choice
1454 (const :tag "Create ID to make link" t)
1455 (const :tag "Create if storing link interactively"
1456 create-if-interactive)
1457 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1458 create-if-interactive-and-no-custom-id)
1459 (const :tag "Only use existing" use-existing)
1460 (const :tag "Do not use ID to create link" nil)))
1462 (defcustom org-context-in-file-links t
1463 "Non-nil means file links from `org-store-link' contain context.
1464 A search string will be added to the file name with :: as separator and
1465 used to find the context when the link is activated by the command
1466 `org-open-at-point'. When this option is t, the entire active region
1467 will be placed in the search string of the file link. If set to a
1468 positive integer, only the first n lines of context will be stored.
1470 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1471 negates this setting for the duration of the command."
1472 :group 'org-link-store
1473 :type '(choice boolean integer))
1475 (defcustom org-keep-stored-link-after-insertion nil
1476 "Non-nil means keep link in list for entire session.
1478 The command `org-store-link' adds a link pointing to the current
1479 location to an internal list. These links accumulate during a session.
1480 The command `org-insert-link' can be used to insert links into any
1481 Org-mode file (offering completion for all stored links). When this
1482 option is nil, every link which has been inserted once using \\[org-insert-link]
1483 will be removed from the list, to make completing the unused links
1484 more efficient."
1485 :group 'org-link-store
1486 :type 'boolean)
1488 (defgroup org-link-follow nil
1489 "Options concerning following links in Org-mode."
1490 :tag "Org Follow Link"
1491 :group 'org-link)
1493 (defcustom org-link-translation-function nil
1494 "Function to translate links with different syntax to Org syntax.
1495 This can be used to translate links created for example by the Planner
1496 or emacs-wiki packages to Org syntax.
1497 The function must accept two parameters, a TYPE containing the link
1498 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1499 which is everything after the link protocol. It should return a cons
1500 with possibly modified values of type and path.
1501 Org contains a function for this, so if you set this variable to
1502 `org-translate-link-from-planner', you should be able follow many
1503 links created by planner."
1504 :group 'org-link-follow
1505 :type 'function)
1507 (defcustom org-follow-link-hook nil
1508 "Hook that is run after a link has been followed."
1509 :group 'org-link-follow
1510 :type 'hook)
1512 (defcustom org-tab-follows-link nil
1513 "Non-nil means on links TAB will follow the link.
1514 Needs to be set before org.el is loaded.
1515 This really should not be used, it does not make sense, and the
1516 implementation is bad."
1517 :group 'org-link-follow
1518 :type 'boolean)
1520 (defcustom org-return-follows-link nil
1521 "Non-nil means on links RET will follow the link."
1522 :group 'org-link-follow
1523 :type 'boolean)
1525 (defcustom org-mouse-1-follows-link
1526 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1527 "Non-nil means mouse-1 on a link will follow the link.
1528 A longer mouse click will still set point. Does not work on XEmacs.
1529 Needs to be set before org.el is loaded."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-mark-ring-length 4
1534 "Number of different positions to be recorded in the ring.
1535 Changing this requires a restart of Emacs to work correctly."
1536 :group 'org-link-follow
1537 :type 'integer)
1539 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1540 "Non-nil means internal links in Org files must exactly match a headline.
1541 When nil, the link search tries to match a phrase with all words
1542 in the search text."
1543 :group 'org-link-follow
1544 :type '(choice
1545 (const :tag "Use fuzzy text search" nil)
1546 (const :tag "Match only exact headline" t)
1547 (const :tag "Match exact headline or query to create it"
1548 query-to-create)))
1550 (defcustom org-link-frame-setup
1551 '((vm . vm-visit-folder-other-frame)
1552 (gnus . org-gnus-no-new-news)
1553 (file . find-file-other-window)
1554 (wl . wl-other-frame))
1555 "Setup the frame configuration for following links.
1556 When following a link with Emacs, it may often be useful to display
1557 this link in another window or frame. This variable can be used to
1558 set this up for the different types of links.
1559 For VM, use any of
1560 `vm-visit-folder'
1561 `vm-visit-folder-other-window'
1562 `vm-visit-folder-other-frame'
1563 For Gnus, use any of
1564 `gnus'
1565 `gnus-other-frame'
1566 `org-gnus-no-new-news'
1567 For FILE, use any of
1568 `find-file'
1569 `find-file-other-window'
1570 `find-file-other-frame'
1571 For Wanderlust use any of
1572 `wl'
1573 `wl-other-frame'
1574 For the calendar, use the variable `calendar-setup'.
1575 For BBDB, it is currently only possible to display the matches in
1576 another window."
1577 :group 'org-link-follow
1578 :type '(list
1579 (cons (const vm)
1580 (choice
1581 (const vm-visit-folder)
1582 (const vm-visit-folder-other-window)
1583 (const vm-visit-folder-other-frame)))
1584 (cons (const gnus)
1585 (choice
1586 (const gnus)
1587 (const gnus-other-frame)
1588 (const org-gnus-no-new-news)))
1589 (cons (const file)
1590 (choice
1591 (const find-file)
1592 (const find-file-other-window)
1593 (const find-file-other-frame)))
1594 (cons (const wl)
1595 (choice
1596 (const wl)
1597 (const wl-other-frame)))))
1599 (defcustom org-display-internal-link-with-indirect-buffer nil
1600 "Non-nil means use indirect buffer to display infile links.
1601 Activating internal links (from one location in a file to another location
1602 in the same file) normally just jumps to the location. When the link is
1603 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1604 is displayed in
1605 another window. When this option is set, the other window actually displays
1606 an indirect buffer clone of the current buffer, to avoid any visibility
1607 changes to the current buffer."
1608 :group 'org-link-follow
1609 :type 'boolean)
1611 (defcustom org-open-non-existing-files nil
1612 "Non-nil means `org-open-file' will open non-existing files.
1613 When nil, an error will be generated.
1614 This variable applies only to external applications because they
1615 might choke on non-existing files. If the link is to a file that
1616 will be opened in Emacs, the variable is ignored."
1617 :group 'org-link-follow
1618 :type 'boolean)
1620 (defcustom org-open-directory-means-index-dot-org nil
1621 "Non-nil means a link to a directory really means to index.org.
1622 When nil, following a directory link will run dired or open a finder/explorer
1623 window on that directory."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1628 "Function and arguments to call for following mailto links.
1629 This is a list with the first element being a Lisp function, and the
1630 remaining elements being arguments to the function. In string arguments,
1631 %a will be replaced by the address, and %s will be replaced by the subject
1632 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1633 :group 'org-link-follow
1634 :type '(choice
1635 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1636 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1637 (const :tag "message-mail" (message-mail "%a" "%s"))
1638 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1640 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1641 "Non-nil means ask for confirmation before executing shell links.
1642 Shell links can be dangerous: just think about a link
1644 [[shell:rm -rf ~/*][Google Search]]
1646 This link would show up in your Org-mode document as \"Google Search\",
1647 but really it would remove your entire home directory.
1648 Therefore we advise against setting this variable to nil.
1649 Just change it to `y-or-n-p' if you want to confirm with a
1650 single keystroke rather than having to type \"yes\"."
1651 :group 'org-link-follow
1652 :type '(choice
1653 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1654 (const :tag "with y-or-n (faster)" y-or-n-p)
1655 (const :tag "no confirmation (dangerous)" nil)))
1656 (put 'org-confirm-shell-link-function
1657 'safe-local-variable
1658 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1660 (defcustom org-confirm-shell-link-not-regexp ""
1661 "A regexp to skip confirmation for shell links."
1662 :group 'org-link-follow
1663 :type 'regexp)
1665 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1666 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1667 Elisp links can be dangerous: just think about a link
1669 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1671 This link would show up in your Org-mode document as \"Google Search\",
1672 but really it would remove your entire home directory.
1673 Therefore we advise against setting this variable to nil.
1674 Just change it to `y-or-n-p' if you want to confirm with a
1675 single keystroke rather than having to type \"yes\"."
1676 :group 'org-link-follow
1677 :type '(choice
1678 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1679 (const :tag "with y-or-n (faster)" y-or-n-p)
1680 (const :tag "no confirmation (dangerous)" nil)))
1681 (put 'org-confirm-shell-link-function
1682 'safe-local-variable
1683 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1685 (defcustom org-confirm-elisp-link-not-regexp ""
1686 "A regexp to skip confirmation for Elisp links."
1687 :group 'org-link-follow
1688 :type 'regexp)
1690 (defconst org-file-apps-defaults-gnu
1691 '((remote . emacs)
1692 (system . mailcap)
1693 (t . mailcap))
1694 "Default file applications on a UNIX or GNU/Linux system.
1695 See `org-file-apps'.")
1697 (defconst org-file-apps-defaults-macosx
1698 '((remote . emacs)
1699 (t . "open %s")
1700 (system . "open %s")
1701 ("ps.gz" . "gv %s")
1702 ("eps.gz" . "gv %s")
1703 ("dvi" . "xdvi %s")
1704 ("fig" . "xfig %s"))
1705 "Default file applications on a MacOS X system.
1706 The system \"open\" is known as a default, but we use X11 applications
1707 for some files for which the OS does not have a good default.
1708 See `org-file-apps'.")
1710 (defconst org-file-apps-defaults-windowsnt
1711 (list
1712 '(remote . emacs)
1713 (cons t
1714 (list (if (featurep 'xemacs)
1715 'mswindows-shell-execute
1716 'w32-shell-execute)
1717 "open" 'file))
1718 (cons 'system
1719 (list (if (featurep 'xemacs)
1720 'mswindows-shell-execute
1721 'w32-shell-execute)
1722 "open" 'file)))
1723 "Default file applications on a Windows NT system.
1724 The system \"open\" is used for most files.
1725 See `org-file-apps'.")
1727 (defcustom org-file-apps
1729 (auto-mode . emacs)
1730 ("\\.mm\\'" . default)
1731 ("\\.x?html?\\'" . default)
1732 ("\\.pdf\\'" . default)
1734 "External applications for opening `file:path' items in a document.
1735 Org-mode uses system defaults for different file types, but
1736 you can use this variable to set the application for a given file
1737 extension. The entries in this list are cons cells where the car identifies
1738 files and the cdr the corresponding command. Possible values for the
1739 file identifier are
1740 \"string\" A string as a file identifier can be interpreted in different
1741 ways, depending on its contents:
1743 - Alphanumeric characters only:
1744 Match links with this file extension.
1745 Example: (\"pdf\" . \"evince %s\")
1746 to open PDFs with evince.
1748 - Regular expression: Match links where the
1749 filename matches the regexp. If you want to
1750 use groups here, use shy groups.
1752 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1753 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1754 to open *.html and *.xhtml with firefox.
1756 - Regular expression which contains (non-shy) groups:
1757 Match links where the whole link, including \"::\", and
1758 anything after that, matches the regexp.
1759 In a custom command string, %1, %2, etc. are replaced with
1760 the parts of the link that were matched by the groups.
1761 For backwards compatibility, if a command string is given
1762 that does not use any of the group matches, this case is
1763 handled identically to the second one (i.e. match against
1764 file name only).
1765 In a custom lisp form, you can access the group matches with
1766 (match-string n link).
1768 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1769 to open [[file:document.pdf::5]] with evince at page 5.
1771 `directory' Matches a directory
1772 `remote' Matches a remote file, accessible through tramp or efs.
1773 Remote files most likely should be visited through Emacs
1774 because external applications cannot handle such paths.
1775 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1776 so all files Emacs knows how to handle. Using this with
1777 command `emacs' will open most files in Emacs. Beware that this
1778 will also open html files inside Emacs, unless you add
1779 (\"html\" . default) to the list as well.
1780 t Default for files not matched by any of the other options.
1781 `system' The system command to open files, like `open' on Windows
1782 and Mac OS X, and mailcap under GNU/Linux. This is the command
1783 that will be selected if you call `C-c C-o' with a double
1784 \\[universal-argument] \\[universal-argument] prefix.
1786 Possible values for the command are:
1787 `emacs' The file will be visited by the current Emacs process.
1788 `default' Use the default application for this file type, which is the
1789 association for t in the list, most likely in the system-specific
1790 part.
1791 This can be used to overrule an unwanted setting in the
1792 system-specific variable.
1793 `system' Use the system command for opening files, like \"open\".
1794 This command is specified by the entry whose car is `system'.
1795 Most likely, the system-specific version of this variable
1796 does define this command, but you can overrule/replace it
1797 here.
1798 string A command to be executed by a shell; %s will be replaced
1799 by the path to the file.
1800 sexp A Lisp form which will be evaluated. The file path will
1801 be available in the Lisp variable `file'.
1802 For more examples, see the system specific constants
1803 `org-file-apps-defaults-macosx'
1804 `org-file-apps-defaults-windowsnt'
1805 `org-file-apps-defaults-gnu'."
1806 :group 'org-link-follow
1807 :type '(repeat
1808 (cons (choice :value ""
1809 (string :tag "Extension")
1810 (const :tag "System command to open files" system)
1811 (const :tag "Default for unrecognized files" t)
1812 (const :tag "Remote file" remote)
1813 (const :tag "Links to a directory" directory)
1814 (const :tag "Any files that have Emacs modes"
1815 auto-mode))
1816 (choice :value ""
1817 (const :tag "Visit with Emacs" emacs)
1818 (const :tag "Use default" default)
1819 (const :tag "Use the system command" system)
1820 (string :tag "Command")
1821 (sexp :tag "Lisp form")))))
1825 (defgroup org-refile nil
1826 "Options concerning refiling entries in Org-mode."
1827 :tag "Org Refile"
1828 :group 'org)
1830 (defcustom org-directory "~/org"
1831 "Directory with org files.
1832 This is just a default location to look for Org files. There is no need
1833 at all to put your files into this directory. It is only used in the
1834 following situations:
1836 1. When a remember template specifies a target file that is not an
1837 absolute path. The path will then be interpreted relative to
1838 `org-directory'
1839 2. When a remember note is filed away in an interactive way (when exiting the
1840 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1841 with `org-directory' as the default path."
1842 :group 'org-refile
1843 :group 'org-remember
1844 :type 'directory)
1846 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1847 "Default target for storing notes.
1848 Used as a fall back file for org-remember.el and org-capture.el, for
1849 templates that do not specify a target file."
1850 :group 'org-refile
1851 :group 'org-remember
1852 :type '(choice
1853 (const :tag "Default from remember-data-file" nil)
1854 file))
1856 (defcustom org-goto-interface 'outline
1857 "The default interface to be used for `org-goto'.
1858 Allowed values are:
1859 outline The interface shows an outline of the relevant file
1860 and the correct heading is found by moving through
1861 the outline or by searching with incremental search.
1862 outline-path-completion Headlines in the current buffer are offered via
1863 completion. This is the interface also used by
1864 the refile command."
1865 :group 'org-refile
1866 :type '(choice
1867 (const :tag "Outline" outline)
1868 (const :tag "Outline-path-completion" outline-path-completion)))
1870 (defcustom org-goto-max-level 5
1871 "Maximum target level when running `org-goto' with refile interface."
1872 :group 'org-refile
1873 :type 'integer)
1875 (defcustom org-reverse-note-order nil
1876 "Non-nil means store new notes at the beginning of a file or entry.
1877 When nil, new notes will be filed to the end of a file or entry.
1878 This can also be a list with cons cells of regular expressions that
1879 are matched against file names, and values."
1880 :group 'org-remember
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Reverse always" t)
1884 (const :tag "Reverse never" nil)
1885 (repeat :tag "By file name regexp"
1886 (cons regexp boolean))))
1888 (defcustom org-log-refile nil
1889 "Information to record when a task is refiled.
1891 Possible values are:
1893 nil Don't add anything
1894 time Add a time stamp to the task
1895 note Prompt for a note and add it with template `org-log-note-headings'
1897 This option can also be set with on a per-file-basis with
1899 #+STARTUP: nologrefile
1900 #+STARTUP: logrefile
1901 #+STARTUP: lognoterefile
1903 You can have local logging settings for a subtree by setting the LOGGING
1904 property to one or more of these keywords.
1906 When bulk-refiling from the agenda, the value `note' is forbidden and
1907 will temporarily be changed to `time'."
1908 :group 'org-refile
1909 :group 'org-progress
1910 :type '(choice
1911 (const :tag "No logging" nil)
1912 (const :tag "Record timestamp" time)
1913 (const :tag "Record timestamp with note." note)))
1915 (defcustom org-refile-targets nil
1916 "Targets for refiling entries with \\[org-refile].
1917 This is a list of cons cells. Each cell contains:
1918 - a specification of the files to be considered, either a list of files,
1919 or a symbol whose function or variable value will be used to retrieve
1920 a file name or a list of file names. If you use `org-agenda-files' for
1921 that, all agenda files will be scanned for targets. Nil means consider
1922 headings in the current buffer.
1923 - A specification of how to find candidate refile targets. This may be
1924 any of:
1925 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1926 This tag has to be present in all target headlines, inheritance will
1927 not be considered.
1928 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1929 todo keyword.
1930 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1931 headlines that are refiling targets.
1932 - a cons cell (:level . N). Any headline of level N is considered a target.
1933 Note that, when `org-odd-levels-only' is set, level corresponds to
1934 order in hierarchy, not to the number of stars.
1935 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1936 Note that, when `org-odd-levels-only' is set, level corresponds to
1937 order in hierarchy, not to the number of stars.
1939 Each element of this list generates a set of possible targets.
1940 The union of these sets is presented (with completion) to
1941 the user by `org-refile'.
1943 You can set the variable `org-refile-target-verify-function' to a function
1944 to verify each headline found by the simple criteria above.
1946 When this variable is nil, all top-level headlines in the current buffer
1947 are used, equivalent to the value `((nil . (:level . 1))'."
1948 :group 'org-refile
1949 :type '(repeat
1950 (cons
1951 (choice :value org-agenda-files
1952 (const :tag "All agenda files" org-agenda-files)
1953 (const :tag "Current buffer" nil)
1954 (function) (variable) (file))
1955 (choice :tag "Identify target headline by"
1956 (cons :tag "Specific tag" (const :value :tag) (string))
1957 (cons :tag "TODO keyword" (const :value :todo) (string))
1958 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1959 (cons :tag "Level number" (const :value :level) (integer))
1960 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1962 (defcustom org-refile-target-verify-function nil
1963 "Function to verify if the headline at point should be a refile target.
1964 The function will be called without arguments, with point at the
1965 beginning of the headline. It should return t and leave point
1966 where it is if the headline is a valid target for refiling.
1968 If the target should not be selected, the function must return nil.
1969 In addition to this, it may move point to a place from where the search
1970 should be continued. For example, the function may decide that the entire
1971 subtree of the current entry should be excluded and move point to the end
1972 of the subtree."
1973 :group 'org-refile
1974 :type 'function)
1976 (defcustom org-refile-use-cache nil
1977 "Non-nil means cache refile targets to speed up the process.
1978 The cache for a particular file will be updated automatically when
1979 the buffer has been killed, or when any of the marker used for flagging
1980 refile targets no longer points at a live buffer.
1981 If you have added new entries to a buffer that might themselves be targets,
1982 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1983 find that easier, `C-u C-u C-u C-c C-w'."
1984 :group 'org-refile
1985 :type 'boolean)
1987 (defcustom org-refile-use-outline-path nil
1988 "Non-nil means provide refile targets as paths.
1989 So a level 3 headline will be available as level1/level2/level3.
1991 When the value is `file', also include the file name (without directory)
1992 into the path. In this case, you can also stop the completion after
1993 the file name, to get entries inserted as top level in the file.
1995 When `full-file-path', include the full file path."
1996 :group 'org-refile
1997 :type '(choice
1998 (const :tag "Not" nil)
1999 (const :tag "Yes" t)
2000 (const :tag "Start with file name" file)
2001 (const :tag "Start with full file path" full-file-path)))
2003 (defcustom org-outline-path-complete-in-steps t
2004 "Non-nil means complete the outline path in hierarchical steps.
2005 When Org-mode uses the refile interface to select an outline path
2006 \(see variable `org-refile-use-outline-path'), the completion of
2007 the path can be done is a single go, or if can be done in steps down
2008 the headline hierarchy. Going in steps is probably the best if you
2009 do not use a special completion package like `ido' or `icicles'.
2010 However, when using these packages, going in one step can be very
2011 fast, while still showing the whole path to the entry."
2012 :group 'org-refile
2013 :type 'boolean)
2015 (defcustom org-refile-allow-creating-parent-nodes nil
2016 "Non-nil means allow to create new nodes as refile targets.
2017 New nodes are then created by adding \"/new node name\" to the completion
2018 of an existing node. When the value of this variable is `confirm',
2019 new node creation must be confirmed by the user (recommended)
2020 When nil, the completion must match an existing entry.
2022 Note that, if the new heading is not seen by the criteria
2023 listed in `org-refile-targets', multiple instances of the same
2024 heading would be created by trying again to file under the new
2025 heading."
2026 :group 'org-refile
2027 :type '(choice
2028 (const :tag "Never" nil)
2029 (const :tag "Always" t)
2030 (const :tag "Prompt for confirmation" confirm)))
2032 (defcustom org-refile-active-region-within-subtree nil
2033 "Non-nil means also refile active region within a subtree.
2035 By default `org-refile' doesn't allow refiling regions if they
2036 don't contain a set of subtrees, but it might be convenient to
2037 do so sometimes: in that case, the first line of the region is
2038 converted to a headline before refiling."
2039 :group 'org-refile
2040 :type 'boolean)
2042 (defgroup org-todo nil
2043 "Options concerning TODO items in Org-mode."
2044 :tag "Org TODO"
2045 :group 'org)
2047 (defgroup org-progress nil
2048 "Options concerning Progress logging in Org-mode."
2049 :tag "Org Progress"
2050 :group 'org-time)
2052 (defvar org-todo-interpretation-widgets
2053 '((:tag "Sequence (cycling hits every state)" sequence)
2054 (:tag "Type (cycling directly to DONE)" type))
2055 "The available interpretation symbols for customizing `org-todo-keywords'.
2056 Interested libraries should add to this list.")
2058 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2059 "List of TODO entry keyword sequences and their interpretation.
2060 \\<org-mode-map>This is a list of sequences.
2062 Each sequence starts with a symbol, either `sequence' or `type',
2063 indicating if the keywords should be interpreted as a sequence of
2064 action steps, or as different types of TODO items. The first
2065 keywords are states requiring action - these states will select a headline
2066 for inclusion into the global TODO list Org-mode produces. If one of
2067 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2068 signify that no further action is necessary. If \"|\" is not found,
2069 the last keyword is treated as the only DONE state of the sequence.
2071 The command \\[org-todo] cycles an entry through these states, and one
2072 additional state where no keyword is present. For details about this
2073 cycling, see the manual.
2075 TODO keywords and interpretation can also be set on a per-file basis with
2076 the special #+SEQ_TODO and #+TYP_TODO lines.
2078 Each keyword can optionally specify a character for fast state selection
2079 \(in combination with the variable `org-use-fast-todo-selection')
2080 and specifiers for state change logging, using the same syntax
2081 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2082 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2083 indicates to record a time stamp each time this state is selected.
2085 Each keyword may also specify if a timestamp or a note should be
2086 recorded when entering or leaving the state, by adding additional
2087 characters in the parenthesis after the keyword. This looks like this:
2088 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2089 record only the time of the state change. With X and Y being either
2090 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2091 Y when leaving the state if and only if the *target* state does not
2092 define X. You may omit any of the fast-selection key or X or /Y,
2093 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2095 For backward compatibility, this variable may also be just a list
2096 of keywords - in this case the interpretation (sequence or type) will be
2097 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2098 :group 'org-todo
2099 :group 'org-keywords
2100 :type '(choice
2101 (repeat :tag "Old syntax, just keywords"
2102 (string :tag "Keyword"))
2103 (repeat :tag "New syntax"
2104 (cons
2105 (choice
2106 :tag "Interpretation"
2107 ;;Quick and dirty way to see
2108 ;;`org-todo-interpretations'. This takes the
2109 ;;place of item arguments
2110 :convert-widget
2111 (lambda (widget)
2112 (widget-put widget
2113 :args (mapcar
2114 #'(lambda (x)
2115 (widget-convert
2116 (cons 'const x)))
2117 org-todo-interpretation-widgets))
2118 widget))
2119 (repeat
2120 (string :tag "Keyword"))))))
2122 (defvar org-todo-keywords-1 nil
2123 "All TODO and DONE keywords active in a buffer.")
2124 (make-variable-buffer-local 'org-todo-keywords-1)
2125 (defvar org-todo-keywords-for-agenda nil)
2126 (defvar org-done-keywords-for-agenda nil)
2127 (defvar org-drawers-for-agenda nil)
2128 (defvar org-todo-keyword-alist-for-agenda nil)
2129 (defvar org-tag-alist-for-agenda nil)
2130 (defvar org-agenda-contributing-files nil)
2131 (defvar org-not-done-keywords nil)
2132 (make-variable-buffer-local 'org-not-done-keywords)
2133 (defvar org-done-keywords nil)
2134 (make-variable-buffer-local 'org-done-keywords)
2135 (defvar org-todo-heads nil)
2136 (make-variable-buffer-local 'org-todo-heads)
2137 (defvar org-todo-sets nil)
2138 (make-variable-buffer-local 'org-todo-sets)
2139 (defvar org-todo-log-states nil)
2140 (make-variable-buffer-local 'org-todo-log-states)
2141 (defvar org-todo-kwd-alist nil)
2142 (make-variable-buffer-local 'org-todo-kwd-alist)
2143 (defvar org-todo-key-alist nil)
2144 (make-variable-buffer-local 'org-todo-key-alist)
2145 (defvar org-todo-key-trigger nil)
2146 (make-variable-buffer-local 'org-todo-key-trigger)
2148 (defcustom org-todo-interpretation 'sequence
2149 "Controls how TODO keywords are interpreted.
2150 This variable is in principle obsolete and is only used for
2151 backward compatibility, if the interpretation of todo keywords is
2152 not given already in `org-todo-keywords'. See that variable for
2153 more information."
2154 :group 'org-todo
2155 :group 'org-keywords
2156 :type '(choice (const sequence)
2157 (const type)))
2159 (defcustom org-use-fast-todo-selection t
2160 "Non-nil means use the fast todo selection scheme with C-c C-t.
2161 This variable describes if and under what circumstances the cycling
2162 mechanism for TODO keywords will be replaced by a single-key, direct
2163 selection scheme.
2165 When nil, fast selection is never used.
2167 When the symbol `prefix', it will be used when `org-todo' is called with
2168 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2169 in an agenda buffer.
2171 When t, fast selection is used by default. In this case, the prefix
2172 argument forces cycling instead.
2174 In all cases, the special interface is only used if access keys have actually
2175 been assigned by the user, i.e. if keywords in the configuration are followed
2176 by a letter in parenthesis, like TODO(t)."
2177 :group 'org-todo
2178 :type '(choice
2179 (const :tag "Never" nil)
2180 (const :tag "By default" t)
2181 (const :tag "Only with C-u C-c C-t" prefix)))
2183 (defcustom org-provide-todo-statistics t
2184 "Non-nil means update todo statistics after insert and toggle.
2185 ALL-HEADLINES means update todo statistics by including headlines
2186 with no TODO keyword as well, counting them as not done.
2187 A list of TODO keywords means the same, but skip keywords that are
2188 not in this list.
2190 When this is set, todo statistics is updated in the parent of the
2191 current entry each time a todo state is changed."
2192 :group 'org-todo
2193 :type '(choice
2194 (const :tag "Yes, only for TODO entries" t)
2195 (const :tag "Yes, including all entries" 'all-headlines)
2196 (repeat :tag "Yes, for TODOs in this list"
2197 (string :tag "TODO keyword"))
2198 (other :tag "No TODO statistics" nil)))
2200 (defcustom org-hierarchical-todo-statistics t
2201 "Non-nil means TODO statistics covers just direct children.
2202 When nil, all entries in the subtree are considered.
2203 This has only an effect if `org-provide-todo-statistics' is set.
2204 To set this to nil for only a single subtree, use a COOKIE_DATA
2205 property and include the word \"recursive\" into the value."
2206 :group 'org-todo
2207 :type 'boolean)
2209 (defcustom org-after-todo-state-change-hook nil
2210 "Hook which is run after the state of a TODO item was changed.
2211 The new state (a string with a TODO keyword, or nil) is available in the
2212 Lisp variable `state'."
2213 :group 'org-todo
2214 :type 'hook)
2216 (defvar org-blocker-hook nil
2217 "Hook for functions that are allowed to block a state change.
2219 Each function gets as its single argument a property list, see
2220 `org-trigger-hook' for more information about this list.
2222 If any of the functions in this hook returns nil, the state change
2223 is blocked.")
2225 (defvar org-trigger-hook nil
2226 "Hook for functions that are triggered by a state change.
2228 Each function gets as its single argument a property list with at least
2229 the following elements:
2231 (:type type-of-change :position pos-at-entry-start
2232 :from old-state :to new-state)
2234 Depending on the type, more properties may be present.
2236 This mechanism is currently implemented for:
2238 TODO state changes
2239 ------------------
2240 :type todo-state-change
2241 :from previous state (keyword as a string), or nil, or a symbol
2242 'todo' or 'done', to indicate the general type of state.
2243 :to new state, like in :from")
2245 (defcustom org-enforce-todo-dependencies nil
2246 "Non-nil means undone TODO entries will block switching the parent to DONE.
2247 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2248 be blocked if any prior sibling is not yet done.
2249 Finally, if the parent is blocked because of ordered siblings of its own,
2250 the child will also be blocked.
2251 This variable needs to be set before org.el is loaded, and you need to
2252 restart Emacs after a change to make the change effective. The only way
2253 to change is while Emacs is running is through the customize interface."
2254 :set (lambda (var val)
2255 (set var val)
2256 (if val
2257 (add-hook 'org-blocker-hook
2258 'org-block-todo-from-children-or-siblings-or-parent)
2259 (remove-hook 'org-blocker-hook
2260 'org-block-todo-from-children-or-siblings-or-parent)))
2261 :group 'org-todo
2262 :type 'boolean)
2264 (defcustom org-enforce-todo-checkbox-dependencies nil
2265 "Non-nil means unchecked boxes will block switching the parent to DONE.
2266 When this is nil, checkboxes have no influence on switching TODO states.
2267 When non-nil, you first need to check off all check boxes before the TODO
2268 entry can be switched to DONE.
2269 This variable needs to be set before org.el is loaded, and you need to
2270 restart Emacs after a change to make the change effective. The only way
2271 to change is while Emacs is running is through the customize interface."
2272 :set (lambda (var val)
2273 (set var val)
2274 (if val
2275 (add-hook 'org-blocker-hook
2276 'org-block-todo-from-checkboxes)
2277 (remove-hook 'org-blocker-hook
2278 'org-block-todo-from-checkboxes)))
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-treat-insert-todo-heading-as-state-change nil
2283 "Non-nil means inserting a TODO heading is treated as state change.
2284 So when the command \\[org-insert-todo-heading] is used, state change
2285 logging will apply if appropriate. When nil, the new TODO item will
2286 be inserted directly, and no logging will take place."
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2291 "Non-nil means switching TODO states with S-cursor counts as state change.
2292 This is the default behavior. However, setting this to nil allows a
2293 convenient way to select a TODO state and bypass any logging associated
2294 with that."
2295 :group 'org-todo
2296 :type 'boolean)
2298 (defcustom org-todo-state-tags-triggers nil
2299 "Tag changes that should be triggered by TODO state changes.
2300 This is a list. Each entry is
2302 (state-change (tag . flag) .......)
2304 State-change can be a string with a state, and empty string to indicate the
2305 state that has no TODO keyword, or it can be one of the symbols `todo'
2306 or `done', meaning any not-done or done state, respectively."
2307 :group 'org-todo
2308 :group 'org-tags
2309 :type '(repeat
2310 (cons (choice :tag "When changing to"
2311 (const :tag "Not-done state" todo)
2312 (const :tag "Done state" done)
2313 (string :tag "State"))
2314 (repeat
2315 (cons :tag "Tag action"
2316 (string :tag "Tag")
2317 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2319 (defcustom org-log-done nil
2320 "Information to record when a task moves to the DONE state.
2322 Possible values are:
2324 nil Don't add anything, just change the keyword
2325 time Add a time stamp to the task
2326 note Prompt for a note and add it with template `org-log-note-headings'
2328 This option can also be set with on a per-file-basis with
2330 #+STARTUP: nologdone
2331 #+STARTUP: logdone
2332 #+STARTUP: lognotedone
2334 You can have local logging settings for a subtree by setting the LOGGING
2335 property to one or more of these keywords."
2336 :group 'org-todo
2337 :group 'org-progress
2338 :type '(choice
2339 (const :tag "No logging" nil)
2340 (const :tag "Record CLOSED timestamp" time)
2341 (const :tag "Record CLOSED timestamp with note." note)))
2343 ;; Normalize old uses of org-log-done.
2344 (cond
2345 ((eq org-log-done t) (setq org-log-done 'time))
2346 ((and (listp org-log-done) (memq 'done org-log-done))
2347 (setq org-log-done 'note)))
2349 (defcustom org-log-reschedule nil
2350 "Information to record when the scheduling date of a tasks is modified.
2352 Possible values are:
2354 nil Don't add anything, just change the date
2355 time Add a time stamp to the task
2356 note Prompt for a note and add it with template `org-log-note-headings'
2358 This option can also be set with on a per-file-basis with
2360 #+STARTUP: nologreschedule
2361 #+STARTUP: logreschedule
2362 #+STARTUP: lognotereschedule"
2363 :group 'org-todo
2364 :group 'org-progress
2365 :type '(choice
2366 (const :tag "No logging" nil)
2367 (const :tag "Record timestamp" time)
2368 (const :tag "Record timestamp with note." note)))
2370 (defcustom org-log-redeadline nil
2371 "Information to record when the deadline date of a tasks is modified.
2373 Possible values are:
2375 nil Don't add anything, just change the date
2376 time Add a time stamp to the task
2377 note Prompt for a note and add it with template `org-log-note-headings'
2379 This option can also be set with on a per-file-basis with
2381 #+STARTUP: nologredeadline
2382 #+STARTUP: logredeadline
2383 #+STARTUP: lognoteredeadline
2385 You can have local logging settings for a subtree by setting the LOGGING
2386 property to one or more of these keywords."
2387 :group 'org-todo
2388 :group 'org-progress
2389 :type '(choice
2390 (const :tag "No logging" nil)
2391 (const :tag "Record timestamp" time)
2392 (const :tag "Record timestamp with note." note)))
2394 (defcustom org-log-note-clock-out nil
2395 "Non-nil means record a note when clocking out of an item.
2396 This can also be configured on a per-file basis by adding one of
2397 the following lines anywhere in the buffer:
2399 #+STARTUP: lognoteclock-out
2400 #+STARTUP: nolognoteclock-out"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type 'boolean)
2405 (defcustom org-log-done-with-time t
2406 "Non-nil means the CLOSED time stamp will contain date and time.
2407 When nil, only the date will be recorded."
2408 :group 'org-progress
2409 :type 'boolean)
2411 (defcustom org-log-note-headings
2412 '((done . "CLOSING NOTE %t")
2413 (state . "State %-12s from %-12S %t")
2414 (note . "Note taken on %t")
2415 (reschedule . "Rescheduled from %S on %t")
2416 (delschedule . "Not scheduled, was %S on %t")
2417 (redeadline . "New deadline from %S on %t")
2418 (deldeadline . "Removed deadline, was %S on %t")
2419 (refile . "Refiled on %t")
2420 (clock-out . ""))
2421 "Headings for notes added to entries.
2422 The value is an alist, with the car being a symbol indicating the note
2423 context, and the cdr is the heading to be used. The heading may also be the
2424 empty string.
2425 %t in the heading will be replaced by a time stamp.
2426 %T will be an active time stamp instead the default inactive one
2427 %d will be replaced by a short-format time stamp.
2428 %D will be replaced by an active short-format time stamp.
2429 %s will be replaced by the new TODO state, in double quotes.
2430 %S will be replaced by the old TODO state, in double quotes.
2431 %u will be replaced by the user name.
2432 %U will be replaced by the full user name.
2434 In fact, it is not a good idea to change the `state' entry, because
2435 agenda log mode depends on the format of these entries."
2436 :group 'org-todo
2437 :group 'org-progress
2438 :type '(list :greedy t
2439 (cons (const :tag "Heading when closing an item" done) string)
2440 (cons (const :tag
2441 "Heading when changing todo state (todo sequence only)"
2442 state) string)
2443 (cons (const :tag "Heading when just taking a note" note) string)
2444 (cons (const :tag "Heading when clocking out" clock-out) string)
2445 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2446 (cons (const :tag "Heading when rescheduling" reschedule) string)
2447 (cons (const :tag "Heading when changing deadline" redeadline) string)
2448 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2449 (cons (const :tag "Heading when refiling" refile) string)))
2451 (unless (assq 'note org-log-note-headings)
2452 (push '(note . "%t") org-log-note-headings))
2454 (defcustom org-log-into-drawer nil
2455 "Non-nil means insert state change notes and time stamps into a drawer.
2456 When nil, state changes notes will be inserted after the headline and
2457 any scheduling and clock lines, but not inside a drawer.
2459 The value of this variable should be the name of the drawer to use.
2460 LOGBOOK is proposed as the default drawer for this purpose, you can
2461 also set this to a string to define the drawer of your choice.
2463 A value of t is also allowed, representing \"LOGBOOK\".
2465 If this variable is set, `org-log-state-notes-insert-after-drawers'
2466 will be ignored.
2468 You can set the property LOG_INTO_DRAWER to overrule this setting for
2469 a subtree."
2470 :group 'org-todo
2471 :group 'org-progress
2472 :type '(choice
2473 (const :tag "Not into a drawer" nil)
2474 (const :tag "LOGBOOK" t)
2475 (string :tag "Other")))
2477 (if (fboundp 'defvaralias)
2478 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2480 (defun org-log-into-drawer ()
2481 "Return the value of `org-log-into-drawer', but let properties overrule.
2482 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2483 used instead of the default value."
2484 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2485 (cond
2486 ((or (not p) (equal p "nil")) org-log-into-drawer)
2487 ((equal p "t") "LOGBOOK")
2488 (t p))))
2490 (defcustom org-log-state-notes-insert-after-drawers nil
2491 "Non-nil means insert state change notes after any drawers in entry.
2492 Only the drawers that *immediately* follow the headline and the
2493 deadline/scheduled line are skipped.
2494 When nil, insert notes right after the heading and perhaps the line
2495 with deadline/scheduling if present.
2497 This variable will have no effect if `org-log-into-drawer' is
2498 set."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type 'boolean)
2503 (defcustom org-log-states-order-reversed t
2504 "Non-nil means the latest state note will be directly after heading.
2505 When nil, the state change notes will be ordered according to time."
2506 :group 'org-todo
2507 :group 'org-progress
2508 :type 'boolean)
2510 (defcustom org-todo-repeat-to-state nil
2511 "The TODO state to which a repeater should return the repeating task.
2512 By default this is the first task in a TODO sequence, or the previous state
2513 in a TODO_TYP set. But you can specify another task here.
2514 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2515 :group 'org-todo
2516 :type '(choice (const :tag "Head of sequence" nil)
2517 (string :tag "Specific state")))
2519 (defcustom org-log-repeat 'time
2520 "Non-nil means record moving through the DONE state when triggering repeat.
2521 An auto-repeating task is immediately switched back to TODO when
2522 marked DONE. If you are not logging state changes (by adding \"@\"
2523 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2524 record a closing note, there will be no record of the task moving
2525 through DONE. This variable forces taking a note anyway.
2527 nil Don't force a record
2528 time Record a time stamp
2529 note Record a note
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: logrepeat
2534 #+STARTUP: lognoterepeat
2535 #+STARTUP: nologrepeat
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "Don't force a record" nil)
2543 (const :tag "Force recording the DONE state" time)
2544 (const :tag "Force recording a note with the DONE state" note)))
2547 (defgroup org-priorities nil
2548 "Priorities in Org-mode."
2549 :tag "Org Priorities"
2550 :group 'org-todo)
2552 (defcustom org-enable-priority-commands t
2553 "Non-nil means priority commands are active.
2554 When nil, these commands will be disabled, so that you never accidentally
2555 set a priority."
2556 :group 'org-priorities
2557 :type 'boolean)
2559 (defcustom org-highest-priority ?A
2560 "The highest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a smaller ASCII number than `org-lowest-priority'."
2562 :group 'org-priorities
2563 :type 'character)
2565 (defcustom org-lowest-priority ?C
2566 "The lowest priority of TODO items. A character like ?A, ?B etc.
2567 Must have a larger ASCII number than `org-highest-priority'."
2568 :group 'org-priorities
2569 :type 'character)
2571 (defcustom org-default-priority ?B
2572 "The default priority of TODO items.
2573 This is the priority an item gets if no explicit priority is given.
2574 When starting to cycle on an empty priority the first step in the cycle
2575 depends on `org-priority-start-cycle-with-default'. The resulting first
2576 step priority must not exceed the range from `org-highest-priority' to
2577 `org-lowest-priority' which means that `org-default-priority' has to be
2578 in this range exclusive or inclusive the range boundaries. Else the
2579 first step refuses to set the default and the second will fall back
2580 to (depending on the command used) the highest or lowest priority."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-priority-start-cycle-with-default t
2585 "Non-nil means start with default priority when starting to cycle.
2586 When this is nil, the first step in the cycle will be (depending on the
2587 command used) one higher or lower than the default priority.
2588 See also `org-default-priority'."
2589 :group 'org-priorities
2590 :type 'boolean)
2592 (defcustom org-get-priority-function nil
2593 "Function to extract the priority from a string.
2594 The string is normally the headline. If this is nil Org computes the
2595 priority from the priority cookie like [#A] in the headline. It returns
2596 an integer, increasing by 1000 for each priority level.
2597 The user can set a different function here, which should take a string
2598 as an argument and return the numeric priority."
2599 :group 'org-priorities
2600 :type 'function)
2602 (defgroup org-time nil
2603 "Options concerning time stamps and deadlines in Org-mode."
2604 :tag "Org Time"
2605 :group 'org)
2607 (defcustom org-insert-labeled-timestamps-at-point nil
2608 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2609 When nil, these labeled time stamps are forces into the second line of an
2610 entry, just after the headline. When scheduling from the global TODO list,
2611 the time stamp will always be forced into the second line."
2612 :group 'org-time
2613 :type 'boolean)
2615 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2616 "Formats for `format-time-string' which are used for time stamps.
2617 It is not recommended to change this constant.")
2619 (defcustom org-time-stamp-rounding-minutes '(0 5)
2620 "Number of minutes to round time stamps to.
2621 These are two values, the first applies when first creating a time stamp.
2622 The second applies when changing it with the commands `S-up' and `S-down'.
2623 When changing the time stamp, this means that it will change in steps
2624 of N minutes, as given by the second value.
2626 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2627 numbers should be factors of 60, so for example 5, 10, 15.
2629 When this is larger than 1, you can still force an exact time stamp by using
2630 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2631 and by using a prefix arg to `S-up/down' to specify the exact number
2632 of minutes to shift."
2633 :group 'org-time
2634 :get #'(lambda (var) ; Make sure both elements are there
2635 (if (integerp (default-value var))
2636 (list (default-value var) 5)
2637 (default-value var)))
2638 :type '(list
2639 (integer :tag "when inserting times")
2640 (integer :tag "when modifying times")))
2642 ;; Normalize old customizations of this variable.
2643 (when (integerp org-time-stamp-rounding-minutes)
2644 (setq org-time-stamp-rounding-minutes
2645 (list org-time-stamp-rounding-minutes
2646 org-time-stamp-rounding-minutes)))
2648 (defcustom org-display-custom-times nil
2649 "Non-nil means overlay custom formats over all time stamps.
2650 The formats are defined through the variable `org-time-stamp-custom-formats'.
2651 To turn this on on a per-file basis, insert anywhere in the file:
2652 #+STARTUP: customtime"
2653 :group 'org-time
2654 :set 'set-default
2655 :type 'sexp)
2656 (make-variable-buffer-local 'org-display-custom-times)
2658 (defcustom org-time-stamp-custom-formats
2659 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2660 "Custom formats for time stamps. See `format-time-string' for the syntax.
2661 These are overlaid over the default ISO format if the variable
2662 `org-display-custom-times' is set. Time like %H:%M should be at the
2663 end of the second format. The custom formats are also honored by export
2664 commands, if custom time display is turned on at the time of export."
2665 :group 'org-time
2666 :type 'sexp)
2668 (defun org-time-stamp-format (&optional long inactive)
2669 "Get the right format for a time string."
2670 (let ((f (if long (cdr org-time-stamp-formats)
2671 (car org-time-stamp-formats))))
2672 (if inactive
2673 (concat "[" (substring f 1 -1) "]")
2674 f)))
2676 (defcustom org-time-clocksum-format "%d:%02d"
2677 "The format string used when creating CLOCKSUM lines.
2678 This is also used when org-mode generates a time duration."
2679 :group 'org-time
2680 :type 'string)
2682 (defcustom org-time-clocksum-use-fractional nil
2683 "If non-nil, \\[org-clock-display] uses fractional times.
2684 org-mode generates a time duration."
2685 :group 'org-time
2686 :type 'boolean)
2688 (defcustom org-time-clocksum-fractional-format "%.2f"
2689 "The format string used when creating CLOCKSUM lines, or when
2690 org-mode generates a time duration."
2691 :group 'org-time
2692 :type 'string)
2694 (defcustom org-deadline-warning-days 14
2695 "No. of days before expiration during which a deadline becomes active.
2696 This variable governs the display in sparse trees and in the agenda.
2697 When 0 or negative, it means use this number (the absolute value of it)
2698 even if a deadline has a different individual lead time specified.
2700 Custom commands can set this variable in the options section."
2701 :group 'org-time
2702 :group 'org-agenda-daily/weekly
2703 :type 'integer)
2705 (defcustom org-read-date-prefer-future t
2706 "Non-nil means assume future for incomplete date input from user.
2707 This affects the following situations:
2708 1. The user gives a month but not a year.
2709 For example, if it is April and you enter \"feb 2\", this will be read
2710 as Feb 2, *next* year. \"May 5\", however, will be this year.
2711 2. The user gives a day, but no month.
2712 For example, if today is the 15th, and you enter \"3\", Org-mode will
2713 read this as the third of *next* month. However, if you enter \"17\",
2714 it will be considered as *this* month.
2716 If you set this variable to the symbol `time', then also the following
2717 will work:
2719 3. If the user gives a time, but no day. If the time is before now,
2720 to will be interpreted as tomorrow.
2722 Currently none of this works for ISO week specifications.
2724 When this option is nil, the current day, month and year will always be
2725 used as defaults.
2727 See also `org-agenda-jump-prefer-future'."
2728 :group 'org-time
2729 :type '(choice
2730 (const :tag "Never" nil)
2731 (const :tag "Check month and day" t)
2732 (const :tag "Check month, day, and time" time)))
2734 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2735 "Should the agenda jump command prefer the future for incomplete dates?
2736 The default is to do the same as configured in `org-read-date-prefer-future'.
2737 But you can also set a deviating value here.
2738 This may t or nil, or the symbol `org-read-date-prefer-future'."
2739 :group 'org-agenda
2740 :group 'org-time
2741 :type '(choice
2742 (const :tag "Use org-read-date-prefer-future"
2743 org-read-date-prefer-future)
2744 (const :tag "Never" nil)
2745 (const :tag "Always" t)))
2747 (defcustom org-read-date-force-compatible-dates t
2748 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2750 Depending on the system Emacs is running on, certain dates cannot
2751 be represented with the type used internally to represent time.
2752 Dates between 1970-1-1 and 2038-1-1 can always be represented
2753 correctly. Some systems allow for earlier dates, some for later,
2754 some for both. One way to find out it to insert any date into an
2755 Org buffer, putting the cursor on the year and hitting S-up and
2756 S-down to test the range.
2758 When this variable is set to t, the date/time prompt will not let
2759 you specify dates outside the 1970-2037 range, so it is certain that
2760 these dates will work in whatever version of Emacs you are
2761 running, and also that you can move a file from one Emacs implementation
2762 to another. WHenever Org is forcing the year for you, it will display
2763 a message and beep.
2765 When this variable is nil, Org will check if the date is
2766 representable in the specific Emacs implementation you are using.
2767 If not, it will force a year, usually the current year, and beep
2768 to remind you. Currently this setting is not recommended because
2769 the likelihood that you will open your Org files in an Emacs that
2770 has limited date range is not negligible.
2772 A workaround for this problem is to use diary sexp dates for time
2773 stamps outside of this range."
2774 :group 'org-time
2775 :type 'boolean)
2777 (defcustom org-read-date-display-live t
2778 "Non-nil means display current interpretation of date prompt live.
2779 This display will be in an overlay, in the minibuffer."
2780 :group 'org-time
2781 :type 'boolean)
2783 (defcustom org-read-date-popup-calendar t
2784 "Non-nil means pop up a calendar when prompting for a date.
2785 In the calendar, the date can be selected with mouse-1. However, the
2786 minibuffer will also be active, and you can simply enter the date as well.
2787 When nil, only the minibuffer will be available."
2788 :group 'org-time
2789 :type 'boolean)
2790 (if (fboundp 'defvaralias)
2791 (defvaralias 'org-popup-calendar-for-date-prompt
2792 'org-read-date-popup-calendar))
2794 (defcustom org-read-date-minibuffer-setup-hook nil
2795 "Hook to be used to set up keys for the date/time interface.
2796 Add key definitions to `minibuffer-local-map', which will be a temporary
2797 copy."
2798 :group 'org-time
2799 :type 'hook)
2801 (defcustom org-extend-today-until 0
2802 "The hour when your day really ends. Must be an integer.
2803 This has influence for the following applications:
2804 - When switching the agenda to \"today\". It it is still earlier than
2805 the time given here, the day recognized as TODAY is actually yesterday.
2806 - When a date is read from the user and it is still before the time given
2807 here, the current date and time will be assumed to be yesterday, 23:59.
2808 Also, timestamps inserted in remember templates follow this rule.
2810 IMPORTANT: This is a feature whose implementation is and likely will
2811 remain incomplete. Really, it is only here because past midnight seems to
2812 be the favorite working time of John Wiegley :-)"
2813 :group 'org-time
2814 :type 'integer)
2816 (defcustom org-use-effective-time nil
2817 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2818 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2819 \"effective time\" of any timestamps between midnight and 8am will be
2820 23:59 of the previous day."
2821 :group 'boolean
2822 :type 'integer)
2824 (defcustom org-edit-timestamp-down-means-later nil
2825 "Non-nil means S-down will increase the time in a time stamp.
2826 When nil, S-up will increase."
2827 :group 'org-time
2828 :type 'boolean)
2830 (defcustom org-calendar-follow-timestamp-change t
2831 "Non-nil means make the calendar window follow timestamp changes.
2832 When a timestamp is modified and the calendar window is visible, it will be
2833 moved to the new date."
2834 :group 'org-time
2835 :type 'boolean)
2837 (defgroup org-tags nil
2838 "Options concerning tags in Org-mode."
2839 :tag "Org Tags"
2840 :group 'org)
2842 (defcustom org-tag-alist nil
2843 "List of tags allowed in Org-mode files.
2844 When this list is nil, Org-mode will base TAG input on what is already in the
2845 buffer.
2846 The value of this variable is an alist, the car of each entry must be a
2847 keyword as a string, the cdr may be a character that is used to select
2848 that tag through the fast-tag-selection interface.
2849 See the manual for details."
2850 :group 'org-tags
2851 :type '(repeat
2852 (choice
2853 (cons (string :tag "Tag name")
2854 (character :tag "Access char"))
2855 (list :tag "Start radio group"
2856 (const :startgroup)
2857 (option (string :tag "Group description")))
2858 (list :tag "End radio group"
2859 (const :endgroup)
2860 (option (string :tag "Group description")))
2861 (const :tag "New line" (:newline)))))
2863 (defcustom org-tag-persistent-alist nil
2864 "List of tags that will always appear in all Org-mode files.
2865 This is in addition to any in buffer settings or customizations
2866 of `org-tag-alist'.
2867 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2868 The value of this variable is an alist, the car of each entry must be a
2869 keyword as a string, the cdr may be a character that is used to select
2870 that tag through the fast-tag-selection interface.
2871 See the manual for details.
2872 To disable these tags on a per-file basis, insert anywhere in the file:
2873 #+STARTUP: noptag"
2874 :group 'org-tags
2875 :type '(repeat
2876 (choice
2877 (cons (string :tag "Tag name")
2878 (character :tag "Access char"))
2879 (const :tag "Start radio group" (:startgroup))
2880 (const :tag "End radio group" (:endgroup))
2881 (const :tag "New line" (:newline)))))
2883 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2884 "If non-nil, always offer completion for all tags of all agenda files.
2885 Instead of customizing this variable directly, you might want to
2886 set it locally for capture buffers, because there no list of
2887 tags in that file can be created dynamically (there are none).
2889 (add-hook 'org-capture-mode-hook
2890 (lambda ()
2891 (set (make-local-variable
2892 'org-complete-tags-always-offer-all-agenda-tags)
2893 t)))"
2894 :group 'org-tags
2895 :type 'boolean)
2897 (defvar org-file-tags nil
2898 "List of tags that can be inherited by all entries in the file.
2899 The tags will be inherited if the variable `org-use-tag-inheritance'
2900 says they should be.
2901 This variable is populated from #+FILETAGS lines.")
2903 (defcustom org-use-fast-tag-selection 'auto
2904 "Non-nil means use fast tag selection scheme.
2905 This is a special interface to select and deselect tags with single keys.
2906 When nil, fast selection is never used.
2907 When the symbol `auto', fast selection is used if and only if selection
2908 characters for tags have been configured, either through the variable
2909 `org-tag-alist' or through a #+TAGS line in the buffer.
2910 When t, fast selection is always used and selection keys are assigned
2911 automatically if necessary."
2912 :group 'org-tags
2913 :type '(choice
2914 (const :tag "Always" t)
2915 (const :tag "Never" nil)
2916 (const :tag "When selection characters are configured" 'auto)))
2918 (defcustom org-fast-tag-selection-single-key nil
2919 "Non-nil means fast tag selection exits after first change.
2920 When nil, you have to press RET to exit it.
2921 During fast tag selection, you can toggle this flag with `C-c'.
2922 This variable can also have the value `expert'. In this case, the window
2923 displaying the tags menu is not even shown, until you press C-c again."
2924 :group 'org-tags
2925 :type '(choice
2926 (const :tag "No" nil)
2927 (const :tag "Yes" t)
2928 (const :tag "Expert" expert)))
2930 (defvar org-fast-tag-selection-include-todo nil
2931 "Non-nil means fast tags selection interface will also offer TODO states.
2932 This is an undocumented feature, you should not rely on it.")
2934 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2935 "The column to which tags should be indented in a headline.
2936 If this number is positive, it specifies the column. If it is negative,
2937 it means that the tags should be flushright to that column. For example,
2938 -80 works well for a normal 80 character screen.
2939 When 0, place tags directly after headline text, with only one space in
2940 between."
2941 :group 'org-tags
2942 :type 'integer)
2944 (defcustom org-auto-align-tags t
2945 "Non-nil keeps tags aligned when modifying headlines.
2946 Some operations (i.e. demoting) change the length of a headline and
2947 therefore shift the tags around. With this option turned on, after
2948 each such operation the tags are again aligned to `org-tags-column'."
2949 :group 'org-tags
2950 :type 'boolean)
2952 (defcustom org-use-tag-inheritance t
2953 "Non-nil means tags in levels apply also for sublevels.
2954 When nil, only the tags directly given in a specific line apply there.
2955 This may also be a list of tags that should be inherited, or a regexp that
2956 matches tags that should be inherited. Additional control is possible
2957 with the variable `org-tags-exclude-from-inheritance' which gives an
2958 explicit list of tags to be excluded from inheritance., even if the value of
2959 `org-use-tag-inheritance' would select it for inheritance.
2961 If this option is t, a match early-on in a tree can lead to a large
2962 number of matches in the subtree when constructing the agenda or creating
2963 a sparse tree. If you only want to see the first match in a tree during
2964 a search, check out the variable `org-tags-match-list-sublevels'."
2965 :group 'org-tags
2966 :type '(choice
2967 (const :tag "Not" nil)
2968 (const :tag "Always" t)
2969 (repeat :tag "Specific tags" (string :tag "Tag"))
2970 (regexp :tag "Tags matched by regexp")))
2972 (defcustom org-tags-exclude-from-inheritance nil
2973 "List of tags that should never be inherited.
2974 This is a way to exclude a few tags from inheritance. For way to do
2975 the opposite, to actively allow inheritance for selected tags,
2976 see the variable `org-use-tag-inheritance'."
2977 :group 'org-tags
2978 :type '(repeat (string :tag "Tag")))
2980 (defun org-tag-inherit-p (tag)
2981 "Check if TAG is one that should be inherited."
2982 (cond
2983 ((member tag org-tags-exclude-from-inheritance) nil)
2984 ((eq org-use-tag-inheritance t) t)
2985 ((not org-use-tag-inheritance) nil)
2986 ((stringp org-use-tag-inheritance)
2987 (string-match org-use-tag-inheritance tag))
2988 ((listp org-use-tag-inheritance)
2989 (member tag org-use-tag-inheritance))
2990 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2992 (defcustom org-tags-match-list-sublevels t
2993 "Non-nil means list also sublevels of headlines matching a search.
2994 This variable applies to tags/property searches, and also to stuck
2995 projects because this search is based on a tags match as well.
2997 When set to the symbol `indented', sublevels are indented with
2998 leading dots.
3000 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3001 the sublevels of a headline matching a tag search often also match
3002 the same search. Listing all of them can create very long lists.
3003 Setting this variable to nil causes subtrees of a match to be skipped.
3005 This variable is semi-obsolete and probably should always be true. It
3006 is better to limit inheritance to certain tags using the variables
3007 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3008 :group 'org-tags
3009 :type '(choice
3010 (const :tag "No, don't list them" nil)
3011 (const :tag "Yes, do list them" t)
3012 (const :tag "List them, indented with leading dots" indented)))
3014 (defcustom org-tags-sort-function nil
3015 "When set, tags are sorted using this function as a comparator."
3016 :group 'org-tags
3017 :type '(choice
3018 (const :tag "No sorting" nil)
3019 (const :tag "Alphabetical" string<)
3020 (const :tag "Reverse alphabetical" string>)
3021 (function :tag "Custom function" nil)))
3023 (defvar org-tags-history nil
3024 "History of minibuffer reads for tags.")
3025 (defvar org-last-tags-completion-table nil
3026 "The last used completion table for tags.")
3027 (defvar org-after-tags-change-hook nil
3028 "Hook that is run after the tags in a line have changed.")
3030 (defgroup org-properties nil
3031 "Options concerning properties in Org-mode."
3032 :tag "Org Properties"
3033 :group 'org)
3035 (defcustom org-property-format "%-10s %s"
3036 "How property key/value pairs should be formatted by `indent-line'.
3037 When `indent-line' hits a property definition, it will format the line
3038 according to this format, mainly to make sure that the values are
3039 lined-up with respect to each other."
3040 :group 'org-properties
3041 :type 'string)
3043 (defcustom org-properties-postprocess-alist nil
3044 "Alist of properties and functions to adjust inserted values.
3045 Elements of this alist must be of the form
3047 ([string] [function])
3049 where [string] must be a property name and [function] must be a
3050 lambda expression: this lambda expression must take one argument,
3051 the value to adjust, and return the new value as a string.
3053 For example, this element will allow the property \"Remaining\"
3054 to be updated wrt the relation between the \"Effort\" property
3055 and the clock summary:
3057 ((\"Remaining\" (lambda(value)
3058 (let ((clocksum (org-clock-sum-current-item))
3059 (effort (org-duration-string-to-minutes
3060 (org-entry-get (point) \"Effort\"))))
3061 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3062 :group 'org-properties
3063 :type 'alist)
3065 (defcustom org-use-property-inheritance nil
3066 "Non-nil means properties apply also for sublevels.
3068 This setting is chiefly used during property searches. Turning it on can
3069 cause significant overhead when doing a search, which is why it is not
3070 on by default.
3072 When nil, only the properties directly given in the current entry count.
3073 When t, every property is inherited. The value may also be a list of
3074 properties that should have inheritance, or a regular expression matching
3075 properties that should be inherited.
3077 However, note that some special properties use inheritance under special
3078 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3079 and the properties ending in \"_ALL\" when they are used as descriptor
3080 for valid values of a property.
3082 Note for programmers:
3083 When querying an entry with `org-entry-get', you can control if inheritance
3084 should be used. By default, `org-entry-get' looks only at the local
3085 properties. You can request inheritance by setting the inherit argument
3086 to t (to force inheritance) or to `selective' (to respect the setting
3087 in this variable)."
3088 :group 'org-properties
3089 :type '(choice
3090 (const :tag "Not" nil)
3091 (const :tag "Always" t)
3092 (repeat :tag "Specific properties" (string :tag "Property"))
3093 (regexp :tag "Properties matched by regexp")))
3095 (defun org-property-inherit-p (property)
3096 "Check if PROPERTY is one that should be inherited."
3097 (cond
3098 ((eq org-use-property-inheritance t) t)
3099 ((not org-use-property-inheritance) nil)
3100 ((stringp org-use-property-inheritance)
3101 (string-match org-use-property-inheritance property))
3102 ((listp org-use-property-inheritance)
3103 (member property org-use-property-inheritance))
3104 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3106 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3107 "The default column format, if no other format has been defined.
3108 This variable can be set on the per-file basis by inserting a line
3110 #+COLUMNS: %25ITEM ....."
3111 :group 'org-properties
3112 :type 'string)
3114 (defcustom org-columns-ellipses ".."
3115 "The ellipses to be used when a field in column view is truncated.
3116 When this is the empty string, as many characters as possible are shown,
3117 but then there will be no visual indication that the field has been truncated.
3118 When this is a string of length N, the last N characters of a truncated
3119 field are replaced by this string. If the column is narrower than the
3120 ellipses string, only part of the ellipses string will be shown."
3121 :group 'org-properties
3122 :type 'string)
3124 (defcustom org-columns-modify-value-for-display-function nil
3125 "Function that modifies values for display in column view.
3126 For example, it can be used to cut out a certain part from a time stamp.
3127 The function must take 2 arguments:
3129 column-title The title of the column (*not* the property name)
3130 value The value that should be modified.
3132 The function should return the value that should be displayed,
3133 or nil if the normal value should be used."
3134 :group 'org-properties
3135 :type 'function)
3137 (defcustom org-effort-property "Effort"
3138 "The property that is being used to keep track of effort estimates.
3139 Effort estimates given in this property need to have the format H:MM."
3140 :group 'org-properties
3141 :group 'org-progress
3142 :type '(string :tag "Property"))
3144 (defconst org-global-properties-fixed
3145 '(("VISIBILITY_ALL" . "folded children content all")
3146 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3147 "List of property/value pairs that can be inherited by any entry.
3149 These are fixed values, for the preset properties. The user variable
3150 that can be used to add to this list is `org-global-properties'.
3152 The entries in this list are cons cells where the car is a property
3153 name and cdr is a string with the value. If the value represents
3154 multiple items like an \"_ALL\" property, separate the items by
3155 spaces.")
3157 (defcustom org-global-properties nil
3158 "List of property/value pairs that can be inherited by any entry.
3160 This list will be combined with the constant `org-global-properties-fixed'.
3162 The entries in this list are cons cells where the car is a property
3163 name and cdr is a string with the value.
3165 You can set buffer-local values for the same purpose in the variable
3166 `org-file-properties' this by adding lines like
3168 #+PROPERTY: NAME VALUE"
3169 :group 'org-properties
3170 :type '(repeat
3171 (cons (string :tag "Property")
3172 (string :tag "Value"))))
3174 (defvar org-file-properties nil
3175 "List of property/value pairs that can be inherited by any entry.
3176 Valid for the current buffer.
3177 This variable is populated from #+PROPERTY lines.")
3178 (make-variable-buffer-local 'org-file-properties)
3180 (defgroup org-agenda nil
3181 "Options concerning agenda views in Org-mode."
3182 :tag "Org Agenda"
3183 :group 'org)
3185 (defvar org-category nil
3186 "Variable used by org files to set a category for agenda display.
3187 Such files should use a file variable to set it, for example
3189 # -*- mode: org; org-category: \"ELisp\"
3191 or contain a special line
3193 #+CATEGORY: ELisp
3195 If the file does not specify a category, then file's base name
3196 is used instead.")
3197 (make-variable-buffer-local 'org-category)
3198 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3200 (defcustom org-agenda-files nil
3201 "The files to be used for agenda display.
3202 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3203 \\[org-remove-file]. You can also use customize to edit the list.
3205 If an entry is a directory, all files in that directory that are matched by
3206 `org-agenda-file-regexp' will be part of the file list.
3208 If the value of the variable is not a list but a single file name, then
3209 the list of agenda files is actually stored and maintained in that file, one
3210 agenda file per line. In this file paths can be given relative to
3211 `org-directory'. Tilde expansion and environment variable substitution
3212 are also made."
3213 :group 'org-agenda
3214 :type '(choice
3215 (repeat :tag "List of files and directories" file)
3216 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3218 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3219 "Regular expression to match files for `org-agenda-files'.
3220 If any element in the list in that variable contains a directory instead
3221 of a normal file, all files in that directory that are matched by this
3222 regular expression will be included."
3223 :group 'org-agenda
3224 :type 'regexp)
3226 (defcustom org-agenda-text-search-extra-files nil
3227 "List of extra files to be searched by text search commands.
3228 These files will be search in addition to the agenda files by the
3229 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3230 Note that these files will only be searched for text search commands,
3231 not for the other agenda views like todo lists, tag searches or the weekly
3232 agenda. This variable is intended to list notes and possibly archive files
3233 that should also be searched by these two commands.
3234 In fact, if the first element in the list is the symbol `agenda-archives',
3235 than all archive files of all agenda files will be added to the search
3236 scope."
3237 :group 'org-agenda
3238 :type '(set :greedy t
3239 (const :tag "Agenda Archives" agenda-archives)
3240 (repeat :inline t (file))))
3242 (if (fboundp 'defvaralias)
3243 (defvaralias 'org-agenda-multi-occur-extra-files
3244 'org-agenda-text-search-extra-files))
3246 (defcustom org-agenda-skip-unavailable-files nil
3247 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3248 A nil value means to remove them, after a query, from the list."
3249 :group 'org-agenda
3250 :type 'boolean)
3252 (defcustom org-calendar-to-agenda-key [?c]
3253 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3254 The command `org-calendar-goto-agenda' will be bound to this key. The
3255 default is the character `c' because then `c' can be used to switch back and
3256 forth between agenda and calendar."
3257 :group 'org-agenda
3258 :type 'sexp)
3260 (defcustom org-calendar-agenda-action-key [?k]
3261 "The key to be installed in `calendar-mode-map' for agenda-action.
3262 The command `org-agenda-action' will be bound to this key. The
3263 default is the character `k' because we use the same key in the agenda."
3264 :group 'org-agenda
3265 :type 'sexp)
3267 (defcustom org-calendar-insert-diary-entry-key [?i]
3268 "The key to be installed in `calendar-mode-map' for adding diary entries.
3269 This option is irrelevant until `org-agenda-diary-file' has been configured
3270 to point to an Org-mode file. When that is the case, the command
3271 `org-agenda-diary-entry' will be bound to the key given here, by default
3272 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3273 if you want to continue doing this, you need to change this to a different
3274 key."
3275 :group 'org-agenda
3276 :type 'sexp)
3278 (defcustom org-agenda-diary-file 'diary-file
3279 "File to which to add new entries with the `i' key in agenda and calendar.
3280 When this is the symbol `diary-file', the functionality in the Emacs
3281 calendar will be used to add entries to the `diary-file'. But when this
3282 points to a file, `org-agenda-diary-entry' will be used instead."
3283 :group 'org-agenda
3284 :type '(choice
3285 (const :tag "The standard Emacs diary file" diary-file)
3286 (file :tag "Special Org file diary entries")))
3288 (eval-after-load "calendar"
3289 '(progn
3290 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3291 'org-calendar-goto-agenda)
3292 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3293 'org-agenda-action)
3294 (add-hook 'calendar-mode-hook
3295 (lambda ()
3296 (unless (eq org-agenda-diary-file 'diary-file)
3297 (define-key calendar-mode-map
3298 org-calendar-insert-diary-entry-key
3299 'org-agenda-diary-entry))))))
3301 (defgroup org-latex nil
3302 "Options for embedding LaTeX code into Org-mode."
3303 :tag "Org LaTeX"
3304 :group 'org)
3306 (defcustom org-format-latex-options
3307 '(:foreground default :background default :scale 1.0
3308 :html-foreground "Black" :html-background "Transparent"
3309 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3310 "Options for creating images from LaTeX fragments.
3311 This is a property list with the following properties:
3312 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3313 `default' means use the foreground of the default face.
3314 :background the background color, or \"Transparent\".
3315 `default' means use the background of the default face.
3316 :scale a scaling factor for the size of the images, to get more pixels
3317 :html-foreground, :html-background, :html-scale
3318 the same numbers for HTML export.
3319 :matchers a list indicating which matchers should be used to
3320 find LaTeX fragments. Valid members of this list are:
3321 \"begin\" find environments
3322 \"$1\" find single characters surrounded by $.$
3323 \"$\" find math expressions surrounded by $...$
3324 \"$$\" find math expressions surrounded by $$....$$
3325 \"\\(\" find math expressions surrounded by \\(...\\)
3326 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3327 :group 'org-latex
3328 :type 'plist)
3330 (defcustom org-format-latex-signal-error t
3331 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3332 When nil, just push out a message."
3333 :group 'org-latex
3334 :type 'boolean)
3335 (defcustom org-latex-to-mathml-jar-file nil
3336 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3337 Use this to specify additional executable file say a jar file.
3339 When using MathToWeb as the converter, specify the full-path to
3340 your mathtoweb.jar file."
3341 :group 'org-latex
3342 :type '(choice
3343 (const :tag "None" nil)
3344 (file :tag "JAR file" :must-match t)))
3346 (defcustom org-latex-to-mathml-convert-command nil
3347 "Command to convert LaTeX fragments to MathML.
3348 Replace format-specifiers in the command as noted below and use
3349 `shell-command' to convert LaTeX to MathML.
3350 %j: Executable file in fully expanded form as specified by
3351 `org-latex-to-mathml-jar-file'.
3352 %I: Input LaTeX file in fully expanded form
3353 %o: Output MathML file
3354 This command is used by `org-create-math-formula'.
3356 When using MathToWeb as the converter, set this to
3357 \"java -jar %j -unicode -force -df %o %I\"."
3358 :group 'org-latex
3359 :type '(choice
3360 (const :tag "None" nil)
3361 (string :tag "\nShell command")))
3363 (defun org-format-latex-mathml-available-p ()
3364 "Return t if `org-latex-to-mathml-convert-command' is usable."
3365 (save-match-data
3366 (when (and (boundp 'org-latex-to-mathml-convert-command)
3367 org-latex-to-mathml-convert-command)
3368 (let ((executable (car (split-string
3369 org-latex-to-mathml-convert-command))))
3370 (when (executable-find executable)
3371 (if (string-match
3372 "%j" org-latex-to-mathml-convert-command)
3373 (file-readable-p org-latex-to-mathml-jar-file)
3374 t))))))
3376 (defcustom org-format-latex-header "\\documentclass{article}
3377 \\usepackage[usenames]{color}
3378 \\usepackage{amsmath}
3379 \\usepackage[mathscr]{eucal}
3380 \\pagestyle{empty} % do not remove
3381 \[PACKAGES]
3382 \[DEFAULT-PACKAGES]
3383 % The settings below are copied from fullpage.sty
3384 \\setlength{\\textwidth}{\\paperwidth}
3385 \\addtolength{\\textwidth}{-3cm}
3386 \\setlength{\\oddsidemargin}{1.5cm}
3387 \\addtolength{\\oddsidemargin}{-2.54cm}
3388 \\setlength{\\evensidemargin}{\\oddsidemargin}
3389 \\setlength{\\textheight}{\\paperheight}
3390 \\addtolength{\\textheight}{-\\headheight}
3391 \\addtolength{\\textheight}{-\\headsep}
3392 \\addtolength{\\textheight}{-\\footskip}
3393 \\addtolength{\\textheight}{-3cm}
3394 \\setlength{\\topmargin}{1.5cm}
3395 \\addtolength{\\topmargin}{-2.54cm}"
3396 "The document header used for processing LaTeX fragments.
3397 It is imperative that this header make sure that no page number
3398 appears on the page. The package defined in the variables
3399 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3400 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3401 will be appended."
3402 :group 'org-latex
3403 :type 'string)
3405 (defvar org-format-latex-header-extra nil)
3407 (defun org-set-packages-alist (var val)
3408 "Set the packages alist and make sure it has 3 elements per entry."
3409 (set var (mapcar (lambda (x)
3410 (if (and (consp x) (= (length x) 2))
3411 (list (car x) (nth 1 x) t)
3413 val)))
3415 (defun org-get-packages-alist (var)
3417 "Get the packages alist and make sure it has 3 elements per entry."
3418 (mapcar (lambda (x)
3419 (if (and (consp x) (= (length x) 2))
3420 (list (car x) (nth 1 x) t)
3422 (default-value var)))
3424 ;; The following variables are defined here because is it also used
3425 ;; when formatting latex fragments. Originally it was part of the
3426 ;; LaTeX exporter, which is why the name includes "export".
3427 (defcustom org-export-latex-default-packages-alist
3428 '(("AUTO" "inputenc" t)
3429 ("T1" "fontenc" t)
3430 ("" "fixltx2e" nil)
3431 ("" "graphicx" t)
3432 ("" "longtable" nil)
3433 ("" "float" nil)
3434 ("" "wrapfig" nil)
3435 ("" "soul" t)
3436 ("" "textcomp" t)
3437 ("" "marvosym" t)
3438 ("" "wasysym" t)
3439 ("" "latexsym" t)
3440 ("" "amssymb" t)
3441 ("" "hyperref" nil)
3442 "\\tolerance=1000"
3444 "Alist of default packages to be inserted in the header.
3445 Change this only if one of the packages here causes an incompatibility
3446 with another package you are using.
3447 The packages in this list are needed by one part or another of Org-mode
3448 to function properly.
3450 - inputenc, fontenc: for basic font and character selection
3451 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3452 for interpreting the entities in `org-entities'. You can skip some of these
3453 packages if you don't use any of the symbols in it.
3454 - graphicx: for including images
3455 - float, wrapfig: for figure placement
3456 - longtable: for long tables
3457 - hyperref: for cross references
3459 Therefore you should not modify this variable unless you know what you
3460 are doing. The one reason to change it anyway is that you might be loading
3461 some other package that conflicts with one of the default packages.
3462 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3463 If SNIPPET-FLAG is t, the package also needs to be included when
3464 compiling LaTeX snippets into images for inclusion into HTML."
3465 :group 'org-export-latex
3466 :set 'org-set-packages-alist
3467 :get 'org-get-packages-alist
3468 :type '(repeat
3469 (choice
3470 (list :tag "options/package pair"
3471 (string :tag "options")
3472 (string :tag "package")
3473 (boolean :tag "Snippet"))
3474 (string :tag "A line of LaTeX"))))
3476 (defcustom org-export-latex-packages-alist nil
3477 "Alist of packages to be inserted in every LaTeX header.
3478 These will be inserted after `org-export-latex-default-packages-alist'.
3479 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3480 SNIPPET-FLAG, when t, indicates that this package is also needed when
3481 turning LaTeX snippets into images for inclusion into HTML.
3482 Make sure that you only list packages here which:
3483 - you want in every file
3484 - do not conflict with the default packages in
3485 `org-export-latex-default-packages-alist'
3486 - do not conflict with the setup in `org-format-latex-header'."
3487 :group 'org-export-latex
3488 :set 'org-set-packages-alist
3489 :get 'org-get-packages-alist
3490 :type '(repeat
3491 (choice
3492 (list :tag "options/package pair"
3493 (string :tag "options")
3494 (string :tag "package")
3495 (boolean :tag "Snippet"))
3496 (string :tag "A line of LaTeX"))))
3499 (defgroup org-appearance nil
3500 "Settings for Org-mode appearance."
3501 :tag "Org Appearance"
3502 :group 'org)
3504 (defcustom org-level-color-stars-only nil
3505 "Non-nil means fontify only the stars in each headline.
3506 When nil, the entire headline is fontified.
3507 Changing it requires restart of `font-lock-mode' to become effective
3508 also in regions already fontified."
3509 :group 'org-appearance
3510 :type 'boolean)
3512 (defcustom org-hide-leading-stars nil
3513 "Non-nil means hide the first N-1 stars in a headline.
3514 This works by using the face `org-hide' for these stars. This
3515 face is white for a light background, and black for a dark
3516 background. You may have to customize the face `org-hide' to
3517 make this work.
3518 Changing it requires restart of `font-lock-mode' to become effective
3519 also in regions already fontified.
3520 You may also set this on a per-file basis by adding one of the following
3521 lines to the buffer:
3523 #+STARTUP: hidestars
3524 #+STARTUP: showstars"
3525 :group 'org-appearance
3526 :type 'boolean)
3528 (defcustom org-hidden-keywords nil
3529 "List of symbols corresponding to keywords to be hidden the org buffer.
3530 For example, a value '(title) for this list will make the document's title
3531 appear in the buffer without the initial #+TITLE: keyword."
3532 :group 'org-appearance
3533 :type '(set (const :tag "#+AUTHOR" author)
3534 (const :tag "#+DATE" date)
3535 (const :tag "#+EMAIL" email)
3536 (const :tag "#+TITLE" title)))
3538 (defcustom org-fontify-done-headline nil
3539 "Non-nil means change the face of a headline if it is marked DONE.
3540 Normally, only the TODO/DONE keyword indicates the state of a headline.
3541 When this is non-nil, the headline after the keyword is set to the
3542 `org-headline-done' as an additional indication."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-fontify-emphasized-text t
3547 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3548 Changing this variable requires a restart of Emacs to take effect."
3549 :group 'org-appearance
3550 :type 'boolean)
3552 (defcustom org-fontify-whole-heading-line nil
3553 "Non-nil means fontify the whole line for headings.
3554 This is useful when setting a background color for the
3555 org-level-* faces."
3556 :group 'org-appearance
3557 :type 'boolean)
3559 (defcustom org-highlight-latex-fragments-and-specials nil
3560 "Non-nil means fontify what is treated specially by the exporters."
3561 :group 'org-appearance
3562 :type 'boolean)
3564 (defcustom org-hide-emphasis-markers nil
3565 "Non-nil mean font-lock should hide the emphasis marker characters."
3566 :group 'org-appearance
3567 :type 'boolean)
3569 (defcustom org-pretty-entities nil
3570 "Non-nil means show entities as UTF8 characters.
3571 When nil, the \\name form remains in the buffer."
3572 :group 'org-appearance
3573 :type 'boolean)
3575 (defcustom org-pretty-entities-include-sub-superscripts t
3576 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3577 :group 'org-appearance
3578 :type 'boolean)
3580 (defvar org-emph-re nil
3581 "Regular expression for matching emphasis.
3582 After a match, the match groups contain these elements:
3583 0 The match of the full regular expression, including the characters
3584 before and after the proper match
3585 1 The character before the proper match, or empty at beginning of line
3586 2 The proper match, including the leading and trailing markers
3587 3 The leading marker like * or /, indicating the type of highlighting
3588 4 The text between the emphasis markers, not including the markers
3589 5 The character after the match, empty at the end of a line")
3590 (defvar org-verbatim-re nil
3591 "Regular expression for matching verbatim text.")
3592 (defvar org-emphasis-regexp-components) ; defined just below
3593 (defvar org-emphasis-alist) ; defined just below
3594 (defun org-set-emph-re (var val)
3595 "Set variable and compute the emphasis regular expression."
3596 (set var val)
3597 (when (and (boundp 'org-emphasis-alist)
3598 (boundp 'org-emphasis-regexp-components)
3599 org-emphasis-alist org-emphasis-regexp-components)
3600 (let* ((e org-emphasis-regexp-components)
3601 (pre (car e))
3602 (post (nth 1 e))
3603 (border (nth 2 e))
3604 (body (nth 3 e))
3605 (nl (nth 4 e))
3606 (body1 (concat body "*?"))
3607 (markers (mapconcat 'car org-emphasis-alist ""))
3608 (vmarkers (mapconcat
3609 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3610 org-emphasis-alist "")))
3611 ;; make sure special characters appear at the right position in the class
3612 (if (string-match "\\^" markers)
3613 (setq markers (concat (replace-match "" t t markers) "^")))
3614 (if (string-match "-" markers)
3615 (setq markers (concat (replace-match "" t t markers) "-")))
3616 (if (string-match "\\^" vmarkers)
3617 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3618 (if (string-match "-" vmarkers)
3619 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3620 (if (> nl 0)
3621 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3622 (int-to-string nl) "\\}")))
3623 ;; Make the regexp
3624 (setq org-emph-re
3625 (concat "\\([" pre "]\\|^\\)"
3626 "\\("
3627 "\\([" markers "]\\)"
3628 "\\("
3629 "[^" border "]\\|"
3630 "[^" border "]"
3631 body1
3632 "[^" border "]"
3633 "\\)"
3634 "\\3\\)"
3635 "\\([" post "]\\|$\\)"))
3636 (setq org-verbatim-re
3637 (concat "\\([" pre "]\\|^\\)"
3638 "\\("
3639 "\\([" vmarkers "]\\)"
3640 "\\("
3641 "[^" border "]\\|"
3642 "[^" border "]"
3643 body1
3644 "[^" border "]"
3645 "\\)"
3646 "\\3\\)"
3647 "\\([" post "]\\|$\\)")))))
3649 (defcustom org-emphasis-regexp-components
3650 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3651 "Components used to build the regular expression for emphasis.
3652 This is a list with five entries. Terminology: In an emphasis string
3653 like \" *strong word* \", we call the initial space PREMATCH, the final
3654 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3655 and \"trong wor\" is the body. The different components in this variable
3656 specify what is allowed/forbidden in each part:
3658 pre Chars allowed as prematch. Beginning of line will be allowed too.
3659 post Chars allowed as postmatch. End of line will be allowed too.
3660 border The chars *forbidden* as border characters.
3661 body-regexp A regexp like \".\" to match a body character. Don't use
3662 non-shy groups here, and don't allow newline here.
3663 newline The maximum number of newlines allowed in an emphasis exp.
3665 Use customize to modify this, or restart Emacs after changing it."
3666 :group 'org-appearance
3667 :set 'org-set-emph-re
3668 :type '(list
3669 (sexp :tag "Allowed chars in pre ")
3670 (sexp :tag "Allowed chars in post ")
3671 (sexp :tag "Forbidden chars in border ")
3672 (sexp :tag "Regexp for body ")
3673 (integer :tag "number of newlines allowed")
3674 (option (boolean :tag "Please ignore this button"))))
3676 (defcustom org-emphasis-alist
3677 `(("*" bold "<b>" "</b>")
3678 ("/" italic "<i>" "</i>")
3679 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3680 ("=" org-code "<code>" "</code>" verbatim)
3681 ("~" org-verbatim "<code>" "</code>" verbatim)
3682 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3683 "<del>" "</del>")
3685 "Special syntax for emphasized text.
3686 Text starting and ending with a special character will be emphasized, for
3687 example *bold*, _underlined_ and /italic/. This variable sets the marker
3688 characters, the face to be used by font-lock for highlighting in Org-mode
3689 Emacs buffers, and the HTML tags to be used for this.
3690 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3691 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3692 Use customize to modify this, or restart Emacs after changing it."
3693 :group 'org-appearance
3694 :set 'org-set-emph-re
3695 :type '(repeat
3696 (list
3697 (string :tag "Marker character")
3698 (choice
3699 (face :tag "Font-lock-face")
3700 (plist :tag "Face property list"))
3701 (string :tag "HTML start tag")
3702 (string :tag "HTML end tag")
3703 (option (const verbatim)))))
3705 (defvar org-protecting-blocks
3706 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3707 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3708 This is needed for font-lock setup.")
3710 ;;; Miscellaneous options
3712 (defgroup org-completion nil
3713 "Completion in Org-mode."
3714 :tag "Org Completion"
3715 :group 'org)
3717 (defcustom org-completion-use-ido nil
3718 "Non-nil means use ido completion wherever possible.
3719 Note that `ido-mode' must be active for this variable to be relevant.
3720 If you decide to turn this variable on, you might well want to turn off
3721 `org-outline-path-complete-in-steps'.
3722 See also `org-completion-use-iswitchb'."
3723 :group 'org-completion
3724 :type 'boolean)
3726 (defcustom org-completion-use-iswitchb nil
3727 "Non-nil means use iswitchb completion wherever possible.
3728 Note that `iswitchb-mode' must be active for this variable to be relevant.
3729 If you decide to turn this variable on, you might well want to turn off
3730 `org-outline-path-complete-in-steps'.
3731 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3732 :group 'org-completion
3733 :type 'boolean)
3735 (defcustom org-completion-fallback-command 'hippie-expand
3736 "The expansion command called by \\[pcomplete] in normal context.
3737 Normal means, no org-mode-specific context."
3738 :group 'org-completion
3739 :type 'function)
3741 ;;; Functions and variables from their packages
3742 ;; Declared here to avoid compiler warnings
3744 ;; XEmacs only
3745 (defvar outline-mode-menu-heading)
3746 (defvar outline-mode-menu-show)
3747 (defvar outline-mode-menu-hide)
3748 (defvar zmacs-regions) ; XEmacs regions
3750 ;; Emacs only
3751 (defvar mark-active)
3753 ;; Various packages
3754 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3755 (declare-function calendar-forward-day "cal-move" (arg))
3756 (declare-function calendar-goto-date "cal-move" (date))
3757 (declare-function calendar-goto-today "cal-move" ())
3758 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3759 (defvar calc-embedded-close-formula)
3760 (defvar calc-embedded-open-formula)
3761 (declare-function cdlatex-tab "ext:cdlatex" ())
3762 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3763 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3764 (defvar font-lock-unfontify-region-function)
3765 (declare-function iswitchb-read-buffer "iswitchb"
3766 (prompt &optional default require-match start matches-set))
3767 (defvar iswitchb-temp-buflist)
3768 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3769 (defvar org-agenda-tags-todo-honor-ignore-options)
3770 (declare-function org-agenda-skip "org-agenda" ())
3771 (declare-function
3772 org-agenda-format-item "org-agenda"
3773 (extra txt &optional category tags dotime noprefix remove-re habitp))
3774 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3775 (declare-function org-agenda-change-all-lines "org-agenda"
3776 (newhead hdmarker &optional fixface just-this))
3777 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3778 (declare-function org-agenda-maybe-redo "org-agenda" ())
3779 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3780 (beg end))
3781 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3782 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3783 "org-agenda" (&optional end))
3784 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3785 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3786 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3787 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3788 (declare-function org-indent-mode "org-indent" (&optional arg))
3789 (declare-function parse-time-string "parse-time" (string))
3790 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3791 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3792 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3793 (defvar remember-data-file)
3794 (defvar texmathp-why)
3795 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3796 (declare-function table--at-cell-p "table" (position &optional object at-column))
3798 (defvar w3m-current-url)
3799 (defvar w3m-current-title)
3801 (defvar org-latex-regexps)
3803 ;;; Autoload and prepare some org modules
3805 ;; Some table stuff that needs to be defined here, because it is used
3806 ;; by the functions setting up org-mode or checking for table context.
3808 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3809 "Detect an org-type or table-type table.")
3810 (defconst org-table-line-regexp "^[ \t]*|"
3811 "Detect an org-type table line.")
3812 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3813 "Detect an org-type table line.")
3814 (defconst org-table-hline-regexp "^[ \t]*|-"
3815 "Detect an org-type table hline.")
3816 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3817 "Detect a table-type table hline.")
3818 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3819 "Detect the first line outside a table when searching from within it.
3820 This works for both table types.")
3822 ;; Autoload the functions in org-table.el that are needed by functions here.
3824 (eval-and-compile
3825 (org-autoload "org-table"
3826 '(org-table-align org-table-begin org-table-blank-field
3827 org-table-convert org-table-convert-region org-table-copy-down
3828 org-table-copy-region org-table-create
3829 org-table-create-or-convert-from-region
3830 org-table-create-with-table.el org-table-current-dline
3831 org-table-cut-region org-table-delete-column org-table-edit-field
3832 org-table-edit-formulas org-table-end org-table-eval-formula
3833 org-table-export org-table-field-info
3834 org-table-get-stored-formulas org-table-goto-column
3835 org-table-hline-and-move org-table-import org-table-insert-column
3836 org-table-insert-hline org-table-insert-row org-table-iterate
3837 org-table-justify-field-maybe org-table-kill-row
3838 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3839 org-table-move-column org-table-move-column-left
3840 org-table-move-column-right org-table-move-row
3841 org-table-move-row-down org-table-move-row-up
3842 org-table-next-field org-table-next-row org-table-paste-rectangle
3843 org-table-previous-field org-table-recalculate
3844 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3845 org-table-toggle-coordinate-overlays
3846 org-table-toggle-formula-debugger org-table-wrap-region
3847 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3848 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3849 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3851 (defun org-at-table-p (&optional table-type)
3852 "Return t if the cursor is inside an org-type table.
3853 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3854 (if org-enable-table-editor
3855 (save-excursion
3856 (beginning-of-line 1)
3857 (looking-at (if table-type org-table-any-line-regexp
3858 org-table-line-regexp)))
3859 nil))
3860 (defsubst org-table-p () (org-at-table-p))
3862 (defun org-at-table.el-p ()
3863 "Return t if and only if we are at a table.el table."
3864 (and (org-at-table-p 'any)
3865 (save-excursion
3866 (goto-char (org-table-begin 'any))
3867 (looking-at org-table1-hline-regexp))))
3868 (defun org-table-recognize-table.el ()
3869 "If there is a table.el table nearby, recognize it and move into it."
3870 (if org-table-tab-recognizes-table.el
3871 (if (org-at-table.el-p)
3872 (progn
3873 (beginning-of-line 1)
3874 (if (looking-at org-table-dataline-regexp)
3876 (if (looking-at org-table1-hline-regexp)
3877 (progn
3878 (beginning-of-line 2)
3879 (if (looking-at org-table-any-border-regexp)
3880 (beginning-of-line -1)))))
3881 (if (re-search-forward "|" (org-table-end t) t)
3882 (progn
3883 (require 'table)
3884 (if (table--at-cell-p (point))
3886 (message "recognizing table.el table...")
3887 (table-recognize-table)
3888 (message "recognizing table.el table...done")))
3889 (error "This should not happen"))
3891 nil)
3892 nil))
3894 (defun org-at-table-hline-p ()
3895 "Return t if the cursor is inside a hline in a table."
3896 (if org-enable-table-editor
3897 (save-excursion
3898 (beginning-of-line 1)
3899 (looking-at org-table-hline-regexp))
3900 nil))
3902 (defvar org-table-clean-did-remove-column nil)
3904 (defun org-table-map-tables (function &optional quietly)
3905 "Apply FUNCTION to the start of all tables in the buffer."
3906 (save-excursion
3907 (save-restriction
3908 (widen)
3909 (goto-char (point-min))
3910 (while (re-search-forward org-table-any-line-regexp nil t)
3911 (unless quietly
3912 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3913 (beginning-of-line 1)
3914 (when (looking-at org-table-line-regexp)
3915 (save-excursion (funcall function))
3916 (or (looking-at org-table-line-regexp)
3917 (forward-char 1)))
3918 (re-search-forward org-table-any-border-regexp nil 1))))
3919 (unless quietly (message "Mapping tables: done")))
3921 ;; Declare and autoload functions from org-exp.el & Co
3923 (declare-function org-default-export-plist "org-exp")
3924 (declare-function org-infile-export-plist "org-exp")
3925 (declare-function org-get-current-options "org-exp")
3926 (eval-and-compile
3927 (org-autoload "org-exp"
3928 '(org-export org-export-visible
3929 org-insert-export-options-template
3930 org-table-clean-before-export))
3931 (org-autoload "org-ascii"
3932 '(org-export-as-ascii org-export-ascii-preprocess
3933 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3934 org-export-region-as-ascii))
3935 (org-autoload "org-latex"
3936 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3937 org-replace-region-by-latex org-export-region-as-latex
3938 org-export-as-latex org-export-as-pdf
3939 org-export-as-pdf-and-open))
3940 (org-autoload "org-html"
3941 '(org-export-as-html-and-open
3942 org-export-as-html-batch org-export-as-html-to-buffer
3943 org-replace-region-by-html org-export-region-as-html
3944 org-export-as-html))
3945 (org-autoload "org-docbook"
3946 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3947 org-replace-region-by-docbook org-export-region-as-docbook
3948 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3949 org-export-as-docbook))
3950 (org-autoload "org-icalendar"
3951 '(org-export-icalendar-this-file
3952 org-export-icalendar-all-agenda-files
3953 org-export-icalendar-combine-agenda-files))
3954 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3955 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3957 ;; Declare and autoload functions from org-agenda.el
3959 (eval-and-compile
3960 (org-autoload "org-agenda"
3961 '(org-agenda org-agenda-list org-search-view
3962 org-todo-list org-tags-view org-agenda-list-stuck-projects
3963 org-diary org-agenda-to-appt
3964 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3966 ;; Autoload org-remember
3968 (eval-and-compile
3969 (org-autoload "org-remember"
3970 '(org-remember-insinuate org-remember-annotation
3971 org-remember-apply-template org-remember org-remember-handler)))
3973 (eval-and-compile
3974 (org-autoload "org-capture"
3975 '(org-capture org-capture-insert-template-here
3976 org-capture-import-remember-templates)))
3978 ;; Autoload org-clock.el
3980 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3981 (beg end))
3982 (declare-function org-clock-update-mode-line "org-clock" ())
3983 (declare-function org-resolve-clocks "org-clock"
3984 (&optional also-non-dangling-p prompt last-valid))
3985 (defvar org-clock-start-time)
3986 (defvar org-clock-marker (make-marker)
3987 "Marker recording the last clock-in.")
3988 (defvar org-clock-hd-marker (make-marker)
3989 "Marker recording the last clock-in, but the headline position.")
3990 (defvar org-clock-heading ""
3991 "The heading of the current clock entry.")
3992 (defun org-clock-is-active ()
3993 "Return non-nil if clock is currently running.
3994 The return value is actually the clock marker."
3995 (marker-buffer org-clock-marker))
3997 (eval-and-compile
3998 (org-autoload
3999 "org-clock"
4000 '(org-clock-in org-clock-out org-clock-cancel
4001 org-clock-goto org-clock-sum org-clock-display
4002 org-clock-remove-overlays org-clock-report
4003 org-clocktable-shift org-dblock-write:clocktable
4004 org-get-clocktable org-resolve-clocks)))
4006 (defun org-clock-update-time-maybe ()
4007 "If this is a CLOCK line, update it and return t.
4008 Otherwise, return nil."
4009 (interactive)
4010 (save-excursion
4011 (beginning-of-line 1)
4012 (skip-chars-forward " \t")
4013 (when (looking-at org-clock-string)
4014 (let ((re (concat "[ \t]*" org-clock-string
4015 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4016 "\\([ \t]*=>.*\\)?\\)?"))
4017 ts te h m s neg)
4018 (cond
4019 ((not (looking-at re))
4020 nil)
4021 ((not (match-end 2))
4022 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4023 (> org-clock-marker (point))
4024 (<= org-clock-marker (point-at-eol)))
4025 ;; The clock is running here
4026 (setq org-clock-start-time
4027 (apply 'encode-time
4028 (org-parse-time-string (match-string 1))))
4029 (org-clock-update-mode-line)))
4031 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4032 (end-of-line 1)
4033 (setq ts (match-string 1)
4034 te (match-string 3))
4035 (setq s (- (org-float-time
4036 (apply 'encode-time (org-parse-time-string te)))
4037 (org-float-time
4038 (apply 'encode-time (org-parse-time-string ts))))
4039 neg (< s 0)
4040 s (abs s)
4041 h (floor (/ s 3600))
4042 s (- s (* 3600 h))
4043 m (floor (/ s 60))
4044 s (- s (* 60 s)))
4045 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4046 t))))))
4048 (defun org-check-running-clock ()
4049 "Check if the current buffer contains the running clock.
4050 If yes, offer to stop it and to save the buffer with the changes."
4051 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4052 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4053 (buffer-name))))
4054 (org-clock-out)
4055 (when (y-or-n-p "Save changed buffer?")
4056 (save-buffer))))
4058 (defun org-clocktable-try-shift (dir n)
4059 "Check if this line starts a clock table, if yes, shift the time block."
4060 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4061 (org-clocktable-shift dir n)))
4063 ;; Autoload org-timer.el
4065 (eval-and-compile
4066 (org-autoload
4067 "org-timer"
4068 '(org-timer-start org-timer org-timer-item
4069 org-timer-change-times-in-region
4070 org-timer-set-timer
4071 org-timer-reset-timers
4072 org-timer-show-remaining-time)))
4074 ;; Autoload org-feed.el
4076 (eval-and-compile
4077 (org-autoload
4078 "org-feed"
4079 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4082 ;; Autoload org-indent.el
4084 ;; Define the variable already here, to make sure we have it.
4085 (defvar org-indent-mode nil
4086 "Non-nil if Org-Indent mode is enabled.
4087 Use the command `org-indent-mode' to change this variable.")
4089 (eval-and-compile
4090 (org-autoload
4091 "org-indent"
4092 '(org-indent-mode)))
4094 ;; Autoload org-mobile.el
4096 (eval-and-compile
4097 (org-autoload
4098 "org-mobile"
4099 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4101 ;; Autoload archiving code
4102 ;; The stuff that is needed for cycling and tags has to be defined here.
4104 (defgroup org-archive nil
4105 "Options concerning archiving in Org-mode."
4106 :tag "Org Archive"
4107 :group 'org-structure)
4109 (defcustom org-archive-location "%s_archive::"
4110 "The location where subtrees should be archived.
4112 The value of this variable is a string, consisting of two parts,
4113 separated by a double-colon. The first part is a filename and
4114 the second part is a headline.
4116 When the filename is omitted, archiving happens in the same file.
4117 %s in the filename will be replaced by the current file
4118 name (without the directory part). Archiving to a different file
4119 is useful to keep archived entries from contributing to the
4120 Org-mode Agenda.
4122 The archived entries will be filed as subtrees of the specified
4123 headline. When the headline is omitted, the subtrees are simply
4124 filed away at the end of the file, as top-level entries. Also in
4125 the heading you can use %s to represent the file name, this can be
4126 useful when using the same archive for a number of different files.
4128 Here are a few examples:
4129 \"%s_archive::\"
4130 If the current file is Projects.org, archive in file
4131 Projects.org_archive, as top-level trees. This is the default.
4133 \"::* Archived Tasks\"
4134 Archive in the current file, under the top-level headline
4135 \"* Archived Tasks\".
4137 \"~/org/archive.org::\"
4138 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4140 \"~/org/archive.org::* From %s\"
4141 Archive in file ~/org/archive.org (absolute path), under headlines
4142 \"From FILENAME\" where file name is the current file name.
4144 \"basement::** Finished Tasks\"
4145 Archive in file ./basement (relative path), as level 3 trees
4146 below the level 2 heading \"** Finished Tasks\".
4148 You may set this option on a per-file basis by adding to the buffer a
4149 line like
4151 #+ARCHIVE: basement::** Finished Tasks
4153 You may also define it locally for a subtree by setting an ARCHIVE property
4154 in the entry. If such a property is found in an entry, or anywhere up
4155 the hierarchy, it will be used."
4156 :group 'org-archive
4157 :type 'string)
4159 (defcustom org-archive-tag "ARCHIVE"
4160 "The tag that marks a subtree as archived.
4161 An archived subtree does not open during visibility cycling, and does
4162 not contribute to the agenda listings.
4163 After changing this, font-lock must be restarted in the relevant buffers to
4164 get the proper fontification."
4165 :group 'org-archive
4166 :group 'org-keywords
4167 :type 'string)
4169 (defcustom org-agenda-skip-archived-trees t
4170 "Non-nil means the agenda will skip any items located in archived trees.
4171 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4172 variable is no longer recommended, you should leave it at the value t.
4173 Instead, use the key `v' to cycle the archives-mode in the agenda."
4174 :group 'org-archive
4175 :group 'org-agenda-skip
4176 :type 'boolean)
4178 (defcustom org-columns-skip-archived-trees t
4179 "Non-nil means ignore archived trees when creating column view."
4180 :group 'org-archive
4181 :group 'org-properties
4182 :type 'boolean)
4184 (defcustom org-cycle-open-archived-trees nil
4185 "Non-nil means `org-cycle' will open archived trees.
4186 An archived tree is a tree marked with the tag ARCHIVE.
4187 When nil, archived trees will stay folded. You can still open them with
4188 normal outline commands like `show-all', but not with the cycling commands."
4189 :group 'org-archive
4190 :group 'org-cycle
4191 :type 'boolean)
4193 (defcustom org-sparse-tree-open-archived-trees nil
4194 "Non-nil means sparse tree construction shows matches in archived trees.
4195 When nil, matches in these trees are highlighted, but the trees are kept in
4196 collapsed state."
4197 :group 'org-archive
4198 :group 'org-sparse-trees
4199 :type 'boolean)
4201 (defun org-cycle-hide-archived-subtrees (state)
4202 "Re-hide all archived subtrees after a visibility state change."
4203 (when (and (not org-cycle-open-archived-trees)
4204 (not (memq state '(overview folded))))
4205 (save-excursion
4206 (let* ((globalp (memq state '(contents all)))
4207 (beg (if globalp (point-min) (point)))
4208 (end (if globalp (point-max) (org-end-of-subtree t))))
4209 (org-hide-archived-subtrees beg end)
4210 (goto-char beg)
4211 (if (looking-at (concat ".*:" org-archive-tag ":"))
4212 (message "%s" (substitute-command-keys
4213 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4215 (defun org-force-cycle-archived ()
4216 "Cycle subtree even if it is archived."
4217 (interactive)
4218 (setq this-command 'org-cycle)
4219 (let ((org-cycle-open-archived-trees t))
4220 (call-interactively 'org-cycle)))
4222 (defun org-hide-archived-subtrees (beg end)
4223 "Re-hide all archived subtrees after a visibility state change."
4224 (save-excursion
4225 (let* ((re (concat ":" org-archive-tag ":")))
4226 (goto-char beg)
4227 (while (re-search-forward re end t)
4228 (when (org-at-heading-p)
4229 (org-flag-subtree t)
4230 (org-end-of-subtree t))))))
4232 (defun org-flag-subtree (flag)
4233 (save-excursion
4234 (org-back-to-heading t)
4235 (outline-end-of-heading)
4236 (outline-flag-region (point)
4237 (progn (org-end-of-subtree t) (point))
4238 flag)))
4240 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4242 (eval-and-compile
4243 (org-autoload "org-archive"
4244 '(org-add-archive-files org-archive-subtree
4245 org-archive-to-archive-sibling org-toggle-archive-tag
4246 org-archive-subtree-default
4247 org-archive-subtree-default-with-confirmation)))
4249 ;; Autoload Column View Code
4251 (declare-function org-columns-number-to-string "org-colview")
4252 (declare-function org-columns-get-format-and-top-level "org-colview")
4253 (declare-function org-columns-compute "org-colview")
4255 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4256 '(org-columns-number-to-string org-columns-get-format-and-top-level
4257 org-columns-compute org-agenda-columns org-columns-remove-overlays
4258 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4260 ;; Autoload ID code
4262 (declare-function org-id-store-link "org-id")
4263 (declare-function org-id-locations-load "org-id")
4264 (declare-function org-id-locations-save "org-id")
4265 (defvar org-id-track-globally)
4266 (org-autoload "org-id"
4267 '(org-id-get-create org-id-new org-id-copy org-id-get
4268 org-id-get-with-outline-path-completion
4269 org-id-get-with-outline-drilling org-id-store-link
4270 org-id-goto org-id-find org-id-store-link))
4272 ;; Autoload Plotting Code
4274 (org-autoload "org-plot"
4275 '(org-plot/gnuplot))
4277 ;;; Variables for pre-computed regular expressions, all buffer local
4279 (defvar org-drawer-regexp nil
4280 "Matches first line of a hidden block.")
4281 (make-variable-buffer-local 'org-drawer-regexp)
4282 (defvar org-todo-regexp nil
4283 "Matches any of the TODO state keywords.")
4284 (make-variable-buffer-local 'org-todo-regexp)
4285 (defvar org-not-done-regexp nil
4286 "Matches any of the TODO state keywords except the last one.")
4287 (make-variable-buffer-local 'org-not-done-regexp)
4288 (defvar org-not-done-heading-regexp nil
4289 "Matches a TODO headline that is not done.")
4290 (make-variable-buffer-local 'org-not-done-regexp)
4291 (defvar org-todo-line-regexp nil
4292 "Matches a headline and puts TODO state into group 2 if present.")
4293 (make-variable-buffer-local 'org-todo-line-regexp)
4294 (defvar org-complex-heading-regexp nil
4295 "Matches a headline and puts everything into groups:
4296 group 1: the stars
4297 group 2: The todo keyword, maybe
4298 group 3: Priority cookie
4299 group 4: True headline
4300 group 5: Tags")
4301 (make-variable-buffer-local 'org-complex-heading-regexp)
4302 (defvar org-complex-heading-regexp-format nil
4303 "Printf format to make regexp to match an exact headline.
4304 This regexp will match the headline of any node which has the
4305 exact headline text that is put into the format, but may have any
4306 TODO state, priority and tags.")
4307 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4308 (defvar org-todo-line-tags-regexp nil
4309 "Matches a headline and puts TODO state into group 2 if present.
4310 Also put tags into group 4 if tags are present.")
4311 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4312 (defvar org-ds-keyword-length 12
4313 "Maximum length of the Deadline and SCHEDULED keywords.")
4314 (make-variable-buffer-local 'org-ds-keyword-length)
4315 (defvar org-deadline-regexp nil
4316 "Matches the DEADLINE keyword.")
4317 (make-variable-buffer-local 'org-deadline-regexp)
4318 (defvar org-deadline-time-regexp nil
4319 "Matches the DEADLINE keyword together with a time stamp.")
4320 (make-variable-buffer-local 'org-deadline-time-regexp)
4321 (defvar org-deadline-line-regexp nil
4322 "Matches the DEADLINE keyword and the rest of the line.")
4323 (make-variable-buffer-local 'org-deadline-line-regexp)
4324 (defvar org-scheduled-regexp nil
4325 "Matches the SCHEDULED keyword.")
4326 (make-variable-buffer-local 'org-scheduled-regexp)
4327 (defvar org-scheduled-time-regexp nil
4328 "Matches the SCHEDULED keyword together with a time stamp.")
4329 (make-variable-buffer-local 'org-scheduled-time-regexp)
4330 (defvar org-closed-time-regexp nil
4331 "Matches the CLOSED keyword together with a time stamp.")
4332 (make-variable-buffer-local 'org-closed-time-regexp)
4334 (defvar org-keyword-time-regexp nil
4335 "Matches any of the 4 keywords, together with the time stamp.")
4336 (make-variable-buffer-local 'org-keyword-time-regexp)
4337 (defvar org-keyword-time-not-clock-regexp nil
4338 "Matches any of the 3 keywords, together with the time stamp.")
4339 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4340 (defvar org-maybe-keyword-time-regexp nil
4341 "Matches a timestamp, possibly preceded by a keyword.")
4342 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4343 (defvar org-planning-or-clock-line-re nil
4344 "Matches a line with planning or clock info.")
4345 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4346 (defvar org-all-time-keywords nil
4347 "List of time keywords.")
4348 (make-variable-buffer-local 'org-all-time-keywords)
4350 (defconst org-plain-time-of-day-regexp
4351 (concat
4352 "\\(\\<[012]?[0-9]"
4353 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4354 "\\(--?"
4355 "\\(\\<[012]?[0-9]"
4356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4357 "\\)?")
4358 "Regular expression to match a plain time or time range.
4359 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4360 groups carry important information:
4361 0 the full match
4362 1 the first time, range or not
4363 8 the second time, if it is a range.")
4365 (defconst org-plain-time-extension-regexp
4366 (concat
4367 "\\(\\<[012]?[0-9]"
4368 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4369 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4370 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4371 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4372 groups carry important information:
4373 0 the full match
4374 7 hours of duration
4375 9 minutes of duration")
4377 (defconst org-stamp-time-of-day-regexp
4378 (concat
4379 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4380 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4381 "\\(--?"
4382 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4383 "Regular expression to match a timestamp time or time range.
4384 After a match, the following groups carry important information:
4385 0 the full match
4386 1 date plus weekday, for back referencing to make sure both times are on the same day
4387 2 the first time, range or not
4388 4 the second time, if it is a range.")
4390 (defconst org-startup-options
4391 '(("fold" org-startup-folded t)
4392 ("overview" org-startup-folded t)
4393 ("nofold" org-startup-folded nil)
4394 ("showall" org-startup-folded nil)
4395 ("showeverything" org-startup-folded showeverything)
4396 ("content" org-startup-folded content)
4397 ("indent" org-startup-indented t)
4398 ("noindent" org-startup-indented nil)
4399 ("hidestars" org-hide-leading-stars t)
4400 ("showstars" org-hide-leading-stars nil)
4401 ("odd" org-odd-levels-only t)
4402 ("oddeven" org-odd-levels-only nil)
4403 ("align" org-startup-align-all-tables t)
4404 ("noalign" org-startup-align-all-tables nil)
4405 ("inlineimages" org-startup-with-inline-images t)
4406 ("noinlineimages" org-startup-with-inline-images nil)
4407 ("customtime" org-display-custom-times t)
4408 ("logdone" org-log-done time)
4409 ("lognotedone" org-log-done note)
4410 ("nologdone" org-log-done nil)
4411 ("lognoteclock-out" org-log-note-clock-out t)
4412 ("nolognoteclock-out" org-log-note-clock-out nil)
4413 ("logrepeat" org-log-repeat state)
4414 ("lognoterepeat" org-log-repeat note)
4415 ("nologrepeat" org-log-repeat nil)
4416 ("logreschedule" org-log-reschedule time)
4417 ("lognotereschedule" org-log-reschedule note)
4418 ("nologreschedule" org-log-reschedule nil)
4419 ("logredeadline" org-log-redeadline time)
4420 ("lognoteredeadline" org-log-redeadline note)
4421 ("nologredeadline" org-log-redeadline nil)
4422 ("logrefile" org-log-refile time)
4423 ("lognoterefile" org-log-refile note)
4424 ("nologrefile" org-log-refile nil)
4425 ("fninline" org-footnote-define-inline t)
4426 ("nofninline" org-footnote-define-inline nil)
4427 ("fnlocal" org-footnote-section nil)
4428 ("fnauto" org-footnote-auto-label t)
4429 ("fnprompt" org-footnote-auto-label nil)
4430 ("fnconfirm" org-footnote-auto-label confirm)
4431 ("fnplain" org-footnote-auto-label plain)
4432 ("fnadjust" org-footnote-auto-adjust t)
4433 ("nofnadjust" org-footnote-auto-adjust nil)
4434 ("constcgs" constants-unit-system cgs)
4435 ("constSI" constants-unit-system SI)
4436 ("noptag" org-tag-persistent-alist nil)
4437 ("hideblocks" org-hide-block-startup t)
4438 ("nohideblocks" org-hide-block-startup nil)
4439 ("beamer" org-startup-with-beamer-mode t)
4440 ("entitiespretty" org-pretty-entities t)
4441 ("entitiesplain" org-pretty-entities nil))
4442 "Variable associated with STARTUP options for org-mode.
4443 Each element is a list of three items: The startup options as written
4444 in the #+STARTUP line, the corresponding variable, and the value to
4445 set this variable to if the option is found. An optional forth element PUSH
4446 means to push this value onto the list in the variable.")
4448 (defun org-update-property-plist (key val props)
4449 "Update PROPS with KEY and VAL."
4450 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4451 (key (if appending (substring key 0 (- (length key) 1)) key))
4452 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4453 (previous (cdr (assoc key props))))
4454 (if appending
4455 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4456 (cons (cons key val) remainder))))
4458 (defconst org-block-regexp
4459 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4460 "Regular expression for hiding blocks.")
4461 (defconst org-heading-keyword-regexp-format
4462 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4463 "Printf format for a regexp matching an headline with some keyword.
4464 This regexp will match the headline of any node which has the
4465 exact keyword that is put into the format. The keyword isn't in
4466 any group by default, but the stars and the body are.")
4467 (defconst org-heading-keyword-maybe-regexp-format
4468 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4469 "Printf format for a regexp matching an headline, possibly with some keyword.
4470 This regexp can match any headline with the specified keyword, or
4471 without a keyword. The keyword isn't in any group by default,
4472 but the stars and the body are.")
4474 (defun org-set-regexps-and-options ()
4475 "Precompute regular expressions for current buffer."
4476 (when (eq major-mode 'org-mode)
4477 (org-set-local 'org-todo-kwd-alist nil)
4478 (org-set-local 'org-todo-key-alist nil)
4479 (org-set-local 'org-todo-key-trigger nil)
4480 (org-set-local 'org-todo-keywords-1 nil)
4481 (org-set-local 'org-done-keywords nil)
4482 (org-set-local 'org-todo-heads nil)
4483 (org-set-local 'org-todo-sets nil)
4484 (org-set-local 'org-todo-log-states nil)
4485 (org-set-local 'org-file-properties nil)
4486 (org-set-local 'org-file-tags nil)
4487 (let ((re (org-make-options-regexp
4488 '("CATEGORY" "TODO" "COLUMNS"
4489 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4490 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4491 "OPTIONS")
4492 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4493 (splitre "[ \t]+")
4494 (scripts org-use-sub-superscripts)
4495 kwds kws0 kwsa key log value cat arch tags const links hw dws
4496 tail sep kws1 prio props ftags drawers beamer-p
4497 ext-setup-or-nil setup-contents (start 0))
4498 (save-excursion
4499 (save-restriction
4500 (widen)
4501 (goto-char (point-min))
4502 (while (or (and ext-setup-or-nil
4503 (string-match re ext-setup-or-nil start)
4504 (setq start (match-end 0)))
4505 (and (setq ext-setup-or-nil nil start 0)
4506 (re-search-forward re nil t)))
4507 (setq key (upcase (match-string 1 ext-setup-or-nil))
4508 value (org-match-string-no-properties 2 ext-setup-or-nil))
4509 (if (stringp value) (setq value (org-trim value)))
4510 (cond
4511 ((equal key "CATEGORY")
4512 (setq cat value))
4513 ((member key '("SEQ_TODO" "TODO"))
4514 (push (cons 'sequence (org-split-string value splitre)) kwds))
4515 ((equal key "TYP_TODO")
4516 (push (cons 'type (org-split-string value splitre)) kwds))
4517 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4518 ;; general TODO-like setup
4519 (push (cons (intern (downcase (match-string 1 key)))
4520 (org-split-string value splitre)) kwds))
4521 ((equal key "TAGS")
4522 (setq tags (append tags (if tags '("\\n") nil)
4523 (org-split-string value splitre))))
4524 ((equal key "COLUMNS")
4525 (org-set-local 'org-columns-default-format value))
4526 ((equal key "LINK")
4527 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4528 (push (cons (match-string 1 value)
4529 (org-trim (match-string 2 value)))
4530 links)))
4531 ((equal key "PRIORITIES")
4532 (setq prio (org-split-string value " +")))
4533 ((equal key "PROPERTY")
4534 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4535 (setq props (org-update-property-plist (match-string 1 value)
4536 (match-string 2 value)
4537 props))))
4538 ((equal key "FILETAGS")
4539 (when (string-match "\\S-" value)
4540 (setq ftags
4541 (append
4542 ftags
4543 (apply 'append
4544 (mapcar (lambda (x) (org-split-string x ":"))
4545 (org-split-string value)))))))
4546 ((equal key "DRAWERS")
4547 (setq drawers (org-split-string value splitre)))
4548 ((equal key "CONSTANTS")
4549 (setq const (append const (org-split-string value splitre))))
4550 ((equal key "STARTUP")
4551 (let ((opts (org-split-string value splitre))
4552 l var val)
4553 (while (setq l (pop opts))
4554 (when (setq l (assoc l org-startup-options))
4555 (setq var (nth 1 l) val (nth 2 l))
4556 (if (not (nth 3 l))
4557 (set (make-local-variable var) val)
4558 (if (not (listp (symbol-value var)))
4559 (set (make-local-variable var) nil))
4560 (set (make-local-variable var) (symbol-value var))
4561 (add-to-list var val))))))
4562 ((equal key "ARCHIVE")
4563 (setq arch value)
4564 (remove-text-properties 0 (length arch)
4565 '(face t fontified t) arch))
4566 ((equal key "LATEX_CLASS")
4567 (setq beamer-p (equal value "beamer")))
4568 ((equal key "OPTIONS")
4569 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4570 (setq scripts (read (match-string 2 value)))))
4571 ((equal key "SETUPFILE")
4572 (setq setup-contents (org-file-contents
4573 (expand-file-name
4574 (org-remove-double-quotes value))
4575 'noerror))
4576 (if (not ext-setup-or-nil)
4577 (setq ext-setup-or-nil setup-contents start 0)
4578 (setq ext-setup-or-nil
4579 (concat (substring ext-setup-or-nil 0 start)
4580 "\n" setup-contents "\n"
4581 (substring ext-setup-or-nil start)))))))
4582 ;; search for property blocks
4583 (goto-char (point-min))
4584 (while (re-search-forward org-block-regexp nil t)
4585 (when (equal "PROPERTY" (upcase (match-string 1)))
4586 (setq value (replace-regexp-in-string
4587 "[\n\r]" " " (match-string 4)))
4588 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4589 (setq props (org-update-property-plist (match-string 1 value)
4590 (match-string 2 value)
4591 props)))))))
4592 (org-set-local 'org-use-sub-superscripts scripts)
4593 (when cat
4594 (org-set-local 'org-category (intern cat))
4595 (push (cons "CATEGORY" cat) props))
4596 (when prio
4597 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4598 (setq prio (mapcar 'string-to-char prio))
4599 (org-set-local 'org-highest-priority (nth 0 prio))
4600 (org-set-local 'org-lowest-priority (nth 1 prio))
4601 (org-set-local 'org-default-priority (nth 2 prio)))
4602 (and props (org-set-local 'org-file-properties (nreverse props)))
4603 (and ftags (org-set-local 'org-file-tags
4604 (mapcar 'org-add-prop-inherited ftags)))
4605 (and drawers (org-set-local 'org-drawers drawers))
4606 (and arch (org-set-local 'org-archive-location arch))
4607 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4608 ;; Process the TODO keywords
4609 (unless kwds
4610 ;; Use the global values as if they had been given locally.
4611 (setq kwds (default-value 'org-todo-keywords))
4612 (if (stringp (car kwds))
4613 (setq kwds (list (cons org-todo-interpretation
4614 (default-value 'org-todo-keywords)))))
4615 (setq kwds (reverse kwds)))
4616 (setq kwds (nreverse kwds))
4617 (let (inter kws kw)
4618 (while (setq kws (pop kwds))
4619 (let ((kws (or
4620 (run-hook-with-args-until-success
4621 'org-todo-setup-filter-hook kws)
4622 kws)))
4623 (setq inter (pop kws) sep (member "|" kws)
4624 kws0 (delete "|" (copy-sequence kws))
4625 kwsa nil
4626 kws1 (mapcar
4627 (lambda (x)
4628 ;; 1 2
4629 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4630 (progn
4631 (setq kw (match-string 1 x)
4632 key (and (match-end 2) (match-string 2 x))
4633 log (org-extract-log-state-settings x))
4634 (push (cons kw (and key (string-to-char key))) kwsa)
4635 (and log (push log org-todo-log-states))
4637 (error "Invalid TODO keyword %s" x)))
4638 kws0)
4639 kwsa (if kwsa (append '((:startgroup))
4640 (nreverse kwsa)
4641 '((:endgroup))))
4642 hw (car kws1)
4643 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4644 tail (list inter hw (car dws) (org-last dws))))
4645 (add-to-list 'org-todo-heads hw 'append)
4646 (push kws1 org-todo-sets)
4647 (setq org-done-keywords (append org-done-keywords dws nil))
4648 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4649 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4650 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4651 (setq org-todo-sets (nreverse org-todo-sets)
4652 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4653 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4654 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4655 ;; Process the constants
4656 (when const
4657 (let (e cst)
4658 (while (setq e (pop const))
4659 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4660 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4661 (setq org-table-formula-constants-local cst)))
4663 ;; Process the tags.
4664 (when tags
4665 (let (e tgs)
4666 (while (setq e (pop tags))
4667 (cond
4668 ((equal e "{") (push '(:startgroup) tgs))
4669 ((equal e "}") (push '(:endgroup) tgs))
4670 ((equal e "\\n") (push '(:newline) tgs))
4671 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4672 (push (cons (match-string 1 e)
4673 (string-to-char (match-string 2 e)))
4674 tgs))
4675 (t (push (list e) tgs))))
4676 (org-set-local 'org-tag-alist nil)
4677 (while (setq e (pop tgs))
4678 (or (and (stringp (car e))
4679 (assoc (car e) org-tag-alist))
4680 (push e org-tag-alist)))))
4682 ;; Compute the regular expressions and other local variables.
4683 ;; Using `org-outline-regexp-bol' would complicate them much,
4684 ;; because of the fixed white space at the end of that string.
4685 (if (not org-done-keywords)
4686 (setq org-done-keywords (and org-todo-keywords-1
4687 (list (org-last org-todo-keywords-1)))))
4688 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4689 (length org-scheduled-string)
4690 (length org-clock-string)
4691 (length org-closed-string)))
4692 org-drawer-regexp
4693 (concat "^[ \t]*:\\("
4694 (mapconcat 'regexp-quote org-drawers "\\|")
4695 "\\):[ \t]*$")
4696 org-not-done-keywords
4697 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4698 org-todo-regexp
4699 (concat "\\("
4700 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4701 "\\)")
4702 org-not-done-regexp
4703 (concat "\\("
4704 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4705 "\\)")
4706 org-not-done-heading-regexp
4707 (format org-heading-keyword-regexp-format org-not-done-regexp)
4708 org-todo-line-regexp
4709 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4710 org-complex-heading-regexp
4711 (concat "^\\(\\*+\\)"
4712 "\\(?: +" org-todo-regexp "\\)?"
4713 "\\(?: +\\(\\[#.\\]\\)\\)?"
4714 "\\(?: +\\(.*?\\)\\)?"
4715 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4716 "[ \t]*$")
4717 org-complex-heading-regexp-format
4718 (concat "^\\(\\*+\\)"
4719 "\\(?: +" org-todo-regexp "\\)?"
4720 "\\(?: +\\(\\[#.\\]\\)\\)?"
4721 "\\(?: +"
4722 ;; Stats cookies can be stuck to body.
4723 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4724 "\\(%s\\)"
4725 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4726 "\\)"
4727 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4728 "[ \t]*$")
4729 org-todo-line-tags-regexp
4730 (concat "^\\(\\*+\\)"
4731 "\\(?: +" org-todo-regexp "\\)?"
4732 "\\(?: +\\(.*?\\)\\)?"
4733 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4734 "[ \t]*$")
4735 org-deadline-regexp (concat "\\<" org-deadline-string)
4736 org-deadline-time-regexp
4737 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4738 org-deadline-line-regexp
4739 (concat "\\<\\(" org-deadline-string "\\).*")
4740 org-scheduled-regexp
4741 (concat "\\<" org-scheduled-string)
4742 org-scheduled-time-regexp
4743 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4744 org-closed-time-regexp
4745 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4746 org-keyword-time-regexp
4747 (concat "\\<\\(" org-scheduled-string
4748 "\\|" org-deadline-string
4749 "\\|" org-closed-string
4750 "\\|" org-clock-string "\\)"
4751 " *[[<]\\([^]>]+\\)[]>]")
4752 org-keyword-time-not-clock-regexp
4753 (concat "\\<\\(" org-scheduled-string
4754 "\\|" org-deadline-string
4755 "\\|" org-closed-string
4756 "\\)"
4757 " *[[<]\\([^]>]+\\)[]>]")
4758 org-maybe-keyword-time-regexp
4759 (concat "\\(\\<\\(" org-scheduled-string
4760 "\\|" org-deadline-string
4761 "\\|" org-closed-string
4762 "\\|" org-clock-string "\\)\\)?"
4763 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4764 org-planning-or-clock-line-re
4765 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4766 "\\|" org-deadline-string
4767 "\\|" org-closed-string "\\|" org-clock-string
4768 "\\)\\>\\)")
4769 org-all-time-keywords
4770 (mapcar (lambda (w) (substring w 0 -1))
4771 (list org-scheduled-string org-deadline-string
4772 org-clock-string org-closed-string))
4774 (org-compute-latex-and-specials-regexp)
4775 (org-set-font-lock-defaults))))
4777 (defun org-file-contents (file &optional noerror)
4778 "Return the contents of FILE, as a string."
4779 (if (or (not file)
4780 (not (file-readable-p file)))
4781 (if noerror
4782 (progn
4783 (message "Cannot read file \"%s\"" file)
4784 (ding) (sit-for 2)
4786 (error "Cannot read file \"%s\"" file))
4787 (with-temp-buffer
4788 (insert-file-contents file)
4789 (buffer-string))))
4791 (defun org-extract-log-state-settings (x)
4792 "Extract the log state setting from a TODO keyword string.
4793 This will extract info from a string like \"WAIT(w@/!)\"."
4794 (let (kw key log1 log2)
4795 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4796 (setq kw (match-string 1 x)
4797 key (and (match-end 2) (match-string 2 x))
4798 log1 (and (match-end 3) (match-string 3 x))
4799 log2 (and (match-end 4) (match-string 4 x)))
4800 (and (or log1 log2)
4801 (list kw
4802 (and log1 (if (equal log1 "!") 'time 'note))
4803 (and log2 (if (equal log2 "!") 'time 'note)))))))
4805 (defun org-remove-keyword-keys (list)
4806 "Remove a pair of parenthesis at the end of each string in LIST."
4807 (mapcar (lambda (x)
4808 (if (string-match "(.*)$" x)
4809 (substring x 0 (match-beginning 0))
4811 list))
4813 (defun org-assign-fast-keys (alist)
4814 "Assign fast keys to a keyword-key alist.
4815 Respect keys that are already there."
4816 (let (new e (alt ?0))
4817 (while (setq e (pop alist))
4818 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4819 (cdr e)) ;; Key already assigned.
4820 (push e new)
4821 (let ((clist (string-to-list (downcase (car e))))
4822 (used (append new alist)))
4823 (when (= (car clist) ?@)
4824 (pop clist))
4825 (while (and clist (rassoc (car clist) used))
4826 (pop clist))
4827 (unless clist
4828 (while (rassoc alt used)
4829 (incf alt)))
4830 (push (cons (car e) (or (car clist) alt)) new))))
4831 (nreverse new)))
4833 ;;; Some variables used in various places
4835 (defvar org-window-configuration nil
4836 "Used in various places to store a window configuration.")
4837 (defvar org-selected-window nil
4838 "Used in various places to store a window configuration.")
4839 (defvar org-finish-function nil
4840 "Function to be called when `C-c C-c' is used.
4841 This is for getting out of special buffers like remember.")
4844 ;; FIXME: Occasionally check by commenting these, to make sure
4845 ;; no other functions uses these, forgetting to let-bind them.
4846 (defvar entry)
4847 (defvar last-state)
4848 (defvar date)
4850 ;; Defined somewhere in this file, but used before definition.
4851 (defvar org-entities) ;; defined in org-entities.el
4852 (defvar org-struct-menu)
4853 (defvar org-org-menu)
4854 (defvar org-tbl-menu)
4856 ;;;; Define the Org-mode
4858 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4859 (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"))
4862 ;; We use a before-change function to check if a table might need
4863 ;; an update.
4864 (defvar org-table-may-need-update t
4865 "Indicates that a table might need an update.
4866 This variable is set by `org-before-change-function'.
4867 `org-table-align' sets it back to nil.")
4868 (defun org-before-change-function (beg end)
4869 "Every change indicates that a table might need an update."
4870 (setq org-table-may-need-update t))
4871 (defvar org-mode-map)
4872 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4873 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4874 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4875 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4876 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4877 (defvar org-table-buffer-is-an nil)
4879 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4880 ;; some places -- e.g. see the macro org-with-limited-levels.
4882 ;; In Org buffers, the value of `outline-regexp' is that of
4883 ;; `org-outline-regexp'. The only function still directly relying on
4884 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4885 ;; job when `orgstruct-mode' is active.
4886 (defvar org-outline-regexp "\\*+ "
4887 "Regexp to match Org headlines.")
4888 (defconst org-outline-regexp-bol "^\\*+ "
4889 "Regexp to match Org headlines.
4890 This is similar to `org-outline-regexp' but additionally makes
4891 sure that we are at the beginning of the line.")
4893 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4894 "Matches an headline, putting stars and text into groups.
4895 Stars are put in group 1 and the trimmed body in group 2.")
4897 ;;;###autoload
4898 (define-derived-mode org-mode outline-mode "Org"
4899 "Outline-based notes management and organizer, alias
4900 \"Carsten's outline-mode for keeping track of everything.\"
4902 Org-mode develops organizational tasks around a NOTES file which
4903 contains information about projects as plain text. Org-mode is
4904 implemented on top of outline-mode, which is ideal to keep the content
4905 of large files well structured. It supports ToDo items, deadlines and
4906 time stamps, which magically appear in the diary listing of the Emacs
4907 calendar. Tables are easily created with a built-in table editor.
4908 Plain text URL-like links connect to websites, emails (VM), Usenet
4909 messages (Gnus), BBDB entries, and any files related to the project.
4910 For printing and sharing of notes, an Org-mode file (or a part of it)
4911 can be exported as a structured ASCII or HTML file.
4913 The following commands are available:
4915 \\{org-mode-map}"
4917 ;; Get rid of Outline menus, they are not needed
4918 ;; Need to do this here because define-derived-mode sets up
4919 ;; the keymap so late. Still, it is a waste to call this each time
4920 ;; we switch another buffer into org-mode.
4921 (if (featurep 'xemacs)
4922 (when (boundp 'outline-mode-menu-heading)
4923 ;; Assume this is Greg's port, it uses easymenu
4924 (easy-menu-remove outline-mode-menu-heading)
4925 (easy-menu-remove outline-mode-menu-show)
4926 (easy-menu-remove outline-mode-menu-hide))
4927 (define-key org-mode-map [menu-bar headings] 'undefined)
4928 (define-key org-mode-map [menu-bar hide] 'undefined)
4929 (define-key org-mode-map [menu-bar show] 'undefined))
4931 (org-load-modules-maybe)
4932 (easy-menu-add org-org-menu)
4933 (easy-menu-add org-tbl-menu)
4934 (org-install-agenda-files-menu)
4935 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4936 (add-to-invisibility-spec '(org-cwidth))
4937 (add-to-invisibility-spec '(org-hide-block . t))
4938 (when (featurep 'xemacs)
4939 (org-set-local 'line-move-ignore-invisible t))
4940 (org-set-local 'outline-regexp org-outline-regexp)
4941 (org-set-local 'outline-level 'org-outline-level)
4942 (setq bidi-paragraph-direction 'left-to-right)
4943 (when (and org-ellipsis
4944 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4945 (fboundp 'make-glyph-code))
4946 (unless org-display-table
4947 (setq org-display-table (make-display-table)))
4948 (set-display-table-slot
4949 org-display-table 4
4950 (vconcat (mapcar
4951 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4952 org-ellipsis)))
4953 (if (stringp org-ellipsis) org-ellipsis "..."))))
4954 (setq buffer-display-table org-display-table))
4955 (org-set-regexps-and-options)
4956 (when (and org-tag-faces (not org-tags-special-faces-re))
4957 ;; tag faces set outside customize.... force initialization.
4958 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4959 ;; Calc embedded
4960 (org-set-local 'calc-embedded-open-mode "# ")
4961 (modify-syntax-entry ?@ "w")
4962 (if org-startup-truncated (setq truncate-lines t))
4963 (org-set-local 'font-lock-unfontify-region-function
4964 'org-unfontify-region)
4965 ;; Activate before-change-function
4966 (org-set-local 'org-table-may-need-update t)
4967 (org-add-hook 'before-change-functions 'org-before-change-function nil
4968 'local)
4969 ;; Check for running clock before killing a buffer
4970 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4971 ;; Paragraphs and auto-filling
4972 (org-set-autofill-regexps)
4973 (setq indent-line-function 'org-indent-line-function)
4974 (org-update-radio-target-regexp)
4975 ;; Beginning/end of defun
4976 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4977 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4978 ;; Next error for sparse trees
4979 (org-set-local 'next-error-function 'org-occur-next-match)
4980 ;; Make sure dependence stuff works reliably, even for users who set it
4981 ;; too late :-(
4982 (if org-enforce-todo-dependencies
4983 (add-hook 'org-blocker-hook
4984 'org-block-todo-from-children-or-siblings-or-parent)
4985 (remove-hook 'org-blocker-hook
4986 'org-block-todo-from-children-or-siblings-or-parent))
4987 (if org-enforce-todo-checkbox-dependencies
4988 (add-hook 'org-blocker-hook
4989 'org-block-todo-from-checkboxes)
4990 (remove-hook 'org-blocker-hook
4991 'org-block-todo-from-checkboxes))
4993 ;; Comment characters
4994 (org-set-local 'comment-start "#")
4995 (org-set-local 'comment-padding " ")
4997 ;; Align options lines
4998 (org-set-local
4999 'align-mode-rules-list
5000 '((org-in-buffer-settings
5001 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5002 (modes . '(org-mode)))))
5004 ;; Imenu
5005 (org-set-local 'imenu-create-index-function
5006 'org-imenu-get-tree)
5008 ;; Make isearch reveal context
5009 (if (or (featurep 'xemacs)
5010 (not (boundp 'outline-isearch-open-invisible-function)))
5011 ;; Emacs 21 and XEmacs make use of the hook
5012 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5013 ;; Emacs 22 deals with this through a special variable
5014 (org-set-local 'outline-isearch-open-invisible-function
5015 (lambda (&rest ignore) (org-show-context 'isearch))))
5017 ;; Turn on org-beamer-mode?
5018 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5020 ;; Setup the pcomplete hooks
5021 (set (make-local-variable 'pcomplete-command-completion-function)
5022 'org-pcomplete-initial)
5023 (set (make-local-variable 'pcomplete-command-name-function)
5024 'org-command-at-point)
5025 (set (make-local-variable 'pcomplete-default-completion-function)
5026 'ignore)
5027 (set (make-local-variable 'pcomplete-parse-arguments-function)
5028 'org-parse-arguments)
5029 (set (make-local-variable 'pcomplete-termination-string) "")
5030 (set (make-local-variable 'face-remapping-alist)
5031 '((default org-default)))
5033 ;; If empty file that did not turn on org-mode automatically, make it to.
5034 (if (and org-insert-mode-line-in-empty-file
5035 (org-called-interactively-p 'any)
5036 (= (point-min) (point-max)))
5037 (insert "# -*- mode: org -*-\n\n"))
5038 (unless org-inhibit-startup
5039 (when org-startup-align-all-tables
5040 (let ((bmp (buffer-modified-p)))
5041 (org-table-map-tables 'org-table-align 'quietly)
5042 (set-buffer-modified-p bmp)))
5043 (when org-startup-with-inline-images
5044 (org-display-inline-images))
5045 (when org-startup-indented
5046 (require 'org-indent)
5047 (org-indent-mode 1))
5048 (unless org-inhibit-startup-visibility-stuff
5049 (org-set-startup-visibility))))
5051 (when (fboundp 'abbrev-table-put)
5052 (abbrev-table-put org-mode-abbrev-table
5053 :parents (list text-mode-abbrev-table)))
5055 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5057 (defun org-current-time ()
5058 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5059 (if (> (car org-time-stamp-rounding-minutes) 1)
5060 (let ((r (car org-time-stamp-rounding-minutes))
5061 (time (decode-time)))
5062 (apply 'encode-time
5063 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5064 (nthcdr 2 time))))
5065 (current-time)))
5067 (defun org-today ()
5068 "Return today date, considering `org-extend-today-until'."
5069 (time-to-days
5070 (time-subtract (current-time)
5071 (list 0 (* 3600 org-extend-today-until) 0))))
5073 ;;;; Font-Lock stuff, including the activators
5075 (defvar org-mouse-map (make-sparse-keymap))
5076 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5077 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5078 (when org-mouse-1-follows-link
5079 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5080 (when org-tab-follows-link
5081 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5082 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5084 (require 'font-lock)
5086 (defconst org-non-link-chars "]\t\n\r<>")
5087 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5088 "shell" "elisp" "doi" "message"))
5089 (defvar org-link-types-re nil
5090 "Matches a link that has a url-like prefix like \"http:\"")
5091 (defvar org-link-re-with-space nil
5092 "Matches a link with spaces, optional angular brackets around it.")
5093 (defvar org-link-re-with-space2 nil
5094 "Matches a link with spaces, optional angular brackets around it.")
5095 (defvar org-link-re-with-space3 nil
5096 "Matches a link with spaces, only for internal part in bracket links.")
5097 (defvar org-angle-link-re nil
5098 "Matches link with angular brackets, spaces are allowed.")
5099 (defvar org-plain-link-re nil
5100 "Matches plain link, without spaces.")
5101 (defvar org-bracket-link-regexp nil
5102 "Matches a link in double brackets.")
5103 (defvar org-bracket-link-analytic-regexp nil
5104 "Regular expression used to analyze links.
5105 Here is what the match groups contain after a match:
5106 1: http:
5107 2: http
5108 3: path
5109 4: [desc]
5110 5: desc")
5111 (defvar org-bracket-link-analytic-regexp++ nil
5112 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5113 (defvar org-any-link-re nil
5114 "Regular expression matching any link.")
5116 (defcustom org-match-sexp-depth 3
5117 "Number of stacked braces for sub/superscript matching.
5118 This has to be set before loading org.el to be effective."
5119 :group 'org-export-translation ; ??????????????????????????/
5120 :type 'integer)
5122 (defun org-create-multibrace-regexp (left right n)
5123 "Create a regular expression which will match a balanced sexp.
5124 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5125 as single character strings.
5126 The regexp returned will match the entire expression including the
5127 delimiters. It will also define a single group which contains the
5128 match except for the outermost delimiters. The maximum depth of
5129 stacked delimiters is N. Escaping delimiters is not possible."
5130 (let* ((nothing (concat "[^" left right "]*?"))
5131 (or "\\|")
5132 (re nothing)
5133 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5134 (while (> n 1)
5135 (setq n (1- n)
5136 re (concat re or next)
5137 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5138 (concat left "\\(" re "\\)" right)))
5140 (defvar org-match-substring-regexp
5141 (concat
5142 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5143 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5144 "\\|"
5145 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5146 "\\|"
5147 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5148 "The regular expression matching a sub- or superscript.")
5150 (defvar org-match-substring-with-braces-regexp
5151 (concat
5152 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5153 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5154 "\\)")
5155 "The regular expression matching a sub- or superscript, forcing braces.")
5157 (defun org-make-link-regexps ()
5158 "Update the link regular expressions.
5159 This should be called after the variable `org-link-types' has changed."
5160 (setq org-link-types-re
5161 (concat
5162 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5163 org-link-re-with-space
5164 (concat
5165 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5166 "\\([^" org-non-link-chars " ]"
5167 "[^" org-non-link-chars "]*"
5168 "[^" org-non-link-chars " ]\\)>?")
5169 org-link-re-with-space2
5170 (concat
5171 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5172 "\\([^" org-non-link-chars " ]"
5173 "[^\t\n\r]*"
5174 "[^" org-non-link-chars " ]\\)>?")
5175 org-link-re-with-space3
5176 (concat
5177 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5178 "\\([^" org-non-link-chars " ]"
5179 "[^\t\n\r]*\\)")
5180 org-angle-link-re
5181 (concat
5182 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5183 "\\([^" org-non-link-chars " ]"
5184 "[^" org-non-link-chars "]*"
5185 "\\)>")
5186 org-plain-link-re
5187 (concat
5188 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5189 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5190 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5191 org-bracket-link-regexp
5192 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5193 org-bracket-link-analytic-regexp
5194 (concat
5195 "\\[\\["
5196 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5197 "\\([^]]+\\)"
5198 "\\]"
5199 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5200 "\\]")
5201 org-bracket-link-analytic-regexp++
5202 (concat
5203 "\\[\\["
5204 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5205 "\\([^]]+\\)"
5206 "\\]"
5207 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5208 "\\]")
5209 org-any-link-re
5210 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5211 org-angle-link-re "\\)\\|\\("
5212 org-plain-link-re "\\)")))
5214 (org-make-link-regexps)
5216 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5217 "Regular expression for fast time stamp matching.")
5218 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5219 "Regular expression for fast time stamp matching.")
5220 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5221 "Regular expression matching time strings for analysis.
5222 This one does not require the space after the date, so it can be used
5223 on a string that terminates immediately after the date.")
5224 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5225 "Regular expression matching time strings for analysis.")
5226 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5227 "Regular expression matching time stamps, with groups.")
5228 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5229 "Regular expression matching time stamps (also [..]), with groups.")
5230 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5231 "Regular expression matching a time stamp range.")
5232 (defconst org-tr-regexp-both
5233 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5234 "Regular expression matching a time stamp range.")
5235 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5236 org-ts-regexp "\\)?")
5237 "Regular expression matching a time stamp or time stamp range.")
5238 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5239 org-ts-regexp-both "\\)?")
5240 "Regular expression matching a time stamp or time stamp range.
5241 The time stamps may be either active or inactive.")
5243 (defvar org-emph-face nil)
5245 (defun org-do-emphasis-faces (limit)
5246 "Run through the buffer and add overlays to emphasized strings."
5247 (let (rtn a)
5248 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5249 (if (not (= (char-after (match-beginning 3))
5250 (char-after (match-beginning 4))))
5251 (progn
5252 (setq rtn t)
5253 (setq a (assoc (match-string 3) org-emphasis-alist))
5254 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5255 'face
5256 (nth 1 a))
5257 (and (nth 4 a)
5258 (org-remove-flyspell-overlays-in
5259 (match-beginning 0) (match-end 0)))
5260 (add-text-properties (match-beginning 2) (match-end 2)
5261 '(font-lock-multiline t org-emphasis t))
5262 (when org-hide-emphasis-markers
5263 (add-text-properties (match-end 4) (match-beginning 5)
5264 '(invisible org-link))
5265 (add-text-properties (match-beginning 3) (match-end 3)
5266 '(invisible org-link)))))
5267 (backward-char 1))
5268 rtn))
5270 (defun org-emphasize (&optional char)
5271 "Insert or change an emphasis, i.e. a font like bold or italic.
5272 If there is an active region, change that region to a new emphasis.
5273 If there is no region, just insert the marker characters and position
5274 the cursor between them.
5275 CHAR should be either the marker character, or the first character of the
5276 HTML tag associated with that emphasis. If CHAR is a space, the means
5277 to remove the emphasis of the selected region.
5278 If char is not given (for example in an interactive call) it
5279 will be prompted for."
5280 (interactive)
5281 (let ((eal org-emphasis-alist) e det
5282 (erc org-emphasis-regexp-components)
5283 (prompt "")
5284 (string "") beg end move tag c s)
5285 (if (org-region-active-p)
5286 (setq beg (region-beginning) end (region-end)
5287 string (buffer-substring beg end))
5288 (setq move t))
5290 (while (setq e (pop eal))
5291 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5292 c (aref tag 0))
5293 (push (cons c (string-to-char (car e))) det)
5294 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5295 (substring tag 1)))))
5296 (setq det (nreverse det))
5297 (unless char
5298 (message "%s" (concat "Emphasis marker or tag:" prompt))
5299 (setq char (read-char-exclusive)))
5300 (setq char (or (cdr (assoc char det)) char))
5301 (if (equal char ?\ )
5302 (setq s "" move nil)
5303 (unless (assoc (char-to-string char) org-emphasis-alist)
5304 (error "No such emphasis marker: \"%c\"" char))
5305 (setq s (char-to-string char)))
5306 (while (and (> (length string) 1)
5307 (equal (substring string 0 1) (substring string -1))
5308 (assoc (substring string 0 1) org-emphasis-alist))
5309 (setq string (substring string 1 -1)))
5310 (setq string (concat s string s))
5311 (if beg (delete-region beg end))
5312 (unless (or (bolp)
5313 (string-match (concat "[" (nth 0 erc) "\n]")
5314 (char-to-string (char-before (point)))))
5315 (insert " "))
5316 (unless (or (eobp)
5317 (string-match (concat "[" (nth 1 erc) "\n]")
5318 (char-to-string (char-after (point)))))
5319 (insert " ") (backward-char 1))
5320 (insert string)
5321 (and move (backward-char 1))))
5323 (defconst org-nonsticky-props
5324 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5326 (defsubst org-rear-nonsticky-at (pos)
5327 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5329 (defun org-activate-plain-links (limit)
5330 "Run through the buffer and add overlays to links."
5331 (catch 'exit
5332 (let (f)
5333 (if (re-search-forward org-plain-link-re limit t)
5334 (progn
5335 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5336 (setq f (get-text-property (match-beginning 0) 'face))
5337 (if (or (eq f 'org-tag)
5338 (and (listp f) (memq 'org-tag f)))
5340 (add-text-properties (match-beginning 0) (match-end 0)
5341 (list 'mouse-face 'highlight
5342 'face 'org-link
5343 'keymap org-mouse-map))
5344 (org-rear-nonsticky-at (match-end 0)))
5345 t)))))
5347 (defun org-activate-code (limit)
5348 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5349 (progn
5350 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5351 (remove-text-properties (match-beginning 0) (match-end 0)
5352 '(display t invisible t intangible t))
5353 t)))
5355 (defcustom org-src-fontify-natively nil
5356 "When non-nil, fontify code in code blocks."
5357 :type 'boolean
5358 :group 'org-appearance
5359 :group 'org-babel)
5361 (defun org-fontify-meta-lines-and-blocks (limit)
5362 (condition-case nil
5363 (org-fontify-meta-lines-and-blocks-1 limit)
5364 (error (message "org-mode fontification error"))))
5366 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5367 "Fontify #+ lines and blocks, in the correct ways."
5368 (let ((case-fold-search t))
5369 (if (re-search-forward
5370 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5371 limit t)
5372 (let ((beg (match-beginning 0))
5373 (block-start (match-end 0))
5374 (block-end nil)
5375 (lang (match-string 7))
5376 (beg1 (line-beginning-position 2))
5377 (dc1 (downcase (match-string 2)))
5378 (dc3 (downcase (match-string 3)))
5379 end end1 quoting block-type ovl)
5380 (cond
5381 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5382 ;; a single line of backend-specific content
5383 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5384 (remove-text-properties (match-beginning 0) (match-end 0)
5385 '(display t invisible t intangible t))
5386 (add-text-properties (match-beginning 1) (match-end 3)
5387 '(font-lock-fontified t face org-meta-line))
5388 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5389 '(font-lock-fontified t face org-block))
5390 ; for backend-specific code
5392 ((and (match-end 4) (equal dc3 "begin"))
5393 ;; Truly a block
5394 (setq block-type (downcase (match-string 5))
5395 quoting (member block-type org-protecting-blocks))
5396 (when (re-search-forward
5397 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5398 nil t) ;; on purpose, we look further than LIMIT
5399 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5400 (setq block-end (match-beginning 0))
5401 (when quoting
5402 (remove-text-properties beg end
5403 '(display t invisible t intangible t)))
5404 (add-text-properties
5405 beg end
5406 '(font-lock-fontified t font-lock-multiline t))
5407 (add-text-properties beg beg1 '(face org-meta-line))
5408 (add-text-properties end1 (min (point-max) (1+ end))
5409 '(face org-meta-line)) ; for end_src
5410 (cond
5411 ((and lang (not (string= lang "")) org-src-fontify-natively)
5412 (org-src-font-lock-fontify-block lang block-start block-end)
5413 ;; remove old background overlays
5414 (mapc (lambda (ov)
5415 (if (eq (overlay-get ov 'face) 'org-block-background)
5416 (delete-overlay ov)))
5417 (overlays-at (/ (+ beg1 block-end) 2)))
5418 ;; add a background overlay
5419 (setq ovl (make-overlay beg1 block-end))
5420 (overlay-put ovl 'face 'org-block-background)
5421 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5422 (quoting
5423 (add-text-properties beg1 (min (point-max) (1+ end1))
5424 '(face org-block))) ; end of source block
5425 ((not org-fontify-quote-and-verse-blocks))
5426 ((string= block-type "quote")
5427 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5428 ((string= block-type "verse")
5429 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5430 (add-text-properties beg beg1 '(face org-block-begin-line))
5431 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5433 ((member dc1 '("title:" "author:" "email:" "date:"))
5434 (add-text-properties
5435 beg (match-end 3)
5436 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5437 '(font-lock-fontified t invisible t)
5438 '(font-lock-fontified t face org-document-info-keyword)))
5439 (add-text-properties
5440 (match-beginning 6) (match-end 6)
5441 (if (string-equal dc1 "title:")
5442 '(font-lock-fontified t face org-document-title)
5443 '(font-lock-fontified t face org-document-info))))
5444 ((not (member (char-after beg) '(?\ ?\t)))
5445 ;; just any other in-buffer setting, but not indented
5446 (add-text-properties
5447 beg (1+ (match-end 0))
5448 '(font-lock-fontified t face org-meta-line))
5450 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5451 "orgtbl:" "tblfm:" "tblname:" "results:"
5452 "call:" "header:" "headers:" "name:"))
5453 (and (match-end 4) (equal dc3 "attr")))
5454 (add-text-properties
5455 beg (match-end 0)
5456 '(font-lock-fontified t face org-meta-line))
5458 ((member dc3 '(" " ""))
5459 (add-text-properties
5460 beg (match-end 0)
5461 '(font-lock-fontified t face font-lock-comment-face)))
5462 (t nil))))))
5464 (defun org-strip-protective-commas (beg end)
5465 "Strip protective commas between BEG and END in the current buffer."
5466 (interactive "r")
5467 (save-excursion
5468 (save-match-data
5469 (goto-char beg)
5470 (let ((front-line (save-excursion
5471 (re-search-forward
5472 "[^[:space:]]" end t)
5473 (goto-char (match-beginning 0))
5474 (current-column))))
5475 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5476 (goto-char (match-beginning 1))
5477 (when (= (current-column) front-line)
5478 (replace-match "" nil nil nil 1)))))))
5480 (defun org-activate-angle-links (limit)
5481 "Run through the buffer and add overlays to links."
5482 (if (re-search-forward org-angle-link-re limit t)
5483 (progn
5484 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5485 (add-text-properties (match-beginning 0) (match-end 0)
5486 (list 'mouse-face 'highlight
5487 'keymap org-mouse-map))
5488 (org-rear-nonsticky-at (match-end 0))
5489 t)))
5491 (defun org-activate-footnote-links (limit)
5492 "Run through the buffer and add overlays to footnotes."
5493 (let ((fn (org-footnote-next-reference-or-definition limit)))
5494 (when fn
5495 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5496 (org-remove-flyspell-overlays-in beg end)
5497 (add-text-properties beg end
5498 (list 'mouse-face 'highlight
5499 'keymap org-mouse-map
5500 'help-echo
5501 (if (= (point-at-bol) beg)
5502 "Footnote definition"
5503 "Footnote reference")
5504 'font-lock-fontified t
5505 'font-lock-multiline t
5506 'face 'org-footnote))))))
5508 (defun org-activate-bracket-links (limit)
5509 "Run through the buffer and add overlays to bracketed links."
5510 (if (re-search-forward org-bracket-link-regexp limit t)
5511 (let* ((help (concat "LINK: "
5512 (org-match-string-no-properties 1)))
5513 ;; FIXME: above we should remove the escapes.
5514 ;; but that requires another match, protecting match data,
5515 ;; a lot of overhead for font-lock.
5516 (ip (org-maybe-intangible
5517 (list 'invisible 'org-link
5518 'keymap org-mouse-map 'mouse-face 'highlight
5519 'font-lock-multiline t 'help-echo help)))
5520 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5521 'font-lock-multiline t 'help-echo help)))
5522 ;; We need to remove the invisible property here. Table narrowing
5523 ;; may have made some of this invisible.
5524 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5525 (remove-text-properties (match-beginning 0) (match-end 0)
5526 '(invisible nil))
5527 (if (match-end 3)
5528 (progn
5529 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5530 (org-rear-nonsticky-at (match-beginning 3))
5531 (add-text-properties (match-beginning 3) (match-end 3) vp)
5532 (org-rear-nonsticky-at (match-end 3))
5533 (add-text-properties (match-end 3) (match-end 0) ip)
5534 (org-rear-nonsticky-at (match-end 0)))
5535 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5536 (org-rear-nonsticky-at (match-beginning 1))
5537 (add-text-properties (match-beginning 1) (match-end 1) vp)
5538 (org-rear-nonsticky-at (match-end 1))
5539 (add-text-properties (match-end 1) (match-end 0) ip)
5540 (org-rear-nonsticky-at (match-end 0)))
5541 t)))
5543 (defun org-activate-dates (limit)
5544 "Run through the buffer and add overlays to dates."
5545 (if (re-search-forward org-tsr-regexp-both limit t)
5546 (progn
5547 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5548 (add-text-properties (match-beginning 0) (match-end 0)
5549 (list 'mouse-face 'highlight
5550 'keymap org-mouse-map))
5551 (org-rear-nonsticky-at (match-end 0))
5552 (when org-display-custom-times
5553 (if (match-end 3)
5554 (org-display-custom-time (match-beginning 3) (match-end 3)))
5555 (org-display-custom-time (match-beginning 1) (match-end 1)))
5556 t)))
5558 (defvar org-target-link-regexp nil
5559 "Regular expression matching radio targets in plain text.")
5560 (make-variable-buffer-local 'org-target-link-regexp)
5561 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5562 "Regular expression matching a link target.")
5563 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5564 "Regular expression matching a radio target.")
5565 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5566 "Regular expression matching any target.")
5568 (defun org-activate-target-links (limit)
5569 "Run through the buffer and add overlays to target matches."
5570 (when org-target-link-regexp
5571 (let ((case-fold-search t))
5572 (if (re-search-forward org-target-link-regexp limit t)
5573 (progn
5574 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5575 (add-text-properties (match-beginning 0) (match-end 0)
5576 (list 'mouse-face 'highlight
5577 'keymap org-mouse-map
5578 'help-echo "Radio target link"
5579 'org-linked-text t))
5580 (org-rear-nonsticky-at (match-end 0))
5581 t)))))
5583 (defun org-update-radio-target-regexp ()
5584 "Find all radio targets in this file and update the regular expression."
5585 (interactive)
5586 (when (memq 'radio org-activate-links)
5587 (setq org-target-link-regexp
5588 (org-make-target-link-regexp (org-all-targets 'radio)))
5589 (org-restart-font-lock)))
5591 (defun org-hide-wide-columns (limit)
5592 (let (s e)
5593 (setq s (text-property-any (point) (or limit (point-max))
5594 'org-cwidth t))
5595 (when s
5596 (setq e (next-single-property-change s 'org-cwidth))
5597 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5598 (goto-char e)
5599 t)))
5601 (defvar org-latex-and-specials-regexp nil
5602 "Regular expression for highlighting export special stuff.")
5603 (defvar org-match-substring-regexp)
5604 (defvar org-match-substring-with-braces-regexp)
5606 ;; This should be with the exporter code, but we also use if for font-locking
5607 (defconst org-export-html-special-string-regexps
5608 '(("\\\\-" . "&shy;")
5609 ("---\\([^-]\\)" . "&mdash;\\1")
5610 ("--\\([^-]\\)" . "&ndash;\\1")
5611 ("\\.\\.\\." . "&hellip;"))
5612 "Regular expressions for special string conversion.")
5615 (defun org-compute-latex-and-specials-regexp ()
5616 "Compute regular expression for stuff treated specially by exporters."
5617 (if (not org-highlight-latex-fragments-and-specials)
5618 (org-set-local 'org-latex-and-specials-regexp nil)
5619 (require 'org-exp)
5620 (let*
5621 ((matchers (plist-get org-format-latex-options :matchers))
5622 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5623 org-latex-regexps)))
5624 (org-export-allow-BIND nil)
5625 (options (org-combine-plists (org-default-export-plist)
5626 (org-infile-export-plist)))
5627 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5628 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5629 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5630 (org-export-html-expand (plist-get options :expand-quoted-html))
5631 (org-export-with-special-strings (plist-get options :special-strings))
5632 (re-sub
5633 (cond
5634 ((equal org-export-with-sub-superscripts '{})
5635 (list org-match-substring-with-braces-regexp))
5636 (org-export-with-sub-superscripts
5637 (list org-match-substring-regexp))
5638 (t nil)))
5639 (re-latex
5640 (if org-export-with-LaTeX-fragments
5641 (mapcar (lambda (x) (nth 1 x)) latexs)))
5642 (re-macros
5643 (if org-export-with-TeX-macros
5644 (list (concat "\\\\"
5645 (regexp-opt
5646 (append
5648 (delq nil
5649 (mapcar 'car-safe
5650 (append org-entities-user
5651 org-entities)))
5652 (if (boundp 'org-latex-entities)
5653 (mapcar (lambda (x)
5654 (or (car-safe x) x))
5655 org-latex-entities)
5656 nil))
5657 'words))) ; FIXME
5659 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5660 (re-special (if org-export-with-special-strings
5661 (mapcar (lambda (x) (car x))
5662 org-export-html-special-string-regexps)))
5663 (re-rest
5664 (delq nil
5665 (list
5666 (if org-export-html-expand "@<[^>\n]+>")
5667 ))))
5668 (org-set-local
5669 'org-latex-and-specials-regexp
5670 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5671 re-rest) "\\|")))))
5673 (defun org-do-latex-and-special-faces (limit)
5674 "Run through the buffer and add overlays to links."
5675 (when org-latex-and-specials-regexp
5676 (let (rtn d)
5677 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5678 limit t))
5679 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5680 'face))
5681 '(org-code org-verbatim underline)))
5682 (progn
5683 (setq rtn t
5684 d (cond ((member (char-after (1+ (match-beginning 0)))
5685 '(?_ ?^)) 1)
5686 (t 0)))
5687 (font-lock-prepend-text-property
5688 (+ d (match-beginning 0)) (match-end 0)
5689 'face 'org-latex-and-export-specials)
5690 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5691 '(font-lock-multiline t)))))
5692 rtn)))
5694 (defun org-restart-font-lock ()
5695 "Restart `font-lock-mode', to force refontification."
5696 (when (and (boundp 'font-lock-mode) font-lock-mode)
5697 (font-lock-mode -1)
5698 (font-lock-mode 1)))
5700 (defun org-all-targets (&optional radio)
5701 "Return a list of all targets in this file.
5702 With optional argument RADIO, only find radio targets."
5703 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5704 rtn)
5705 (save-excursion
5706 (goto-char (point-min))
5707 (while (re-search-forward re nil t)
5708 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5709 rtn)))
5711 (defun org-make-target-link-regexp (targets)
5712 "Make regular expression matching all strings in TARGETS.
5713 The regular expression finds the targets also if there is a line break
5714 between words."
5715 (and targets
5716 (concat
5717 "\\<\\("
5718 (mapconcat
5719 (lambda (x)
5720 (setq x (regexp-quote x))
5721 (while (string-match " +" x)
5722 (setq x (replace-match "\\s-+" t t x)))
5724 targets
5725 "\\|")
5726 "\\)\\>")))
5728 (defun org-activate-tags (limit)
5729 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5730 (progn
5731 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5732 (add-text-properties (match-beginning 1) (match-end 1)
5733 (list 'mouse-face 'highlight
5734 'keymap org-mouse-map))
5735 (org-rear-nonsticky-at (match-end 1))
5736 t)))
5738 (defun org-outline-level ()
5739 "Compute the outline level of the heading at point.
5740 This function assumes that the cursor is at the beginning of a line matched
5741 by `outline-regexp'. Otherwise it returns garbage.
5742 If this is called at a normal headline, the level is the number of stars.
5743 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5744 (save-excursion
5745 (looking-at org-outline-regexp)
5746 (1- (- (match-end 0) (match-beginning 0)))))
5748 (defvar org-font-lock-keywords nil)
5750 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5751 "Regular expression matching a property line.")
5753 (defvar org-font-lock-hook nil
5754 "Functions to be called for special font lock stuff.")
5756 (defvar org-font-lock-set-keywords-hook nil
5757 "Functions that can manipulate `org-font-lock-extra-keywords'.
5758 This is called after `org-font-lock-extra-keywords' is defined, but before
5759 it is installed to be used by font lock. This can be useful if something
5760 needs to be inserted at a specific position in the font-lock sequence.")
5762 (defun org-font-lock-hook (limit)
5763 (run-hook-with-args 'org-font-lock-hook limit))
5765 (defun org-set-font-lock-defaults ()
5766 (let* ((em org-fontify-emphasized-text)
5767 (lk org-activate-links)
5768 (org-font-lock-extra-keywords
5769 (list
5770 ;; Call the hook
5771 '(org-font-lock-hook)
5772 ;; Headlines
5773 `(,(if org-fontify-whole-heading-line
5774 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5775 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5776 (1 (org-get-level-face 1))
5777 (2 (org-get-level-face 2))
5778 (3 (org-get-level-face 3)))
5779 ;; Table lines
5780 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5781 (1 'org-table t))
5782 ;; Table internals
5783 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5784 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5785 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5786 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5787 ;; Drawers
5788 (list org-drawer-regexp '(0 'org-special-keyword t))
5789 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5790 ;; Properties
5791 (list org-property-re
5792 '(1 'org-special-keyword t)
5793 '(3 'org-property-value t))
5794 ;; Links
5795 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5796 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5797 (if (memq 'plain lk) '(org-activate-plain-links))
5798 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5799 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5800 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5801 (if (memq 'footnote lk) '(org-activate-footnote-links))
5802 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5803 '(org-hide-wide-columns (0 nil append))
5804 ;; TODO keyword
5805 (list (format org-heading-keyword-regexp-format
5806 org-todo-regexp)
5807 '(2 (org-get-todo-face 2) t))
5808 ;; DONE
5809 (if org-fontify-done-headline
5810 (list (format org-heading-keyword-regexp-format
5811 (concat
5812 "\\(?:"
5813 (mapconcat 'regexp-quote org-done-keywords "\\|")
5814 "\\)"))
5815 '(2 'org-headline-done t))
5816 nil)
5817 ;; Priorities
5818 '(org-font-lock-add-priority-faces)
5819 ;; Tags
5820 '(org-font-lock-add-tag-faces)
5821 ;; Special keywords
5822 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5823 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5824 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5825 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5826 ;; Emphasis
5827 (if em
5828 (if (featurep 'xemacs)
5829 '(org-do-emphasis-faces (0 nil append))
5830 '(org-do-emphasis-faces)))
5831 ;; Checkboxes
5832 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5833 1 'org-checkbox prepend)
5834 (if (cdr (assq 'checkbox org-list-automatic-rules))
5835 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5836 (0 (org-get-checkbox-statistics-face) t)))
5837 ;; Description list items
5838 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5839 1 'bold prepend)
5840 ;; ARCHIVEd headings
5841 (list (concat
5842 org-outline-regexp-bol
5843 "\\(.*:" org-archive-tag ":.*\\)")
5844 '(1 'org-archived prepend))
5845 ;; Specials
5846 '(org-do-latex-and-special-faces)
5847 '(org-fontify-entities)
5848 '(org-raise-scripts)
5849 ;; Code
5850 '(org-activate-code (1 'org-code t))
5851 ;; COMMENT
5852 (list (format org-heading-keyword-regexp-format
5853 (concat "\\("
5854 org-comment-string "\\|" org-quote-string
5855 "\\)"))
5856 '(2 'org-special-keyword t))
5857 '("^#.*" (0 'font-lock-comment-face t))
5858 ;; Blocks and meta lines
5859 '(org-fontify-meta-lines-and-blocks)
5861 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5862 (run-hooks 'org-font-lock-set-keywords-hook)
5863 ;; Now set the full font-lock-keywords
5864 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5865 (org-set-local 'font-lock-defaults
5866 '(org-font-lock-keywords t nil nil backward-paragraph))
5867 (kill-local-variable 'font-lock-keywords) nil))
5869 (defun org-toggle-pretty-entities ()
5870 "Toggle the composition display of entities as UTF8 characters."
5871 (interactive)
5872 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5873 (org-restart-font-lock)
5874 (if org-pretty-entities
5875 (message "Entities are displayed as UTF8 characters")
5876 (save-restriction
5877 (widen)
5878 (org-decompose-region (point-min) (point-max))
5879 (message "Entities are displayed plain"))))
5881 (defun org-fontify-entities (limit)
5882 "Find an entity to fontify."
5883 (let (ee)
5884 (when org-pretty-entities
5885 (catch 'match
5886 (while (re-search-forward
5887 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5888 limit t)
5889 (if (and (not (org-in-indented-comment-line))
5890 (setq ee (org-entity-get (match-string 1)))
5891 (= (length (nth 6 ee)) 1))
5892 (progn
5893 (add-text-properties
5894 (match-beginning 0) (match-end 1)
5895 (list 'font-lock-fontified t))
5896 (compose-region (match-beginning 0) (match-end 1)
5897 (nth 6 ee) nil)
5898 (backward-char 1)
5899 (throw 'match t))))
5900 nil))))
5902 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5903 "Fontify string S like in Org-mode."
5904 (with-temp-buffer
5905 (insert s)
5906 (let ((org-odd-levels-only odd-levels))
5907 (org-mode)
5908 (font-lock-fontify-buffer)
5909 (buffer-string))))
5911 (defvar org-m nil)
5912 (defvar org-l nil)
5913 (defvar org-f nil)
5914 (defun org-get-level-face (n)
5915 "Get the right face for match N in font-lock matching of headlines."
5916 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5917 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5918 (if org-cycle-level-faces
5919 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5920 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5921 (cond
5922 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5923 ((eq n 2) org-f)
5924 (t (if org-level-color-stars-only nil org-f))))
5927 (defun org-get-todo-face (kwd)
5928 "Get the right face for a TODO keyword KWD.
5929 If KWD is a number, get the corresponding match group."
5930 (if (numberp kwd) (setq kwd (match-string kwd)))
5931 (or (org-face-from-face-or-color
5932 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5933 (and (member kwd org-done-keywords) 'org-done)
5934 'org-todo))
5936 (defun org-face-from-face-or-color (context inherit face-or-color)
5937 "Create a face list that inherits INHERIT, but sets the foreground color.
5938 When FACE-OR-COLOR is not a string, just return it."
5939 (if (stringp face-or-color)
5940 (list :inherit inherit
5941 (cdr (assoc context org-faces-easy-properties))
5942 face-or-color)
5943 face-or-color))
5945 (defun org-font-lock-add-tag-faces (limit)
5946 "Add the special tag faces."
5947 (when (and org-tag-faces org-tags-special-faces-re)
5948 (while (re-search-forward org-tags-special-faces-re limit t)
5949 (add-text-properties (match-beginning 1) (match-end 1)
5950 (list 'face (org-get-tag-face 1)
5951 'font-lock-fontified t))
5952 (backward-char 1))))
5954 (defun org-font-lock-add-priority-faces (limit)
5955 "Add the special priority faces."
5956 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 (list 'face (or (org-face-from-face-or-color
5960 'priority 'org-special-keyword
5961 (cdr (assoc (char-after (match-beginning 1))
5962 org-priority-faces)))
5963 'org-special-keyword)
5964 'font-lock-fontified t))))
5966 (defun org-get-tag-face (kwd)
5967 "Get the right face for a TODO keyword KWD.
5968 If KWD is a number, get the corresponding match group."
5969 (if (numberp kwd) (setq kwd (match-string kwd)))
5970 (or (org-face-from-face-or-color
5971 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5972 'org-tag))
5974 (defun org-unfontify-region (beg end &optional maybe_loudly)
5975 "Remove fontification and activation overlays from links."
5976 (font-lock-default-unfontify-region beg end)
5977 (let* ((buffer-undo-list t)
5978 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5979 (inhibit-modification-hooks t)
5980 deactivate-mark buffer-file-name buffer-file-truename)
5981 (org-decompose-region beg end)
5982 (remove-text-properties beg end
5983 '(mouse-face t keymap t org-linked-text t
5984 invisible t intangible t
5985 org-no-flyspell t org-emphasis t))
5986 (org-remove-font-lock-display-properties beg end)))
5988 (defconst org-script-display '(((raise -0.3) (height 0.7))
5989 ((raise 0.3) (height 0.7))
5990 ((raise -0.5))
5991 ((raise 0.5)))
5992 "Display properties for showing superscripts and subscripts.")
5994 (defun org-remove-font-lock-display-properties (beg end)
5995 "Remove specific display properties that have been added by font lock.
5996 The will remove the raise properties that are used to show superscripts
5997 and subscripts."
5998 (let (next prop)
5999 (while (< beg end)
6000 (setq next (next-single-property-change beg 'display nil end)
6001 prop (get-text-property beg 'display))
6002 (if (member prop org-script-display)
6003 (put-text-property beg next 'display nil))
6004 (setq beg next))))
6006 (defun org-raise-scripts (limit)
6007 "Add raise properties to sub/superscripts."
6008 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6009 (if (re-search-forward
6010 (if (eq org-use-sub-superscripts t)
6011 org-match-substring-regexp
6012 org-match-substring-with-braces-regexp)
6013 limit t)
6014 (let* ((pos (point)) table-p comment-p
6015 (mpos (match-beginning 3))
6016 (emph-p (get-text-property mpos 'org-emphasis))
6017 (link-p (get-text-property mpos 'mouse-face))
6018 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6019 (goto-char (point-at-bol))
6020 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6021 comment-p (org-looking-at-p "[ \t]*#"))
6022 (goto-char pos)
6023 ;; FIXME: Should we go back one character here, for a_b^c
6024 ;; (goto-char (1- pos)) ;????????????????????
6025 (if (or comment-p emph-p link-p keyw-p)
6027 (put-text-property (match-beginning 3) (match-end 0)
6028 'display
6029 (if (equal (char-after (match-beginning 2)) ?^)
6030 (nth (if table-p 3 1) org-script-display)
6031 (nth (if table-p 2 0) org-script-display)))
6032 (add-text-properties (match-beginning 2) (match-end 2)
6033 (list 'invisible t
6034 'org-dwidth t 'org-dwidth-n 1))
6035 (if (and (eq (char-after (match-beginning 3)) ?{)
6036 (eq (char-before (match-end 3)) ?}))
6037 (progn
6038 (add-text-properties
6039 (match-beginning 3) (1+ (match-beginning 3))
6040 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6041 (add-text-properties
6042 (1- (match-end 3)) (match-end 3)
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6044 t)))))
6046 ;;;; Visibility cycling, including org-goto and indirect buffer
6048 ;;; Cycling
6050 (defvar org-cycle-global-status nil)
6051 (make-variable-buffer-local 'org-cycle-global-status)
6052 (defvar org-cycle-subtree-status nil)
6053 (make-variable-buffer-local 'org-cycle-subtree-status)
6055 ;;;###autoload
6057 (defvar org-inlinetask-min-level)
6059 (defun org-cycle (&optional arg)
6060 "TAB-action and visibility cycling for Org-mode.
6062 This is the command invoked in Org-mode by the TAB key. Its main purpose
6063 is outline visibility cycling, but it also invokes other actions
6064 in special contexts.
6066 - When this function is called with a prefix argument, rotate the entire
6067 buffer through 3 states (global cycling)
6068 1. OVERVIEW: Show only top-level headlines.
6069 2. CONTENTS: Show all headlines of all levels, but no body text.
6070 3. SHOW ALL: Show everything.
6071 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6072 determined by the variable `org-startup-folded', and by any VISIBILITY
6073 properties in the buffer.
6074 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6075 including any drawers.
6077 - When inside a table, re-align the table and move to the next field.
6079 - When point is at the beginning of a headline, rotate the subtree started
6080 by this line through 3 different states (local cycling)
6081 1. FOLDED: Only the main headline is shown.
6082 2. CHILDREN: The main headline and the direct children are shown.
6083 From this state, you can move to one of the children
6084 and zoom in further.
6085 3. SUBTREE: Show the entire subtree, including body text.
6086 If there is no subtree, switch directly from CHILDREN to FOLDED.
6088 - When point is at the beginning of an empty headline and the variable
6089 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6090 of the headline by demoting and promoting it to likely levels. This
6091 speeds up creation document structure by pressing TAB once or several
6092 times right after creating a new headline.
6094 - When there is a numeric prefix, go up to a heading with level ARG, do
6095 a `show-subtree' and return to the previous cursor position. If ARG
6096 is negative, go up that many levels.
6098 - When point is not at the beginning of a headline, execute the global
6099 binding for TAB, which is re-indenting the line. See the option
6100 `org-cycle-emulate-tab' for details.
6102 - Special case: if point is at the beginning of the buffer and there is
6103 no headline in line 1, this function will act as if called with prefix arg
6104 (C-u TAB, same as S-TAB) also when called without prefix arg.
6105 But only if also the variable `org-cycle-global-at-bob' is t."
6106 (interactive "P")
6107 (org-load-modules-maybe)
6108 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6109 (and org-cycle-level-after-item/entry-creation
6110 (or (org-cycle-level)
6111 (org-cycle-item-indentation))))
6112 (let* ((limit-level
6113 (or org-cycle-max-level
6114 (and (boundp 'org-inlinetask-min-level)
6115 org-inlinetask-min-level
6116 (1- org-inlinetask-min-level))))
6117 (nstars (and limit-level
6118 (if org-odd-levels-only
6119 (and limit-level (1- (* limit-level 2)))
6120 limit-level)))
6121 (org-outline-regexp
6122 (if (not (eq major-mode 'org-mode))
6123 outline-regexp
6124 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6125 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6126 (not (looking-at org-outline-regexp))))
6127 (org-cycle-hook
6128 (if bob-special
6129 (delq 'org-optimize-window-after-visibility-change
6130 (copy-sequence org-cycle-hook))
6131 org-cycle-hook))
6132 (pos (point)))
6134 (if (or bob-special (equal arg '(4)))
6135 ;; special case: use global cycling
6136 (setq arg t))
6138 (cond
6140 ((equal arg '(16))
6141 (setq last-command 'dummy)
6142 (org-set-startup-visibility)
6143 (message "Startup visibility, plus VISIBILITY properties"))
6145 ((equal arg '(64))
6146 (show-all)
6147 (message "Entire buffer visible, including drawers"))
6149 ;; Table: enter it or move to the next field.
6150 ((org-at-table-p 'any)
6151 (if (org-at-table.el-p)
6152 (message "Use C-c ' to edit table.el tables")
6153 (if arg (org-table-edit-field t)
6154 (org-table-justify-field-maybe)
6155 (call-interactively 'org-table-next-field))))
6157 ((run-hook-with-args-until-success
6158 'org-tab-after-check-for-table-hook))
6160 ;; Global cycling: delegate to `org-cycle-internal-global'.
6161 ((eq arg t) (org-cycle-internal-global))
6163 ;; Drawers: delegate to `org-flag-drawer'.
6164 ((and org-drawers org-drawer-regexp
6165 (save-excursion
6166 (beginning-of-line 1)
6167 (looking-at org-drawer-regexp)))
6168 (org-flag-drawer ; toggle block visibility
6169 (not (get-char-property (match-end 0) 'invisible))))
6171 ;; Show-subtree, ARG levels up from here.
6172 ((integerp arg)
6173 (save-excursion
6174 (org-back-to-heading)
6175 (outline-up-heading (if (< arg 0) (- arg)
6176 (- (funcall outline-level) arg)))
6177 (org-show-subtree)))
6179 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6180 ((and (featurep 'org-inlinetask)
6181 (org-inlinetask-at-task-p)
6182 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6183 (org-inlinetask-toggle-visibility))
6185 ((org-try-cdlatex-tab))
6187 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6188 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6189 (save-excursion (beginning-of-line 1)
6190 (looking-at org-outline-regexp)))
6191 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6192 (org-cycle-internal-local))
6194 ;; From there: TAB emulation and template completion.
6195 (buffer-read-only (org-back-to-heading))
6197 ((run-hook-with-args-until-success
6198 'org-tab-after-check-for-cycling-hook))
6200 ((org-try-structure-completion))
6202 ((run-hook-with-args-until-success
6203 'org-tab-before-tab-emulation-hook))
6205 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6206 (or (not (bolp))
6207 (not (looking-at org-outline-regexp))))
6208 (call-interactively (global-key-binding "\t")))
6210 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6211 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6212 (or (and (eq org-cycle-emulate-tab 'white)
6213 (= (match-end 0) (point-at-eol)))
6214 (and (eq org-cycle-emulate-tab 'whitestart)
6215 (>= (match-end 0) pos))))
6217 (eq org-cycle-emulate-tab t))
6218 (call-interactively (global-key-binding "\t")))
6220 (t (save-excursion
6221 (org-back-to-heading)
6222 (org-cycle)))))))
6224 (defun org-cycle-internal-global ()
6225 "Do the global cycling action."
6226 (cond
6227 ((and (eq last-command this-command)
6228 (eq org-cycle-global-status 'overview))
6229 ;; We just created the overview - now do table of contents
6230 ;; This can be slow in very large buffers, so indicate action
6231 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6232 (message "CONTENTS...")
6233 (org-content)
6234 (message "CONTENTS...done")
6235 (setq org-cycle-global-status 'contents)
6236 (run-hook-with-args 'org-cycle-hook 'contents))
6238 ((and (eq last-command this-command)
6239 (eq org-cycle-global-status 'contents))
6240 ;; We just showed the table of contents - now show everything
6241 (run-hook-with-args 'org-pre-cycle-hook 'all)
6242 (show-all)
6243 (message "SHOW ALL")
6244 (setq org-cycle-global-status 'all)
6245 (run-hook-with-args 'org-cycle-hook 'all))
6248 ;; Default action: go to overview
6249 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6250 (org-overview)
6251 (message "OVERVIEW")
6252 (setq org-cycle-global-status 'overview)
6253 (run-hook-with-args 'org-cycle-hook 'overview))))
6255 (defun org-cycle-internal-local ()
6256 "Do the local cycling action."
6257 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6258 ;; First, determine end of headline (EOH), end of subtree or item
6259 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6260 (save-excursion
6261 (if (org-at-item-p)
6262 (progn
6263 (beginning-of-line)
6264 (setq struct (org-list-struct))
6265 (setq eoh (point-at-eol))
6266 (setq eos (org-list-get-item-end-before-blank (point) struct))
6267 (setq has-children (org-list-has-child-p (point) struct)))
6268 (org-back-to-heading)
6269 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6270 (setq eos (save-excursion
6271 (org-end-of-subtree t)
6272 (unless (eobp)
6273 (skip-chars-forward " \t\n"))
6274 (if (eobp) (point) (1- (point)))))
6275 (setq has-children
6276 (or (save-excursion
6277 (let ((level (funcall outline-level)))
6278 (outline-next-heading)
6279 (and (org-at-heading-p t)
6280 (> (funcall outline-level) level))))
6281 (save-excursion
6282 (org-list-search-forward (org-item-beginning-re) eos t)))))
6283 ;; Determine end invisible part of buffer (EOL)
6284 (beginning-of-line 2)
6285 ;; XEmacs doesn't have `next-single-char-property-change'
6286 (if (featurep 'xemacs)
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (beginning-of-line 2))
6290 (while (and (not (eobp)) ;; this is like `next-line'
6291 (get-char-property (1- (point)) 'invisible))
6292 (goto-char (next-single-char-property-change (point) 'invisible))
6293 (and (eolp) (beginning-of-line 2))))
6294 (setq eol (point)))
6295 ;; Find out what to do next and set `this-command'
6296 (cond
6297 ((= eos eoh)
6298 ;; Nothing is hidden behind this heading
6299 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6300 (message "EMPTY ENTRY")
6301 (setq org-cycle-subtree-status nil)
6302 (save-excursion
6303 (goto-char eos)
6304 (outline-next-heading)
6305 (if (outline-invisible-p) (org-flag-heading nil))))
6306 ((and (or (>= eol eos)
6307 (not (string-match "\\S-" (buffer-substring eol eos))))
6308 (or has-children
6309 (not (setq children-skipped
6310 org-cycle-skip-children-state-if-no-children))))
6311 ;; Entire subtree is hidden in one line: children view
6312 (run-hook-with-args 'org-pre-cycle-hook 'children)
6313 (if (org-at-item-p)
6314 (org-list-set-item-visibility (point-at-bol) struct 'children)
6315 (org-show-entry)
6316 (org-with-limited-levels (show-children))
6317 (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6318 (org-cycle-hide-drawers 'subtree))
6319 ;; Fold every list in subtree to top-level items.
6320 (when (eq org-cycle-include-plain-lists 'integrate)
6321 (save-excursion
6322 (org-back-to-heading)
6323 (while (org-list-search-forward (org-item-beginning-re) eos t)
6324 (beginning-of-line 1)
6325 (let* ((struct (org-list-struct))
6326 (prevs (org-list-prevs-alist struct))
6327 (end (org-list-get-bottom-point struct)))
6328 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6329 (org-list-get-all-items (point) struct prevs))
6330 (goto-char end))))))
6331 (message "CHILDREN")
6332 (save-excursion
6333 (goto-char eos)
6334 (outline-next-heading)
6335 (if (outline-invisible-p) (org-flag-heading nil)))
6336 (setq org-cycle-subtree-status 'children)
6337 (run-hook-with-args 'org-cycle-hook 'children))
6338 ((or children-skipped
6339 (and (eq last-command this-command)
6340 (eq org-cycle-subtree-status 'children)))
6341 ;; We just showed the children, or no children are there,
6342 ;; now show everything.
6343 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6344 (outline-flag-region eoh eos nil)
6345 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6346 (setq org-cycle-subtree-status 'subtree)
6347 (run-hook-with-args 'org-cycle-hook 'subtree))
6349 ;; Default action: hide the subtree.
6350 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6351 (outline-flag-region eoh eos t)
6352 (message "FOLDED")
6353 (setq org-cycle-subtree-status 'folded)
6354 (run-hook-with-args 'org-cycle-hook 'folded)))))
6356 ;;;###autoload
6357 (defun org-global-cycle (&optional arg)
6358 "Cycle the global visibility. For details see `org-cycle'.
6359 With \\[universal-argument] prefix arg, switch to startup visibility.
6360 With a numeric prefix, show all headlines up to that level."
6361 (interactive "P")
6362 (let ((org-cycle-include-plain-lists
6363 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6364 (cond
6365 ((integerp arg)
6366 (show-all)
6367 (hide-sublevels arg)
6368 (setq org-cycle-global-status 'contents))
6369 ((equal arg '(4))
6370 (org-set-startup-visibility)
6371 (message "Startup visibility, plus VISIBILITY properties."))
6373 (org-cycle '(4))))))
6375 (defun org-set-startup-visibility ()
6376 "Set the visibility required by startup options and properties."
6377 (cond
6378 ((eq org-startup-folded t)
6379 (org-cycle '(4)))
6380 ((eq org-startup-folded 'content)
6381 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6382 (org-cycle '(4)) (org-cycle '(4)))))
6383 (unless (eq org-startup-folded 'showeverything)
6384 (if org-hide-block-startup (org-hide-block-all))
6385 (org-set-visibility-according-to-property 'no-cleanup)
6386 (org-cycle-hide-archived-subtrees 'all)
6387 (org-cycle-hide-drawers 'all)
6388 (org-cycle-show-empty-lines t)))
6390 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6391 "Switch subtree visibilities according to :VISIBILITY: property."
6392 (interactive)
6393 (let (org-show-entry-below state)
6394 (save-excursion
6395 (goto-char (point-min))
6396 (while (re-search-forward
6397 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6398 nil t)
6399 (setq state (match-string 1))
6400 (save-excursion
6401 (org-back-to-heading t)
6402 (hide-subtree)
6403 (org-reveal)
6404 (cond
6405 ((equal state '("fold" "folded"))
6406 (hide-subtree))
6407 ((equal state "children")
6408 (org-show-hidden-entry)
6409 (show-children))
6410 ((equal state "content")
6411 (save-excursion
6412 (save-restriction
6413 (org-narrow-to-subtree)
6414 (org-content))))
6415 ((member state '("all" "showall"))
6416 (show-subtree)))))
6417 (unless no-cleanup
6418 (org-cycle-hide-archived-subtrees 'all)
6419 (org-cycle-hide-drawers 'all)
6420 (org-cycle-show-empty-lines 'all)))))
6422 ;; This function uses outline-regexp instead of the more fundamental
6423 ;; org-outline-regexp so that org-cycle-global works outside of Org
6424 ;; buffers, where outline-regexp is needed.
6425 (defun org-overview ()
6426 "Switch to overview mode, showing only top-level headlines.
6427 Really, this shows all headlines with level equal or greater than the level
6428 of the first headline in the buffer. This is important, because if the
6429 first headline is not level one, then (hide-sublevels 1) gives confusing
6430 results."
6431 (interactive)
6432 (let ((level (save-excursion
6433 (goto-char (point-min))
6434 (if (re-search-forward (concat "^" outline-regexp) nil t)
6435 (progn
6436 (goto-char (match-beginning 0))
6437 (funcall outline-level))))))
6438 (and level (hide-sublevels level))))
6440 (defun org-content (&optional arg)
6441 "Show all headlines in the buffer, like a table of contents.
6442 With numerical argument N, show content up to level N."
6443 (interactive "P")
6444 (save-excursion
6445 ;; Visit all headings and show their offspring
6446 (and (integerp arg) (org-overview))
6447 (goto-char (point-max))
6448 (catch 'exit
6449 (while (and (progn (condition-case nil
6450 (outline-previous-visible-heading 1)
6451 (error (goto-char (point-min))))
6453 (looking-at org-outline-regexp))
6454 (if (integerp arg)
6455 (show-children (1- arg))
6456 (show-branches))
6457 (if (bobp) (throw 'exit nil))))))
6460 (defun org-optimize-window-after-visibility-change (state)
6461 "Adjust the window after a change in outline visibility.
6462 This function is the default value of the hook `org-cycle-hook'."
6463 (when (get-buffer-window (current-buffer))
6464 (cond
6465 ((eq state 'content) nil)
6466 ((eq state 'all) nil)
6467 ((eq state 'folded) nil)
6468 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6469 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6471 (defun org-remove-empty-overlays-at (pos)
6472 "Remove outline overlays that do not contain non-white stuff."
6473 (mapc
6474 (lambda (o)
6475 (and (eq 'outline (overlay-get o 'invisible))
6476 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6477 (overlay-end o))))
6478 (delete-overlay o)))
6479 (overlays-at pos)))
6481 (defun org-clean-visibility-after-subtree-move ()
6482 "Fix visibility issues after moving a subtree."
6483 ;; First, find a reasonable region to look at:
6484 ;; Start two siblings above, end three below
6485 (let* ((beg (save-excursion
6486 (and (org-get-last-sibling)
6487 (org-get-last-sibling))
6488 (point)))
6489 (end (save-excursion
6490 (and (org-get-next-sibling)
6491 (org-get-next-sibling)
6492 (org-get-next-sibling))
6493 (if (org-at-heading-p)
6494 (point-at-eol)
6495 (point))))
6496 (level (looking-at "\\*+"))
6497 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6498 (save-excursion
6499 (save-restriction
6500 (narrow-to-region beg end)
6501 (when re
6502 ;; Properly fold already folded siblings
6503 (goto-char (point-min))
6504 (while (re-search-forward re nil t)
6505 (if (and (not (outline-invisible-p))
6506 (save-excursion
6507 (goto-char (point-at-eol)) (outline-invisible-p)))
6508 (hide-entry))))
6509 (org-cycle-show-empty-lines 'overview)
6510 (org-cycle-hide-drawers 'overview)))))
6512 (defun org-cycle-show-empty-lines (state)
6513 "Show empty lines above all visible headlines.
6514 The region to be covered depends on STATE when called through
6515 `org-cycle-hook'. Lisp program can use t for STATE to get the
6516 entire buffer covered. Note that an empty line is only shown if there
6517 are at least `org-cycle-separator-lines' empty lines before the headline."
6518 (when (not (= org-cycle-separator-lines 0))
6519 (save-excursion
6520 (let* ((n (abs org-cycle-separator-lines))
6521 (re (cond
6522 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6523 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6524 (t (let ((ns (number-to-string (- n 2))))
6525 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6526 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6527 beg end b e)
6528 (cond
6529 ((memq state '(overview contents t))
6530 (setq beg (point-min) end (point-max)))
6531 ((memq state '(children folded))
6532 (setq beg (point) end (progn (org-end-of-subtree t t)
6533 (beginning-of-line 2)
6534 (point)))))
6535 (when beg
6536 (goto-char beg)
6537 (while (re-search-forward re end t)
6538 (unless (get-char-property (match-end 1) 'invisible)
6539 (setq e (match-end 1))
6540 (if (< org-cycle-separator-lines 0)
6541 (setq b (save-excursion
6542 (goto-char (match-beginning 0))
6543 (org-back-over-empty-lines)
6544 (if (save-excursion
6545 (goto-char (max (point-min) (1- (point))))
6546 (org-at-heading-p))
6547 (1- (point))
6548 (point))))
6549 (setq b (match-beginning 1)))
6550 (outline-flag-region b e nil)))))))
6551 ;; Never hide empty lines at the end of the file.
6552 (save-excursion
6553 (goto-char (point-max))
6554 (outline-previous-heading)
6555 (outline-end-of-heading)
6556 (if (and (looking-at "[ \t\n]+")
6557 (= (match-end 0) (point-max)))
6558 (outline-flag-region (point) (match-end 0) nil))))
6560 (defun org-show-empty-lines-in-parent ()
6561 "Move to the parent and re-show empty lines before visible headlines."
6562 (save-excursion
6563 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6564 (org-cycle-show-empty-lines context))))
6566 (defun org-files-list ()
6567 "Return `org-agenda-files' list, plus all open org-mode files.
6568 This is useful for operations that need to scan all of a user's
6569 open and agenda-wise Org files."
6570 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6571 (dolist (buf (buffer-list))
6572 (with-current-buffer buf
6573 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6574 (let ((file (expand-file-name (buffer-file-name))))
6575 (unless (member file files)
6576 (push file files))))))
6577 files))
6579 (defsubst org-entry-beginning-position ()
6580 "Return the beginning position of the current entry."
6581 (save-excursion (outline-back-to-heading t) (point)))
6583 (defsubst org-entry-end-position ()
6584 "Return the end position of the current entry."
6585 (save-excursion (outline-next-heading) (point)))
6587 (defun org-cycle-hide-drawers (state)
6588 "Re-hide all drawers after a visibility state change."
6589 (when (and (eq major-mode 'org-mode)
6590 (not (memq state '(overview folded contents))))
6591 (save-excursion
6592 (let* ((globalp (memq state '(contents all)))
6593 (beg (if globalp (point-min) (point)))
6594 (end (if globalp (point-max)
6595 (if (eq state 'children)
6596 (save-excursion (outline-next-heading) (point))
6597 (org-end-of-subtree t)))))
6598 (goto-char beg)
6599 (while (re-search-forward org-drawer-regexp end t)
6600 (org-flag-drawer t))))))
6602 (defun org-flag-drawer (flag)
6603 (save-excursion
6604 (beginning-of-line 1)
6605 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6606 (let ((b (match-end 0)))
6607 (if (re-search-forward
6608 "^[ \t]*:END:"
6609 (save-excursion (outline-next-heading) (point)) t)
6610 (outline-flag-region b (point-at-eol) flag)
6611 (error ":END: line missing at position %s" b))))))
6613 (defun org-subtree-end-visible-p ()
6614 "Is the end of the current subtree visible?"
6615 (pos-visible-in-window-p
6616 (save-excursion (org-end-of-subtree t) (point))))
6618 (defun org-first-headline-recenter (&optional N)
6619 "Move cursor to the first headline and recenter the headline.
6620 Optional argument N means put the headline into the Nth line of the window."
6621 (goto-char (point-min))
6622 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6623 (beginning-of-line)
6624 (recenter (prefix-numeric-value N))))
6626 ;;; Saving and restoring visibility
6628 (defun org-outline-overlay-data (&optional use-markers)
6629 "Return a list of the locations of all outline overlays.
6630 These are overlays with the `invisible' property value `outline'.
6631 The return value is a list of cons cells, with start and stop
6632 positions for each overlay.
6633 If USE-MARKERS is set, return the positions as markers."
6634 (let (beg end)
6635 (save-excursion
6636 (save-restriction
6637 (widen)
6638 (delq nil
6639 (mapcar (lambda (o)
6640 (when (eq (overlay-get o 'invisible) 'outline)
6641 (setq beg (overlay-start o)
6642 end (overlay-end o))
6643 (and beg end (> end beg)
6644 (if use-markers
6645 (cons (move-marker (make-marker) beg)
6646 (move-marker (make-marker) end))
6647 (cons beg end)))))
6648 (overlays-in (point-min) (point-max))))))))
6650 (defun org-set-outline-overlay-data (data)
6651 "Create visibility overlays for all positions in DATA.
6652 DATA should have been made by `org-outline-overlay-data'."
6653 (let (o)
6654 (save-excursion
6655 (save-restriction
6656 (widen)
6657 (show-all)
6658 (mapc (lambda (c)
6659 (outline-flag-region (car c) (cdr c) t))
6660 data)))))
6662 ;;; Folding of blocks
6664 (defvar org-hide-block-overlays nil
6665 "Overlays hiding blocks.")
6666 (make-variable-buffer-local 'org-hide-block-overlays)
6668 (defun org-block-map (function &optional start end)
6669 "Call FUNCTION at the head of all source blocks in the current buffer.
6670 Optional arguments START and END can be used to limit the range."
6671 (let ((start (or start (point-min)))
6672 (end (or end (point-max))))
6673 (save-excursion
6674 (goto-char start)
6675 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6676 (save-excursion
6677 (save-match-data
6678 (goto-char (match-beginning 0))
6679 (funcall function)))))))
6681 (defun org-hide-block-toggle-all ()
6682 "Toggle the visibility of all blocks in the current buffer."
6683 (org-block-map #'org-hide-block-toggle))
6685 (defun org-hide-block-all ()
6686 "Fold all blocks in the current buffer."
6687 (interactive)
6688 (org-show-block-all)
6689 (org-block-map #'org-hide-block-toggle-maybe))
6691 (defun org-show-block-all ()
6692 "Unfold all blocks in the current buffer."
6693 (interactive)
6694 (mapc 'delete-overlay org-hide-block-overlays)
6695 (setq org-hide-block-overlays nil))
6697 (defun org-hide-block-toggle-maybe ()
6698 "Toggle visibility of block at point."
6699 (interactive)
6700 (let ((case-fold-search t))
6701 (if (save-excursion
6702 (beginning-of-line 1)
6703 (looking-at org-block-regexp))
6704 (progn (org-hide-block-toggle)
6705 t) ;; to signal that we took action
6706 nil))) ;; to signal that we did not
6708 (defun org-hide-block-toggle (&optional force)
6709 "Toggle the visibility of the current block."
6710 (interactive)
6711 (save-excursion
6712 (beginning-of-line)
6713 (if (re-search-forward org-block-regexp nil t)
6714 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6715 (end (match-end 0)) ;; end of entire body
6717 (if (memq t (mapcar (lambda (overlay)
6718 (eq (overlay-get overlay 'invisible)
6719 'org-hide-block))
6720 (overlays-at start)))
6721 (if (or (not force) (eq force 'off))
6722 (mapc (lambda (ov)
6723 (when (member ov org-hide-block-overlays)
6724 (setq org-hide-block-overlays
6725 (delq ov org-hide-block-overlays)))
6726 (when (eq (overlay-get ov 'invisible)
6727 'org-hide-block)
6728 (delete-overlay ov)))
6729 (overlays-at start)))
6730 (setq ov (make-overlay start end))
6731 (overlay-put ov 'invisible 'org-hide-block)
6732 ;; make the block accessible to isearch
6733 (overlay-put
6734 ov 'isearch-open-invisible
6735 (lambda (ov)
6736 (when (member ov org-hide-block-overlays)
6737 (setq org-hide-block-overlays
6738 (delq ov org-hide-block-overlays)))
6739 (when (eq (overlay-get ov 'invisible)
6740 'org-hide-block)
6741 (delete-overlay ov))))
6742 (push ov org-hide-block-overlays)))
6743 (error "Not looking at a source block"))))
6745 ;; org-tab-after-check-for-cycling-hook
6746 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6747 ;; Remove overlays when changing major mode
6748 (add-hook 'org-mode-hook
6749 (lambda () (org-add-hook 'change-major-mode-hook
6750 'org-show-block-all 'append 'local)))
6752 ;;; Org-goto
6754 (defvar org-goto-window-configuration nil)
6755 (defvar org-goto-marker nil)
6756 (defvar org-goto-map
6757 (let ((map (make-sparse-keymap)))
6758 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6759 (while (setq cmd (pop cmds))
6760 (substitute-key-definition cmd cmd map global-map)))
6761 (suppress-keymap map)
6762 (org-defkey map "\C-m" 'org-goto-ret)
6763 (org-defkey map [(return)] 'org-goto-ret)
6764 (org-defkey map [(left)] 'org-goto-left)
6765 (org-defkey map [(right)] 'org-goto-right)
6766 (org-defkey map [(control ?g)] 'org-goto-quit)
6767 (org-defkey map "\C-i" 'org-cycle)
6768 (org-defkey map [(tab)] 'org-cycle)
6769 (org-defkey map [(down)] 'outline-next-visible-heading)
6770 (org-defkey map [(up)] 'outline-previous-visible-heading)
6771 (if org-goto-auto-isearch
6772 (if (fboundp 'define-key-after)
6773 (define-key-after map [t] 'org-goto-local-auto-isearch)
6774 nil)
6775 (org-defkey map "q" 'org-goto-quit)
6776 (org-defkey map "n" 'outline-next-visible-heading)
6777 (org-defkey map "p" 'outline-previous-visible-heading)
6778 (org-defkey map "f" 'outline-forward-same-level)
6779 (org-defkey map "b" 'outline-backward-same-level)
6780 (org-defkey map "u" 'outline-up-heading))
6781 (org-defkey map "/" 'org-occur)
6782 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6783 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6784 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6785 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6786 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6787 map))
6789 (defconst org-goto-help
6790 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6791 RET=jump to location [Q]uit and return to previous location
6792 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6794 (defvar org-goto-start-pos) ; dynamically scoped parameter
6796 ;; FIXME: Docstring does not mention both interfaces
6797 (defun org-goto (&optional alternative-interface)
6798 "Look up a different location in the current file, keeping current visibility.
6800 When you want look-up or go to a different location in a document, the
6801 fastest way is often to fold the entire buffer and then dive into the tree.
6802 This method has the disadvantage, that the previous location will be folded,
6803 which may not be what you want.
6805 This command works around this by showing a copy of the current buffer
6806 in an indirect buffer, in overview mode. You can dive into the tree in
6807 that copy, use org-occur and incremental search to find a location.
6808 When pressing RET or `Q', the command returns to the original buffer in
6809 which the visibility is still unchanged. After RET it will also jump to
6810 the location selected in the indirect buffer and expose the headline
6811 hierarchy above."
6812 (interactive "P")
6813 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6814 (org-refile-use-outline-path t)
6815 (org-refile-target-verify-function nil)
6816 (interface
6817 (if (not alternative-interface)
6818 org-goto-interface
6819 (if (eq org-goto-interface 'outline)
6820 'outline-path-completion
6821 'outline)))
6822 (org-goto-start-pos (point))
6823 (selected-point
6824 (if (eq interface 'outline)
6825 (car (org-get-location (current-buffer) org-goto-help))
6826 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6827 (org-refile-check-position pa)
6828 (nth 3 pa)))))
6829 (if selected-point
6830 (progn
6831 (org-mark-ring-push org-goto-start-pos)
6832 (goto-char selected-point)
6833 (if (or (outline-invisible-p) (org-invisible-p2))
6834 (org-show-context 'org-goto)))
6835 (message "Quit"))))
6837 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6838 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6839 (defvar org-goto-local-auto-isearch-map) ; defined below
6841 (defun org-get-location (buf help)
6842 "Let the user select a location in the Org-mode buffer BUF.
6843 This function uses a recursive edit. It returns the selected position
6844 or nil."
6845 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6846 (isearch-hide-immediately nil)
6847 (isearch-search-fun-function
6848 (lambda () 'org-goto-local-search-headings))
6849 (org-goto-selected-point org-goto-exit-command)
6850 (pop-up-frames nil)
6851 (special-display-buffer-names nil)
6852 (special-display-regexps nil)
6853 (special-display-function nil))
6854 (save-excursion
6855 (save-window-excursion
6856 (delete-other-windows)
6857 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6858 (org-pop-to-buffer-same-window
6859 (condition-case nil
6860 (make-indirect-buffer (current-buffer) "*org-goto*")
6861 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6862 (with-output-to-temp-buffer "*Help*"
6863 (princ help))
6864 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6865 (setq buffer-read-only nil)
6866 (let ((org-startup-truncated t)
6867 (org-startup-folded nil)
6868 (org-startup-align-all-tables nil))
6869 (org-mode)
6870 (org-overview))
6871 (setq buffer-read-only t)
6872 (if (and (boundp 'org-goto-start-pos)
6873 (integer-or-marker-p org-goto-start-pos))
6874 (let ((org-show-hierarchy-above t)
6875 (org-show-siblings t)
6876 (org-show-following-heading t))
6877 (goto-char org-goto-start-pos)
6878 (and (outline-invisible-p) (org-show-context)))
6879 (goto-char (point-min)))
6880 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6881 (message "Select location and press RET")
6882 (use-local-map org-goto-map)
6883 (recursive-edit)
6885 (kill-buffer "*org-goto*")
6886 (cons org-goto-selected-point org-goto-exit-command)))
6888 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6889 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6890 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6891 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6893 (defun org-goto-local-search-headings (string bound noerror)
6894 "Search and make sure that any matches are in headlines."
6895 (catch 'return
6896 (while (if isearch-forward
6897 (search-forward string bound noerror)
6898 (search-backward string bound noerror))
6899 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6900 (and (member :headline context)
6901 (not (member :tags context))))
6902 (throw 'return (point))))))
6904 (defun org-goto-local-auto-isearch ()
6905 "Start isearch."
6906 (interactive)
6907 (goto-char (point-min))
6908 (let ((keys (this-command-keys)))
6909 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6910 (isearch-mode t)
6911 (isearch-process-search-char (string-to-char keys)))))
6913 (defun org-goto-ret (&optional arg)
6914 "Finish `org-goto' by going to the new location."
6915 (interactive "P")
6916 (setq org-goto-selected-point (point)
6917 org-goto-exit-command 'return)
6918 (throw 'exit nil))
6920 (defun org-goto-left ()
6921 "Finish `org-goto' by going to the new location."
6922 (interactive)
6923 (if (org-at-heading-p)
6924 (progn
6925 (beginning-of-line 1)
6926 (setq org-goto-selected-point (point)
6927 org-goto-exit-command 'left)
6928 (throw 'exit nil))
6929 (error "Not on a heading")))
6931 (defun org-goto-right ()
6932 "Finish `org-goto' by going to the new location."
6933 (interactive)
6934 (if (org-at-heading-p)
6935 (progn
6936 (setq org-goto-selected-point (point)
6937 org-goto-exit-command 'right)
6938 (throw 'exit nil))
6939 (error "Not on a heading")))
6941 (defun org-goto-quit ()
6942 "Finish `org-goto' without cursor motion."
6943 (interactive)
6944 (setq org-goto-selected-point nil)
6945 (setq org-goto-exit-command 'quit)
6946 (throw 'exit nil))
6948 ;;; Indirect buffer display of subtrees
6950 (defvar org-indirect-dedicated-frame nil
6951 "This is the frame being used for indirect tree display.")
6952 (defvar org-last-indirect-buffer nil)
6954 (defun org-tree-to-indirect-buffer (&optional arg)
6955 "Create indirect buffer and narrow it to current subtree.
6956 With numerical prefix ARG, go up to this level and then take that tree.
6957 If ARG is negative, go up that many levels.
6958 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6959 indirect buffer previously made with this command, to avoid proliferation of
6960 indirect buffers. However, when you call the command with a \
6961 \\[universal-argument] prefix, or
6962 when `org-indirect-buffer-display' is `new-frame', the last buffer
6963 is kept so that you can work with several indirect buffers at the same time.
6964 If `org-indirect-buffer-display' is `dedicated-frame', the \
6965 \\[universal-argument] prefix also
6966 requests that a new frame be made for the new buffer, so that the dedicated
6967 frame is not changed."
6968 (interactive "P")
6969 (let ((cbuf (current-buffer))
6970 (cwin (selected-window))
6971 (pos (point))
6972 beg end level heading ibuf)
6973 (save-excursion
6974 (org-back-to-heading t)
6975 (when (numberp arg)
6976 (setq level (org-outline-level))
6977 (if (< arg 0) (setq arg (+ level arg)))
6978 (while (> (setq level (org-outline-level)) arg)
6979 (outline-up-heading 1 t)))
6980 (setq beg (point)
6981 heading (org-get-heading))
6982 (org-end-of-subtree t t)
6983 (if (org-at-heading-p) (backward-char 1))
6984 (setq end (point)))
6985 (if (and (buffer-live-p org-last-indirect-buffer)
6986 (not (eq org-indirect-buffer-display 'new-frame))
6987 (not arg))
6988 (kill-buffer org-last-indirect-buffer))
6989 (setq ibuf (org-get-indirect-buffer cbuf)
6990 org-last-indirect-buffer ibuf)
6991 (cond
6992 ((or (eq org-indirect-buffer-display 'new-frame)
6993 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6994 (select-frame (make-frame))
6995 (delete-other-windows)
6996 (org-pop-to-buffer-same-window ibuf)
6997 (org-set-frame-title heading))
6998 ((eq org-indirect-buffer-display 'dedicated-frame)
6999 (raise-frame
7000 (select-frame (or (and org-indirect-dedicated-frame
7001 (frame-live-p org-indirect-dedicated-frame)
7002 org-indirect-dedicated-frame)
7003 (setq org-indirect-dedicated-frame (make-frame)))))
7004 (delete-other-windows)
7005 (org-pop-to-buffer-same-window ibuf)
7006 (org-set-frame-title (concat "Indirect: " heading)))
7007 ((eq org-indirect-buffer-display 'current-window)
7008 (org-pop-to-buffer-same-window ibuf))
7009 ((eq org-indirect-buffer-display 'other-window)
7010 (pop-to-buffer ibuf))
7011 (t (error "Invalid value")))
7012 (if (featurep 'xemacs)
7013 (save-excursion (org-mode) (turn-on-font-lock)))
7014 (narrow-to-region beg end)
7015 (show-all)
7016 (goto-char pos)
7017 (run-hook-with-args 'org-cycle-hook 'all)
7018 (and (window-live-p cwin) (select-window cwin))))
7020 (defun org-get-indirect-buffer (&optional buffer)
7021 (setq buffer (or buffer (current-buffer)))
7022 (let ((n 1) (base (buffer-name buffer)) bname)
7023 (while (buffer-live-p
7024 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7025 (setq n (1+ n)))
7026 (condition-case nil
7027 (make-indirect-buffer buffer bname 'clone)
7028 (error (make-indirect-buffer buffer bname)))))
7030 (defun org-set-frame-title (title)
7031 "Set the title of the current frame to the string TITLE."
7032 ;; FIXME: how to name a single frame in XEmacs???
7033 (unless (featurep 'xemacs)
7034 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7036 ;;;; Structure editing
7038 ;;; Inserting headlines
7040 (defun org-previous-line-empty-p ()
7041 (save-excursion
7042 (and (not (bobp))
7043 (or (beginning-of-line 0) t)
7044 (save-match-data
7045 (looking-at "[ \t]*$")))))
7047 (defun org-insert-heading (&optional force-heading invisible-ok)
7048 "Insert a new heading or item with same depth at point.
7049 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7050 If point is at the beginning of a headline, insert a sibling before the
7051 current headline. If point is not at the beginning, split the line,
7052 create the new headline with the text in the current line after point
7053 \(but see also the variable `org-M-RET-may-split-line').
7055 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7056 This is important for non-interactive uses of the command."
7057 (interactive "P")
7058 (if (or (= (buffer-size) 0)
7059 (and (not (save-excursion
7060 (and (ignore-errors (org-back-to-heading invisible-ok))
7061 (org-at-heading-p))))
7062 (or force-heading (not (org-in-item-p)))))
7063 (progn
7064 (insert "\n* ")
7065 (run-hooks 'org-insert-heading-hook))
7066 (when (or force-heading (not (org-insert-item)))
7067 (let* ((empty-line-p nil)
7068 (level nil)
7069 (on-heading (org-at-heading-p))
7070 (head (save-excursion
7071 (condition-case nil
7072 (progn
7073 (org-back-to-heading invisible-ok)
7074 (when (and (not on-heading)
7075 (featurep 'org-inlinetask)
7076 (integerp org-inlinetask-min-level)
7077 (>= (length (match-string 0))
7078 org-inlinetask-min-level))
7079 ;; Find a heading level before the inline task
7080 (while (and (setq level (org-up-heading-safe))
7081 (>= level org-inlinetask-min-level)))
7082 (if (org-at-heading-p)
7083 (org-back-to-heading invisible-ok)
7084 (error "This should not happen")))
7085 (setq empty-line-p (org-previous-line-empty-p))
7086 (match-string 0))
7087 (error "*"))))
7088 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7089 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7090 pos hide-previous previous-pos)
7091 (cond
7092 ((and (org-at-heading-p) (bolp)
7093 (or (bobp)
7094 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7095 ;; insert before the current line
7096 (open-line (if blank 2 1)))
7097 ((and (bolp)
7098 (not org-insert-heading-respect-content)
7099 (or (bobp)
7100 (save-excursion
7101 (backward-char 1) (not (outline-invisible-p)))))
7102 ;; insert right here
7103 nil)
7105 ;; somewhere in the line
7106 (save-excursion
7107 (setq previous-pos (point-at-bol))
7108 (end-of-line)
7109 (setq hide-previous (outline-invisible-p)))
7110 (and org-insert-heading-respect-content (org-show-subtree))
7111 (let ((split
7112 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7113 (save-excursion
7114 (let ((p (point)))
7115 (goto-char (point-at-bol))
7116 (and (looking-at org-complex-heading-regexp)
7117 (match-beginning 4)
7118 (> p (match-beginning 4)))))))
7119 tags pos)
7120 (cond
7121 (org-insert-heading-respect-content
7122 (org-end-of-subtree nil t)
7123 (when (featurep 'org-inlinetask)
7124 (while (and (not (eobp))
7125 (looking-at "\\(\\*+\\)[ \t]+")
7126 (>= (length (match-string 1))
7127 org-inlinetask-min-level))
7128 (org-end-of-subtree nil t)))
7129 (or (bolp) (newline))
7130 (or (org-previous-line-empty-p)
7131 (and blank (newline)))
7132 (open-line 1))
7133 ((org-at-heading-p)
7134 (when hide-previous
7135 (show-children)
7136 (org-show-entry))
7137 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7138 (setq tags (and (match-end 2) (match-string 2)))
7139 (and (match-end 1)
7140 (delete-region (match-beginning 1) (match-end 1)))
7141 (setq pos (point-at-bol))
7142 (or split (end-of-line 1))
7143 (delete-horizontal-space)
7144 (if (string-match "\\`\\*+\\'"
7145 (buffer-substring (point-at-bol) (point)))
7146 (insert " "))
7147 (newline (if blank 2 1))
7148 (when tags
7149 (save-excursion
7150 (goto-char pos)
7151 (end-of-line 1)
7152 (insert " " tags)
7153 (org-set-tags nil 'align))))
7155 (or split (end-of-line 1))
7156 (newline (if blank 2 1)))))))
7157 (insert head) (just-one-space)
7158 (setq pos (point))
7159 (end-of-line 1)
7160 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7161 (when (and org-insert-heading-respect-content hide-previous)
7162 (save-excursion
7163 (goto-char previous-pos)
7164 (hide-subtree)))
7165 (run-hooks 'org-insert-heading-hook)))))
7167 (defun org-get-heading (&optional no-tags no-todo)
7168 "Return the heading of the current entry, without the stars.
7169 When NO-TAGS is non-nil, don't include tags.
7170 When NO-TODO is non-nil, don't include TODO keywords."
7171 (save-excursion
7172 (org-back-to-heading t)
7173 (cond
7174 ((and no-tags no-todo)
7175 (looking-at org-complex-heading-regexp)
7176 (match-string 4))
7177 (no-tags
7178 (looking-at (concat org-outline-regexp
7179 "\\(.*?\\)"
7180 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7181 (match-string 1))
7182 (no-todo
7183 (looking-at org-todo-line-regexp)
7184 (match-string 3))
7185 (t (looking-at org-heading-regexp)
7186 (match-string 2)))))
7188 (defun org-heading-components ()
7189 "Return the components of the current heading.
7190 This is a list with the following elements:
7191 - the level as an integer
7192 - the reduced level, different if `org-odd-levels-only' is set.
7193 - the TODO keyword, or nil
7194 - the priority character, like ?A, or nil if no priority is given
7195 - the headline text itself, or the tags string if no headline text
7196 - the tags string, or nil."
7197 (save-excursion
7198 (org-back-to-heading t)
7199 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7200 (list (length (match-string 1))
7201 (org-reduced-level (length (match-string 1)))
7202 (org-match-string-no-properties 2)
7203 (and (match-end 3) (aref (match-string 3) 2))
7204 (org-match-string-no-properties 4)
7205 (org-match-string-no-properties 5)))))
7207 (defun org-get-entry ()
7208 "Get the entry text, after heading, entire subtree."
7209 (save-excursion
7210 (org-back-to-heading t)
7211 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7213 (defun org-insert-heading-after-current ()
7214 "Insert a new heading with same level as current, after current subtree."
7215 (interactive)
7216 (org-back-to-heading)
7217 (org-insert-heading)
7218 (org-move-subtree-down)
7219 (end-of-line 1))
7221 (defun org-insert-heading-respect-content ()
7222 (interactive)
7223 (let ((org-insert-heading-respect-content t))
7224 (org-insert-heading t)))
7226 (defun org-insert-todo-heading-respect-content (&optional force-state)
7227 (interactive "P")
7228 (let ((org-insert-heading-respect-content t))
7229 (org-insert-todo-heading force-state t)))
7231 (defun org-insert-todo-heading (arg &optional force-heading)
7232 "Insert a new heading with the same level and TODO state as current heading.
7233 If the heading has no TODO state, or if the state is DONE, use the first
7234 state (TODO by default). Also with prefix arg, force first state."
7235 (interactive "P")
7236 (when (or force-heading (not (org-insert-item 'checkbox)))
7237 (org-insert-heading force-heading)
7238 (save-excursion
7239 (org-back-to-heading)
7240 (outline-previous-heading)
7241 (looking-at org-todo-line-regexp))
7242 (let*
7243 ((new-mark-x
7244 (if (or arg
7245 (not (match-beginning 2))
7246 (member (match-string 2) org-done-keywords))
7247 (car org-todo-keywords-1)
7248 (match-string 2)))
7249 (new-mark
7251 (run-hook-with-args-until-success
7252 'org-todo-get-default-hook new-mark-x nil)
7253 new-mark-x)))
7254 (beginning-of-line 1)
7255 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7256 (if org-treat-insert-todo-heading-as-state-change
7257 (org-todo new-mark)
7258 (insert new-mark " "))))
7259 (when org-provide-todo-statistics
7260 (org-update-parent-todo-statistics))))
7262 (defun org-insert-subheading (arg)
7263 "Insert a new subheading and demote it.
7264 Works for outline headings and for plain lists alike."
7265 (interactive "P")
7266 (org-insert-heading arg)
7267 (cond
7268 ((org-at-heading-p) (org-do-demote))
7269 ((org-at-item-p) (org-indent-item))))
7271 (defun org-insert-todo-subheading (arg)
7272 "Insert a new subheading with TODO keyword or checkbox and demote it.
7273 Works for outline headings and for plain lists alike."
7274 (interactive "P")
7275 (org-insert-todo-heading arg)
7276 (cond
7277 ((org-at-heading-p) (org-do-demote))
7278 ((org-at-item-p) (org-indent-item))))
7280 ;;; Promotion and Demotion
7282 (defvar org-after-demote-entry-hook nil
7283 "Hook run after an entry has been demoted.
7284 The cursor will be at the beginning of the entry.
7285 When a subtree is being demoted, the hook will be called for each node.")
7287 (defvar org-after-promote-entry-hook nil
7288 "Hook run after an entry has been promoted.
7289 The cursor will be at the beginning of the entry.
7290 When a subtree is being promoted, the hook will be called for each node.")
7292 (defun org-promote-subtree ()
7293 "Promote the entire subtree.
7294 See also `org-promote'."
7295 (interactive)
7296 (save-excursion
7297 (org-with-limited-levels (org-map-tree 'org-promote)))
7298 (org-fix-position-after-promote))
7300 (defun org-demote-subtree ()
7301 "Demote the entire subtree. See `org-demote'.
7302 See also `org-promote'."
7303 (interactive)
7304 (save-excursion
7305 (org-with-limited-levels (org-map-tree 'org-demote)))
7306 (org-fix-position-after-promote))
7309 (defun org-do-promote ()
7310 "Promote the current heading higher up the tree.
7311 If the region is active in `transient-mark-mode', promote all headings
7312 in the region."
7313 (interactive)
7314 (save-excursion
7315 (if (org-region-active-p)
7316 (org-map-region 'org-promote (region-beginning) (region-end))
7317 (org-promote)))
7318 (org-fix-position-after-promote))
7320 (defun org-do-demote ()
7321 "Demote the current heading lower down the tree.
7322 If the region is active in `transient-mark-mode', demote all headings
7323 in the region."
7324 (interactive)
7325 (save-excursion
7326 (if (org-region-active-p)
7327 (org-map-region 'org-demote (region-beginning) (region-end))
7328 (org-demote)))
7329 (org-fix-position-after-promote))
7331 (defun org-fix-position-after-promote ()
7332 "Make sure that after pro/demotion cursor position is right."
7333 (let ((pos (point)))
7334 (when (save-excursion
7335 (beginning-of-line 1)
7336 (looking-at org-todo-line-regexp)
7337 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7338 (cond ((eobp) (insert " "))
7339 ((eolp) (insert " "))
7340 ((equal (char-after) ?\ ) (forward-char 1))))))
7342 (defun org-current-level ()
7343 "Return the level of the current entry, or nil if before the first headline.
7344 The level is the number of stars at the beginning of the headline."
7345 (save-excursion
7346 (org-with-limited-levels
7347 (if (ignore-errors (org-back-to-heading t))
7348 (funcall outline-level)))))
7350 (defun org-get-previous-line-level ()
7351 "Return the outline depth of the last headline before the current line.
7352 Returns 0 for the first headline in the buffer, and nil if before the
7353 first headline."
7354 (let ((current-level (org-current-level))
7355 (prev-level (when (> (line-number-at-pos) 1)
7356 (save-excursion
7357 (beginning-of-line 0)
7358 (org-current-level)))))
7359 (cond ((null current-level) nil) ; Before first headline
7360 ((null prev-level) 0) ; At first headline
7361 (prev-level))))
7363 (defun org-reduced-level (l)
7364 "Compute the effective level of a heading.
7365 This takes into account the setting of `org-odd-levels-only'."
7366 (cond
7367 ((zerop l) 0)
7368 (org-odd-levels-only (1+ (floor (/ l 2))))
7369 (t l)))
7371 (defun org-level-increment ()
7372 "Return the number of stars that will be added or removed at a
7373 time to headlines when structure editing, based on the value of
7374 `org-odd-levels-only'."
7375 (if org-odd-levels-only 2 1))
7377 (defun org-get-valid-level (level &optional change)
7378 "Rectify a level change under the influence of `org-odd-levels-only'
7379 LEVEL is a current level, CHANGE is by how much the level should be
7380 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7381 even level numbers will become the next higher odd number."
7382 (if org-odd-levels-only
7383 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7384 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7385 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7386 (max 1 (+ level (or change 0)))))
7388 (if (boundp 'define-obsolete-function-alias)
7389 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7390 (define-obsolete-function-alias 'org-get-legal-level
7391 'org-get-valid-level)
7392 (define-obsolete-function-alias 'org-get-legal-level
7393 'org-get-valid-level "23.1")))
7395 (defun org-promote ()
7396 "Promote the current heading higher up the tree.
7397 If the region is active in `transient-mark-mode', promote all headings
7398 in the region."
7399 (org-back-to-heading t)
7400 (let* ((level (save-match-data (funcall outline-level)))
7401 (after-change-functions (remove 'flyspell-after-change-function
7402 after-change-functions))
7403 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7404 (diff (abs (- level (length up-head) -1))))
7405 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7406 (replace-match up-head nil t)
7407 ;; Fixup tag positioning
7408 (and org-auto-align-tags (org-set-tags nil t))
7409 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7410 (run-hooks 'org-after-promote-entry-hook)))
7412 (defun org-demote ()
7413 "Demote the current heading lower down the tree.
7414 If the region is active in `transient-mark-mode', demote all headings
7415 in the region."
7416 (org-back-to-heading t)
7417 (let* ((level (save-match-data (funcall outline-level)))
7418 (after-change-functions (remove 'flyspell-after-change-function
7419 after-change-functions))
7420 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7421 (diff (abs (- level (length down-head) -1))))
7422 (replace-match down-head nil t)
7423 ;; Fixup tag positioning
7424 (and org-auto-align-tags (org-set-tags nil t))
7425 (if org-adapt-indentation (org-fixup-indentation diff))
7426 (run-hooks 'org-after-demote-entry-hook)))
7428 (defun org-cycle-level ()
7429 "Cycle the level of an empty headline through possible states.
7430 This goes first to child, then to parent, level, then up the hierarchy.
7431 After top level, it switches back to sibling level."
7432 (interactive)
7433 (let ((org-adapt-indentation nil))
7434 (when (org-point-at-end-of-empty-headline)
7435 (setq this-command 'org-cycle-level) ; Only needed for caching
7436 (let ((cur-level (org-current-level))
7437 (prev-level (org-get-previous-line-level)))
7438 (cond
7439 ;; If first headline in file, promote to top-level.
7440 ((= prev-level 0)
7441 (loop repeat (/ (- cur-level 1) (org-level-increment))
7442 do (org-do-promote)))
7443 ;; If same level as prev, demote one.
7444 ((= prev-level cur-level)
7445 (org-do-demote))
7446 ;; If parent is top-level, promote to top level if not already.
7447 ((= prev-level 1)
7448 (loop repeat (/ (- cur-level 1) (org-level-increment))
7449 do (org-do-promote)))
7450 ;; If top-level, return to prev-level.
7451 ((= cur-level 1)
7452 (loop repeat (/ (- prev-level 1) (org-level-increment))
7453 do (org-do-demote)))
7454 ;; If less than prev-level, promote one.
7455 ((< cur-level prev-level)
7456 (org-do-promote))
7457 ;; If deeper than prev-level, promote until higher than
7458 ;; prev-level.
7459 ((> cur-level prev-level)
7460 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7461 do (org-do-promote))))
7462 t))))
7464 (defun org-map-tree (fun)
7465 "Call FUN for every heading underneath the current one."
7466 (org-back-to-heading)
7467 (let ((level (funcall outline-level)))
7468 (save-excursion
7469 (funcall fun)
7470 (while (and (progn
7471 (outline-next-heading)
7472 (> (funcall outline-level) level))
7473 (not (eobp)))
7474 (funcall fun)))))
7476 (defun org-map-region (fun beg end)
7477 "Call FUN for every heading between BEG and END."
7478 (let ((org-ignore-region t))
7479 (save-excursion
7480 (setq end (copy-marker end))
7481 (goto-char beg)
7482 (if (and (re-search-forward org-outline-regexp-bol nil t)
7483 (< (point) end))
7484 (funcall fun))
7485 (while (and (progn
7486 (outline-next-heading)
7487 (< (point) end))
7488 (not (eobp)))
7489 (funcall fun)))))
7491 (defvar org-property-end-re) ; silence byte-compiler
7492 (defun org-fixup-indentation (diff)
7493 "Change the indentation in the current entry by DIFF.
7494 However, if any line in the current entry has no indentation, or if it
7495 would end up with no indentation after the change, nothing at all is done."
7496 (save-excursion
7497 (let ((end (save-excursion (outline-next-heading)
7498 (point-marker)))
7499 (prohibit (if (> diff 0)
7500 "^\\S-"
7501 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7502 col)
7503 (unless (save-excursion (end-of-line 1)
7504 (re-search-forward prohibit end t))
7505 (while (and (< (point) end)
7506 (re-search-forward "^[ \t]+" end t))
7507 (goto-char (match-end 0))
7508 (setq col (current-column))
7509 (if (< diff 0) (replace-match ""))
7510 (org-indent-to-column (+ diff col))))
7511 (move-marker end nil))))
7513 (defun org-convert-to-odd-levels ()
7514 "Convert an org-mode file with all levels allowed to one with odd levels.
7515 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7516 level 5 etc."
7517 (interactive)
7518 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7519 (let ((outline-level 'org-outline-level)
7520 (org-odd-levels-only nil) n)
7521 (save-excursion
7522 (goto-char (point-min))
7523 (while (re-search-forward "^\\*\\*+ " nil t)
7524 (setq n (- (length (match-string 0)) 2))
7525 (while (>= (setq n (1- n)) 0)
7526 (org-demote))
7527 (end-of-line 1))))))
7529 (defun org-convert-to-oddeven-levels ()
7530 "Convert an org-mode file with only odd levels to one with odd/even levels.
7531 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7532 file contains a section with an even level, conversion would
7533 destroy the structure of the file. An error is signaled in this
7534 case."
7535 (interactive)
7536 (goto-char (point-min))
7537 ;; First check if there are no even levels
7538 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7539 (org-show-context t)
7540 (error "Not all levels are odd in this file. Conversion not possible"))
7541 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7542 (let ((outline-regexp org-outline-regexp)
7543 (outline-level 'org-outline-level)
7544 (org-odd-levels-only nil) n)
7545 (save-excursion
7546 (goto-char (point-min))
7547 (while (re-search-forward "^\\*\\*+ " nil t)
7548 (setq n (/ (1- (length (match-string 0))) 2))
7549 (while (>= (setq n (1- n)) 0)
7550 (org-promote))
7551 (end-of-line 1))))))
7553 (defun org-tr-level (n)
7554 "Make N odd if required."
7555 (if org-odd-levels-only (1+ (/ n 2)) n))
7557 ;;; Vertical tree motion, cutting and pasting of subtrees
7559 (defun org-move-subtree-up (&optional arg)
7560 "Move the current subtree up past ARG headlines of the same level."
7561 (interactive "p")
7562 (org-move-subtree-down (- (prefix-numeric-value arg))))
7564 (defun org-move-subtree-down (&optional arg)
7565 "Move the current subtree down past ARG headlines of the same level."
7566 (interactive "p")
7567 (setq arg (prefix-numeric-value arg))
7568 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7569 'org-get-last-sibling))
7570 (ins-point (make-marker))
7571 (cnt (abs arg))
7572 (col (current-column))
7573 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7574 ;; Select the tree
7575 (org-back-to-heading)
7576 (setq beg0 (point))
7577 (save-excursion
7578 (setq ne-beg (org-back-over-empty-lines))
7579 (setq beg (point)))
7580 (save-match-data
7581 (save-excursion (outline-end-of-heading)
7582 (setq folded (outline-invisible-p)))
7583 (outline-end-of-subtree))
7584 (outline-next-heading)
7585 (setq ne-end (org-back-over-empty-lines))
7586 (setq end (point))
7587 (goto-char beg0)
7588 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7589 ;; include less whitespace
7590 (save-excursion
7591 (goto-char beg)
7592 (forward-line (- ne-beg ne-end))
7593 (setq beg (point))))
7594 ;; Find insertion point, with error handling
7595 (while (> cnt 0)
7596 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7597 (progn (goto-char beg0)
7598 (error "Cannot move past superior level or buffer limit")))
7599 (setq cnt (1- cnt)))
7600 (if (> arg 0)
7601 ;; Moving forward - still need to move over subtree
7602 (progn (org-end-of-subtree t t)
7603 (save-excursion
7604 (org-back-over-empty-lines)
7605 (or (bolp) (newline)))))
7606 (setq ne-ins (org-back-over-empty-lines))
7607 (move-marker ins-point (point))
7608 (setq txt (buffer-substring beg end))
7609 (org-save-markers-in-region beg end)
7610 (delete-region beg end)
7611 (org-remove-empty-overlays-at beg)
7612 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7613 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7614 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7615 (let ((bbb (point)))
7616 (insert-before-markers txt)
7617 (org-reinstall-markers-in-region bbb)
7618 (move-marker ins-point bbb))
7619 (or (bolp) (insert "\n"))
7620 (setq ins-end (point))
7621 (goto-char ins-point)
7622 (org-skip-whitespace)
7623 (when (and (< arg 0)
7624 (org-first-sibling-p)
7625 (> ne-ins ne-beg))
7626 ;; Move whitespace back to beginning
7627 (save-excursion
7628 (goto-char ins-end)
7629 (let ((kill-whole-line t))
7630 (kill-line (- ne-ins ne-beg)) (point)))
7631 (insert (make-string (- ne-ins ne-beg) ?\n)))
7632 (move-marker ins-point nil)
7633 (if folded
7634 (hide-subtree)
7635 (org-show-entry)
7636 (show-children)
7637 (org-cycle-hide-drawers 'children))
7638 (org-clean-visibility-after-subtree-move)
7639 ;; move back to the initial column we were at
7640 (move-to-column col)))
7642 (defvar org-subtree-clip ""
7643 "Clipboard for cut and paste of subtrees.
7644 This is actually only a copy of the kill, because we use the normal kill
7645 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7647 (defvar org-subtree-clip-folded nil
7648 "Was the last copied subtree folded?
7649 This is used to fold the tree back after pasting.")
7651 (defun org-cut-subtree (&optional n)
7652 "Cut the current subtree into the clipboard.
7653 With prefix arg N, cut this many sequential subtrees.
7654 This is a short-hand for marking the subtree and then cutting it."
7655 (interactive "p")
7656 (org-copy-subtree n 'cut))
7658 (defun org-copy-subtree (&optional n cut force-store-markers)
7659 "Cut the current subtree into the clipboard.
7660 With prefix arg N, cut this many sequential subtrees.
7661 This is a short-hand for marking the subtree and then copying it.
7662 If CUT is non-nil, actually cut the subtree.
7663 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7664 of some markers in the region, even if CUT is non-nil. This is
7665 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7666 (interactive "p")
7667 (let (beg end folded (beg0 (point)))
7668 (if (org-called-interactively-p 'any)
7669 (org-back-to-heading nil) ; take what looks like a subtree
7670 (org-back-to-heading t)) ; take what is really there
7671 (org-back-over-empty-lines)
7672 (setq beg (point))
7673 (skip-chars-forward " \t\r\n")
7674 (save-match-data
7675 (save-excursion (outline-end-of-heading)
7676 (setq folded (outline-invisible-p)))
7677 (condition-case nil
7678 (org-forward-same-level (1- n) t)
7679 (error nil))
7680 (org-end-of-subtree t t))
7681 (org-back-over-empty-lines)
7682 (setq end (point))
7683 (goto-char beg0)
7684 (when (> end beg)
7685 (setq org-subtree-clip-folded folded)
7686 (when (or cut force-store-markers)
7687 (org-save-markers-in-region beg end))
7688 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7689 (setq org-subtree-clip (current-kill 0))
7690 (message "%s: Subtree(s) with %d characters"
7691 (if cut "Cut" "Copied")
7692 (length org-subtree-clip)))))
7694 (defun org-paste-subtree (&optional level tree for-yank)
7695 "Paste the clipboard as a subtree, with modification of headline level.
7696 The entire subtree is promoted or demoted in order to match a new headline
7697 level.
7699 If the cursor is at the beginning of a headline, the same level as
7700 that headline is used to paste the tree
7702 If not, the new level is derived from the *visible* headings
7703 before and after the insertion point, and taken to be the inferior headline
7704 level of the two. So if the previous visible heading is level 3 and the
7705 next is level 4 (or vice versa), level 4 will be used for insertion.
7706 This makes sure that the subtree remains an independent subtree and does
7707 not swallow low level entries.
7709 You can also force a different level, either by using a numeric prefix
7710 argument, or by inserting the heading marker by hand. For example, if the
7711 cursor is after \"*****\", then the tree will be shifted to level 5.
7713 If optional TREE is given, use this text instead of the kill ring.
7715 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7716 move back over whitespace before inserting, and move point to the end of
7717 the inserted text when done."
7718 (interactive "P")
7719 (setq tree (or tree (and kill-ring (current-kill 0))))
7720 (unless (org-kill-is-subtree-p tree)
7721 (error "%s"
7722 (substitute-command-keys
7723 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7724 (org-with-limited-levels
7725 (let* ((visp (not (outline-invisible-p)))
7726 (txt tree)
7727 (^re_ "\\(\\*+\\)[ \t]*")
7728 (old-level (if (string-match org-outline-regexp-bol txt)
7729 (- (match-end 0) (match-beginning 0) 1)
7730 -1))
7731 (force-level (cond (level (prefix-numeric-value level))
7732 ((and (looking-at "[ \t]*$")
7733 (string-match
7734 "^\\*+$" (buffer-substring
7735 (point-at-bol) (point))))
7736 (- (match-end 1) (match-beginning 1)))
7737 ((and (bolp)
7738 (looking-at org-outline-regexp))
7739 (- (match-end 0) (point) 1))
7740 (t nil)))
7741 (previous-level (save-excursion
7742 (condition-case nil
7743 (progn
7744 (outline-previous-visible-heading 1)
7745 (if (looking-at ^re_)
7746 (- (match-end 0) (match-beginning 0) 1)
7748 (error 1))))
7749 (next-level (save-excursion
7750 (condition-case nil
7751 (progn
7752 (or (looking-at org-outline-regexp)
7753 (outline-next-visible-heading 1))
7754 (if (looking-at ^re_)
7755 (- (match-end 0) (match-beginning 0) 1)
7757 (error 1))))
7758 (new-level (or force-level (max previous-level next-level)))
7759 (shift (if (or (= old-level -1)
7760 (= new-level -1)
7761 (= old-level new-level))
7763 (- new-level old-level)))
7764 (delta (if (> shift 0) -1 1))
7765 (func (if (> shift 0) 'org-demote 'org-promote))
7766 (org-odd-levels-only nil)
7767 beg end newend)
7768 ;; Remove the forced level indicator
7769 (if force-level
7770 (delete-region (point-at-bol) (point)))
7771 ;; Paste
7772 (beginning-of-line (if (bolp) 1 2))
7773 (unless for-yank (org-back-over-empty-lines))
7774 (setq beg (point))
7775 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7776 (insert-before-markers txt)
7777 (unless (string-match "\n\\'" txt) (insert "\n"))
7778 (setq newend (point))
7779 (org-reinstall-markers-in-region beg)
7780 (setq end (point))
7781 (goto-char beg)
7782 (skip-chars-forward " \t\n\r")
7783 (setq beg (point))
7784 (if (and (outline-invisible-p) visp)
7785 (save-excursion (outline-show-heading)))
7786 ;; Shift if necessary
7787 (unless (= shift 0)
7788 (save-restriction
7789 (narrow-to-region beg end)
7790 (while (not (= shift 0))
7791 (org-map-region func (point-min) (point-max))
7792 (setq shift (+ delta shift)))
7793 (goto-char (point-min))
7794 (setq newend (point-max))))
7795 (when (or (org-called-interactively-p 'interactive) for-yank)
7796 (message "Clipboard pasted as level %d subtree" new-level))
7797 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7798 kill-ring
7799 (eq org-subtree-clip (current-kill 0))
7800 org-subtree-clip-folded)
7801 ;; The tree was folded before it was killed/copied
7802 (hide-subtree))
7803 (and for-yank (goto-char newend)))))
7805 (defun org-kill-is-subtree-p (&optional txt)
7806 "Check if the current kill is an outline subtree, or a set of trees.
7807 Returns nil if kill does not start with a headline, or if the first
7808 headline level is not the largest headline level in the tree.
7809 So this will actually accept several entries of equal levels as well,
7810 which is OK for `org-paste-subtree'.
7811 If optional TXT is given, check this string instead of the current kill."
7812 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7813 (re (org-get-limited-outline-regexp))
7814 (^re (concat "^" re))
7815 (start-level (and kill
7816 (string-match
7817 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7818 kill)
7819 (- (match-end 2) (match-beginning 2) 1)))
7820 (start (1+ (or (match-beginning 2) -1))))
7821 (if (not start-level)
7822 (progn
7823 nil) ;; does not even start with a heading
7824 (catch 'exit
7825 (while (setq start (string-match ^re kill (1+ start)))
7826 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7827 (throw 'exit nil)))
7828 t))))
7830 (defvar org-markers-to-move nil
7831 "Markers that should be moved with a cut-and-paste operation.
7832 Those markers are stored together with their positions relative to
7833 the start of the region.")
7835 (defun org-save-markers-in-region (beg end)
7836 "Check markers in region.
7837 If these markers are between BEG and END, record their position relative
7838 to BEG, so that after moving the block of text, we can put the markers back
7839 into place.
7840 This function gets called just before an entry or tree gets cut from the
7841 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7842 called immediately, to move the markers with the entries."
7843 (setq org-markers-to-move nil)
7844 (when (featurep 'org-clock)
7845 (org-clock-save-markers-for-cut-and-paste beg end))
7846 (when (featurep 'org-agenda)
7847 (org-agenda-save-markers-for-cut-and-paste beg end)))
7849 (defun org-check-and-save-marker (marker beg end)
7850 "Check if MARKER is between BEG and END.
7851 If yes, remember the marker and the distance to BEG."
7852 (when (and (marker-buffer marker)
7853 (equal (marker-buffer marker) (current-buffer)))
7854 (if (and (>= marker beg) (< marker end))
7855 (push (cons marker (- marker beg)) org-markers-to-move))))
7857 (defun org-reinstall-markers-in-region (beg)
7858 "Move all remembered markers to their position relative to BEG."
7859 (mapc (lambda (x)
7860 (move-marker (car x) (+ beg (cdr x))))
7861 org-markers-to-move)
7862 (setq org-markers-to-move nil))
7864 (defun org-narrow-to-subtree ()
7865 "Narrow buffer to the current subtree."
7866 (interactive)
7867 (save-excursion
7868 (save-match-data
7869 (org-with-limited-levels
7870 (narrow-to-region
7871 (progn (org-back-to-heading t) (point))
7872 (progn (org-end-of-subtree t t)
7873 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7874 (point)))))))
7876 (defun org-narrow-to-block ()
7877 "Narrow buffer to the current block."
7878 (interactive)
7879 (let* ((case-fold-search t)
7880 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7881 "^[ \t]*#\\+end_.*")))
7882 (if blockp
7883 (narrow-to-region (car blockp) (cdr blockp))
7884 (error "Not in a block"))))
7886 (eval-when-compile
7887 (defvar org-property-drawer-re))
7889 (defvar org-property-start-re) ;; defined below
7890 (defun org-clone-subtree-with-time-shift (n &optional shift)
7891 "Clone the task (subtree) at point N times.
7892 The clones will be inserted as siblings.
7894 In interactive use, the user will be prompted for the number of
7895 clones to be produced, and for a time SHIFT, which may be a
7896 repeater as used in time stamps, for example `+3d'.
7898 When a valid repeater is given and the entry contains any time
7899 stamps, the clones will become a sequence in time, with time
7900 stamps in the subtree shifted for each clone produced. If SHIFT
7901 is nil or the empty string, time stamps will be left alone. The
7902 ID property of the original subtree is removed.
7904 If the original subtree did contain time stamps with a repeater,
7905 the following will happen:
7906 - the repeater will be removed in each clone
7907 - an additional clone will be produced, with the current, unshifted
7908 date(s) in the entry.
7909 - the original entry will be placed *after* all the clones, with
7910 repeater intact.
7911 - the start days in the repeater in the original entry will be shifted
7912 to past the last clone.
7913 In this way you can spell out a number of instances of a repeating task,
7914 and still retain the repeater to cover future instances of the task."
7915 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7916 (let (beg end template task idprop
7917 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7918 (drawer-re org-drawer-regexp))
7919 (if (not (and (integerp n) (> n 0)))
7920 (error "Invalid number of replications %s" n))
7921 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7922 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7923 shift)))
7924 (error "Invalid shift specification %s" shift))
7925 (when doshift
7926 (setq shift-n (string-to-number (match-string 1 shift))
7927 shift-what (cdr (assoc (match-string 2 shift)
7928 '(("d" . day) ("w" . week)
7929 ("m" . month) ("y" . year))))))
7930 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7931 (setq nmin 1 nmax n)
7932 (org-back-to-heading t)
7933 (setq beg (point))
7934 (setq idprop (org-entry-get nil "ID"))
7935 (org-end-of-subtree t t)
7936 (or (bolp) (insert "\n"))
7937 (setq end (point))
7938 (setq template (buffer-substring beg end))
7939 (when (and doshift
7940 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7941 (delete-region beg end)
7942 (setq end beg)
7943 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7944 (goto-char end)
7945 (loop for n from nmin to nmax do
7946 ;; prepare clone
7947 (with-temp-buffer
7948 (insert template)
7949 (org-mode)
7950 (goto-char (point-min))
7951 (org-show-subtree)
7952 (and idprop (if org-clone-delete-id
7953 (org-entry-delete nil "ID")
7954 (org-id-get-create t)))
7955 (unless (= n 0)
7956 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7957 (kill-whole-line))
7958 (goto-char (point-min))
7959 (while (re-search-forward drawer-re nil t)
7960 (mapc (lambda (d)
7961 (org-remove-empty-drawer-at d (point))) org-drawers)))
7962 (goto-char (point-min))
7963 (when doshift
7964 (while (re-search-forward org-ts-regexp-both nil t)
7965 (org-timestamp-change (* n shift-n) shift-what))
7966 (unless (= n n-no-remove)
7967 (goto-char (point-min))
7968 (while (re-search-forward org-ts-regexp nil t)
7969 (save-excursion
7970 (goto-char (match-beginning 0))
7971 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
7972 (delete-region (match-beginning 1) (match-end 1)))))))
7973 (setq task (buffer-string)))
7974 (insert task))
7975 (goto-char beg)))
7977 ;;; Outline Sorting
7979 (defun org-sort (with-case)
7980 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7981 Optional argument WITH-CASE means sort case-sensitively."
7982 (interactive "P")
7983 (cond
7984 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7985 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7987 (org-call-with-arg 'org-sort-entries with-case))))
7989 (defun org-sort-remove-invisible (s)
7990 (remove-text-properties 0 (length s) org-rm-props s)
7991 (while (string-match org-bracket-link-regexp s)
7992 (setq s (replace-match (if (match-end 2)
7993 (match-string 3 s)
7994 (match-string 1 s)) t t s)))
7997 (defvar org-priority-regexp) ; defined later in the file
7999 (defvar org-after-sorting-entries-or-items-hook nil
8000 "Hook that is run after a bunch of entries or items have been sorted.
8001 When children are sorted, the cursor is in the parent line when this
8002 hook gets called. When a region or a plain list is sorted, the cursor
8003 will be in the first entry of the sorted region/list.")
8005 (defun org-sort-entries
8006 (&optional with-case sorting-type getkey-func compare-func property)
8007 "Sort entries on a certain level of an outline tree.
8008 If there is an active region, the entries in the region are sorted.
8009 Else, if the cursor is before the first entry, sort the top-level items.
8010 Else, the children of the entry at point are sorted.
8012 Sorting can be alphabetically, numerically, by date/time as given by
8013 a time stamp, by a property or by priority.
8015 The command prompts for the sorting type unless it has been given to the
8016 function through the SORTING-TYPE argument, which needs to be a character,
8017 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8018 precise meaning of each character:
8020 n Numerically, by converting the beginning of the entry/item to a number.
8021 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8022 t By date/time, either the first active time stamp in the entry, or, if
8023 none exist, by the first inactive one.
8024 s By the scheduled date/time.
8025 d By deadline date/time.
8026 c By creation time, which is assumed to be the first inactive time stamp
8027 at the beginning of a line.
8028 p By priority according to the cookie.
8029 r By the value of a property.
8031 Capital letters will reverse the sort order.
8033 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8034 called with point at the beginning of the record. It must return either
8035 a string or a number that should serve as the sorting key for that record.
8037 Comparing entries ignores case by default. However, with an optional argument
8038 WITH-CASE, the sorting considers case as well."
8039 (interactive "P")
8040 (let ((case-func (if with-case 'identity 'downcase))
8041 start beg end stars re re2
8042 txt what tmp)
8043 ;; Find beginning and end of region to sort
8044 (cond
8045 ((org-region-active-p)
8046 ;; we will sort the region
8047 (setq end (region-end)
8048 what "region")
8049 (goto-char (region-beginning))
8050 (if (not (org-at-heading-p)) (outline-next-heading))
8051 (setq start (point)))
8052 ((or (org-at-heading-p)
8053 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8054 ;; we will sort the children of the current headline
8055 (org-back-to-heading)
8056 (setq start (point)
8057 end (progn (org-end-of-subtree t t)
8058 (or (bolp) (insert "\n"))
8059 (org-back-over-empty-lines)
8060 (point))
8061 what "children")
8062 (goto-char start)
8063 (show-subtree)
8064 (outline-next-heading))
8066 ;; we will sort the top-level entries in this file
8067 (goto-char (point-min))
8068 (or (org-at-heading-p) (outline-next-heading))
8069 (setq start (point))
8070 (goto-char (point-max))
8071 (beginning-of-line 1)
8072 (when (looking-at ".*?\\S-")
8073 ;; File ends in a non-white line
8074 (end-of-line 1)
8075 (insert "\n"))
8076 (setq end (point-max))
8077 (setq what "top-level")
8078 (goto-char start)
8079 (show-all)))
8081 (setq beg (point))
8082 (if (>= beg end) (error "Nothing to sort"))
8084 (looking-at "\\(\\*+\\)")
8085 (setq stars (match-string 1)
8086 re (concat "^" (regexp-quote stars) " +")
8087 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8088 txt (buffer-substring beg end))
8089 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8090 (if (and (not (equal stars "*")) (string-match re2 txt))
8091 (error "Region to sort contains a level above the first entry"))
8093 (unless sorting-type
8094 (message
8095 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8096 [t]ime [s]cheduled [d]eadline [c]reated
8097 A/N/T/S/D/C/P/O/F means reversed:"
8098 what)
8099 (setq sorting-type (read-char-exclusive))
8101 (and (= (downcase sorting-type) ?f)
8102 (setq getkey-func
8103 (org-icompleting-read "Sort using function: "
8104 obarray 'fboundp t nil nil))
8105 (setq getkey-func (intern getkey-func)))
8107 (and (= (downcase sorting-type) ?r)
8108 (setq property
8109 (org-icompleting-read "Property: "
8110 (mapcar 'list (org-buffer-property-keys t))
8111 nil t))))
8113 (message "Sorting entries...")
8115 (save-restriction
8116 (narrow-to-region start end)
8117 (let ((dcst (downcase sorting-type))
8118 (case-fold-search nil)
8119 (now (current-time)))
8120 (sort-subr
8121 (/= dcst sorting-type)
8122 ;; This function moves to the beginning character of the "record" to
8123 ;; be sorted.
8124 (lambda nil
8125 (if (re-search-forward re nil t)
8126 (goto-char (match-beginning 0))
8127 (goto-char (point-max))))
8128 ;; This function moves to the last character of the "record" being
8129 ;; sorted.
8130 (lambda nil
8131 (save-match-data
8132 (condition-case nil
8133 (outline-forward-same-level 1)
8134 (error
8135 (goto-char (point-max))))))
8136 ;; This function returns the value that gets sorted against.
8137 (lambda nil
8138 (cond
8139 ((= dcst ?n)
8140 (if (looking-at org-complex-heading-regexp)
8141 (string-to-number (match-string 4))
8142 nil))
8143 ((= dcst ?a)
8144 (if (looking-at org-complex-heading-regexp)
8145 (funcall case-func (match-string 4))
8146 nil))
8147 ((= dcst ?t)
8148 (let ((end (save-excursion (outline-next-heading) (point))))
8149 (if (or (re-search-forward org-ts-regexp end t)
8150 (re-search-forward org-ts-regexp-both end t))
8151 (org-time-string-to-seconds (match-string 0))
8152 (org-float-time now))))
8153 ((= dcst ?c)
8154 (let ((end (save-excursion (outline-next-heading) (point))))
8155 (if (re-search-forward
8156 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8157 end t)
8158 (org-time-string-to-seconds (match-string 0))
8159 (org-float-time now))))
8160 ((= dcst ?s)
8161 (let ((end (save-excursion (outline-next-heading) (point))))
8162 (if (re-search-forward org-scheduled-time-regexp end t)
8163 (org-time-string-to-seconds (match-string 1))
8164 (org-float-time now))))
8165 ((= dcst ?d)
8166 (let ((end (save-excursion (outline-next-heading) (point))))
8167 (if (re-search-forward org-deadline-time-regexp end t)
8168 (org-time-string-to-seconds (match-string 1))
8169 (org-float-time now))))
8170 ((= dcst ?p)
8171 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8172 (string-to-char (match-string 2))
8173 org-default-priority))
8174 ((= dcst ?r)
8175 (or (org-entry-get nil property) ""))
8176 ((= dcst ?o)
8177 (if (looking-at org-complex-heading-regexp)
8178 (- 9999 (length (member (match-string 2)
8179 org-todo-keywords-1)))))
8180 ((= dcst ?f)
8181 (if getkey-func
8182 (progn
8183 (setq tmp (funcall getkey-func))
8184 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8185 tmp)
8186 (error "Invalid key function `%s'" getkey-func)))
8187 (t (error "Invalid sorting type `%c'" sorting-type))))
8189 (cond
8190 ((= dcst ?a) 'string<)
8191 ((= dcst ?f) compare-func)
8192 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8193 (t nil)))))
8194 (run-hooks 'org-after-sorting-entries-or-items-hook)
8195 (message "Sorting entries...done")))
8197 (defun org-do-sort (table what &optional with-case sorting-type)
8198 "Sort TABLE of WHAT according to SORTING-TYPE.
8199 The user will be prompted for the SORTING-TYPE if the call to this
8200 function does not specify it. WHAT is only for the prompt, to indicate
8201 what is being sorted. The sorting key will be extracted from
8202 the car of the elements of the table.
8203 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8204 (unless sorting-type
8205 (message
8206 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8207 what)
8208 (setq sorting-type (read-char-exclusive)))
8209 (let ((dcst (downcase sorting-type))
8210 extractfun comparefun)
8211 ;; Define the appropriate functions
8212 (cond
8213 ((= dcst ?n)
8214 (setq extractfun 'string-to-number
8215 comparefun (if (= dcst sorting-type) '< '>)))
8216 ((= dcst ?a)
8217 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8218 (lambda(x) (downcase (org-sort-remove-invisible x))))
8219 comparefun (if (= dcst sorting-type)
8220 'string<
8221 (lambda (a b) (and (not (string< a b))
8222 (not (string= a b)))))))
8223 ((= dcst ?t)
8224 (setq extractfun
8225 (lambda (x)
8226 (if (or (string-match org-ts-regexp x)
8227 (string-match org-ts-regexp-both x))
8228 (org-float-time
8229 (org-time-string-to-time (match-string 0 x)))
8231 comparefun (if (= dcst sorting-type) '< '>)))
8232 (t (error "Invalid sorting type `%c'" sorting-type)))
8234 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8235 table)
8236 (lambda (a b) (funcall comparefun (car a) (car b))))))
8239 ;;; The orgstruct minor mode
8241 ;; Define a minor mode which can be used in other modes in order to
8242 ;; integrate the org-mode structure editing commands.
8244 ;; This is really a hack, because the org-mode structure commands use
8245 ;; keys which normally belong to the major mode. Here is how it
8246 ;; works: The minor mode defines all the keys necessary to operate the
8247 ;; structure commands, but wraps the commands into a function which
8248 ;; tests if the cursor is currently at a headline or a plain list
8249 ;; item. If that is the case, the structure command is used,
8250 ;; temporarily setting many Org-mode variables like regular
8251 ;; expressions for filling etc. However, when any of those keys is
8252 ;; used at a different location, function uses `key-binding' to look
8253 ;; up if the key has an associated command in another currently active
8254 ;; keymap (minor modes, major mode, global), and executes that
8255 ;; command. There might be problems if any of the keys is otherwise
8256 ;; used as a prefix key.
8258 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8259 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8260 ;; addresses this by checking explicitly for both bindings.
8262 (defvar orgstruct-mode-map (make-sparse-keymap)
8263 "Keymap for the minor `orgstruct-mode'.")
8265 (defvar org-local-vars nil
8266 "List of local variables, for use by `orgstruct-mode'.")
8268 ;;;###autoload
8269 (define-minor-mode orgstruct-mode
8270 "Toggle the minor mode `orgstruct-mode'.
8271 This mode is for using Org-mode structure commands in other
8272 modes. The following keys behave as if Org-mode were active, if
8273 the cursor is on a headline, or on a plain list item (both as
8274 defined by Org-mode).
8276 M-up Move entry/item up
8277 M-down Move entry/item down
8278 M-left Promote
8279 M-right Demote
8280 M-S-up Move entry/item up
8281 M-S-down Move entry/item down
8282 M-S-left Promote subtree
8283 M-S-right Demote subtree
8284 M-q Fill paragraph and items like in Org-mode
8285 C-c ^ Sort entries
8286 C-c - Cycle list bullet
8287 TAB Cycle item visibility
8288 M-RET Insert new heading/item
8289 S-M-RET Insert new TODO heading / Checkbox item
8290 C-c C-c Set tags / toggle checkbox"
8291 nil " OrgStruct" nil
8292 (org-load-modules-maybe)
8293 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8295 ;;;###autoload
8296 (defun turn-on-orgstruct ()
8297 "Unconditionally turn on `orgstruct-mode'."
8298 (orgstruct-mode 1))
8300 (defun orgstruct++-mode (&optional arg)
8301 "Toggle `orgstruct-mode', the enhanced version of it.
8302 In addition to setting orgstruct-mode, this also exports all indentation
8303 and autofilling variables from org-mode into the buffer. It will also
8304 recognize item context in multiline items.
8305 Note that turning off orgstruct-mode will *not* remove the
8306 indentation/paragraph settings. This can only be done by refreshing the
8307 major mode, for example with \\[normal-mode]."
8308 (interactive "P")
8309 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8310 (if (< arg 1)
8311 (orgstruct-mode -1)
8312 (orgstruct-mode 1)
8313 (let (var val)
8314 (mapc
8315 (lambda (x)
8316 (when (string-match
8317 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8318 (symbol-name (car x)))
8319 (setq var (car x) val (nth 1 x))
8320 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8321 org-local-vars)
8322 (org-set-local 'orgstruct-is-++ t))))
8324 (defvar orgstruct-is-++ nil
8325 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8326 (make-variable-buffer-local 'orgstruct-is-++)
8328 ;;;###autoload
8329 (defun turn-on-orgstruct++ ()
8330 "Unconditionally turn on `orgstruct++-mode'."
8331 (orgstruct++-mode 1))
8333 (defun orgstruct-error ()
8334 "Error when there is no default binding for a structure key."
8335 (interactive)
8336 (error "This key has no function outside structure elements"))
8338 (defun orgstruct-setup ()
8339 "Setup orgstruct keymaps."
8340 (let ((nfunc 0)
8341 (bindings
8342 (list
8343 '([(meta up)] org-metaup)
8344 '([(meta down)] org-metadown)
8345 '([(meta left)] org-metaleft)
8346 '([(meta right)] org-metaright)
8347 '([(meta shift up)] org-shiftmetaup)
8348 '([(meta shift down)] org-shiftmetadown)
8349 '([(meta shift left)] org-shiftmetaleft)
8350 '([(meta shift right)] org-shiftmetaright)
8351 '([?\e (up)] org-metaup)
8352 '([?\e (down)] org-metadown)
8353 '([?\e (left)] org-metaleft)
8354 '([?\e (right)] org-metaright)
8355 '([?\e (shift up)] org-shiftmetaup)
8356 '([?\e (shift down)] org-shiftmetadown)
8357 '([?\e (shift left)] org-shiftmetaleft)
8358 '([?\e (shift right)] org-shiftmetaright)
8359 '([(shift up)] org-shiftup)
8360 '([(shift down)] org-shiftdown)
8361 '([(shift left)] org-shiftleft)
8362 '([(shift right)] org-shiftright)
8363 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8364 '("\M-q" fill-paragraph)
8365 '("\C-c^" org-sort)
8366 '("\C-c-" org-cycle-list-bullet)))
8367 elt key fun cmd)
8368 (while (setq elt (pop bindings))
8369 (setq nfunc (1+ nfunc))
8370 (setq key (org-key (car elt))
8371 fun (nth 1 elt)
8372 cmd (orgstruct-make-binding fun nfunc key))
8373 (org-defkey orgstruct-mode-map key cmd))
8375 ;; Special treatment needed for TAB and RET
8376 (org-defkey orgstruct-mode-map [(tab)]
8377 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8378 (org-defkey orgstruct-mode-map "\C-i"
8379 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8381 (org-defkey orgstruct-mode-map "\M-\C-m"
8382 (orgstruct-make-binding 'org-insert-heading 105
8383 "\M-\C-m" [(meta return)]))
8384 (org-defkey orgstruct-mode-map [(meta return)]
8385 (orgstruct-make-binding 'org-insert-heading 106
8386 [(meta return)] "\M-\C-m"))
8388 (org-defkey orgstruct-mode-map [(shift meta return)]
8389 (orgstruct-make-binding 'org-insert-todo-heading 107
8390 [(meta return)] "\M-\C-m"))
8392 (org-defkey orgstruct-mode-map "\e\C-m"
8393 (orgstruct-make-binding 'org-insert-heading 108
8394 "\e\C-m" [?\e (return)]))
8395 (org-defkey orgstruct-mode-map [?\e (return)]
8396 (orgstruct-make-binding 'org-insert-heading 109
8397 [?\e (return)] "\e\C-m"))
8398 (org-defkey orgstruct-mode-map [?\e (shift return)]
8399 (orgstruct-make-binding 'org-insert-todo-heading 110
8400 [?\e (return)] "\e\C-m"))
8402 (unless org-local-vars
8403 (setq org-local-vars (org-get-local-variables)))
8407 (defun orgstruct-make-binding (fun n &rest keys)
8408 "Create a function for binding in the structure minor mode.
8409 FUN is the command to call inside a table. N is used to create a unique
8410 command name. KEYS are keys that should be checked in for a command
8411 to execute outside of tables."
8412 (eval
8413 (list 'defun
8414 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8415 '(arg)
8416 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8417 "Outside of structure, run the binding of `"
8418 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8419 "'.")
8420 '(interactive "p")
8421 (list 'if
8422 `(org-context-p 'headline 'item
8423 (and orgstruct-is-++
8424 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8425 'item-body))
8426 (list 'org-run-like-in-org-mode (list 'quote fun))
8427 (list 'let '(orgstruct-mode)
8428 (list 'call-interactively
8429 (append '(or)
8430 (mapcar (lambda (k)
8431 (list 'key-binding k))
8432 keys)
8433 '('orgstruct-error))))))))
8435 (defun org-context-p (&rest contexts)
8436 "Check if local context is any of CONTEXTS.
8437 Possible values in the list of contexts are `table', `headline', and `item'."
8438 (let ((pos (point)))
8439 (goto-char (point-at-bol))
8440 (prog1 (or (and (memq 'table contexts)
8441 (looking-at "[ \t]*|"))
8442 (and (memq 'headline contexts)
8443 (looking-at org-outline-regexp))
8444 (and (memq 'item contexts)
8445 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8446 (and (memq 'item-body contexts)
8447 (org-in-item-p)))
8448 (goto-char pos))))
8450 (defun org-get-local-variables ()
8451 "Return a list of all local variables in an org-mode buffer."
8452 (let (varlist)
8453 (with-current-buffer (get-buffer-create "*Org tmp*")
8454 (erase-buffer)
8455 (org-mode)
8456 (setq varlist (buffer-local-variables)))
8457 (kill-buffer "*Org tmp*")
8458 (delq nil
8459 (mapcar
8460 (lambda (x)
8461 (setq x
8462 (if (symbolp x)
8463 (list x)
8464 (list (car x) (list 'quote (cdr x)))))
8465 (if (string-match
8466 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8467 (symbol-name (car x)))
8468 x nil))
8469 varlist))))
8471 (defun org-clone-local-variables (from-buffer &optional regexp)
8472 "Clone local variables from FROM-BUFFER.
8473 Optional argument REGEXP selects variables to clone."
8474 (mapc
8475 (lambda (pair)
8476 (and (symbolp (car pair))
8477 (or (null regexp)
8478 (string-match regexp (symbol-name (car pair))))
8479 (set (make-local-variable (car pair))
8480 (cdr pair))))
8481 (buffer-local-variables from-buffer)))
8483 ;;;###autoload
8484 (defun org-run-like-in-org-mode (cmd)
8485 "Run a command, pretending that the current buffer is in Org-mode.
8486 This will temporarily bind local variables that are typically bound in
8487 Org-mode to the values they have in Org-mode, and then interactively
8488 call CMD."
8489 (org-load-modules-maybe)
8490 (unless org-local-vars
8491 (setq org-local-vars (org-get-local-variables)))
8492 (eval (list 'let org-local-vars
8493 (list 'call-interactively (list 'quote cmd)))))
8495 ;;;; Archiving
8497 (defun org-get-category (&optional pos force-refresh)
8498 "Get the category applying to position POS."
8499 (save-match-data
8500 (if force-refresh (org-refresh-category-properties))
8501 (let ((pos (or pos (point))))
8502 (or (get-text-property pos 'org-category)
8503 (progn (org-refresh-category-properties)
8504 (get-text-property pos 'org-category))))))
8506 (defun org-refresh-category-properties ()
8507 "Refresh category text properties in the buffer."
8508 (let ((def-cat (cond
8509 ((null org-category)
8510 (if buffer-file-name
8511 (file-name-sans-extension
8512 (file-name-nondirectory buffer-file-name))
8513 "???"))
8514 ((symbolp org-category) (symbol-name org-category))
8515 (t org-category)))
8516 beg end cat pos optionp)
8517 (org-unmodified
8518 (save-excursion
8519 (save-restriction
8520 (widen)
8521 (goto-char (point-min))
8522 (put-text-property (point) (point-max) 'org-category def-cat)
8523 (while (re-search-forward
8524 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8525 (setq pos (match-end 0)
8526 optionp (equal (char-after (match-beginning 0)) ?#)
8527 cat (org-trim (match-string 2)))
8528 (if optionp
8529 (setq beg (point-at-bol) end (point-max))
8530 (org-back-to-heading t)
8531 (setq beg (point) end (org-end-of-subtree t t)))
8532 (put-text-property beg end 'org-category cat)
8533 (put-text-property beg end 'org-category-position beg)
8534 (goto-char pos)))))))
8537 ;;;; Link Stuff
8539 ;;; Link abbreviations
8541 (defun org-link-expand-abbrev (link)
8542 "Apply replacements as defined in `org-link-abbrev-alist."
8543 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8544 (let* ((key (match-string 1 link))
8545 (as (or (assoc key org-link-abbrev-alist-local)
8546 (assoc key org-link-abbrev-alist)))
8547 (tag (and (match-end 2) (match-string 3 link)))
8548 rpl)
8549 (if (not as)
8550 link
8551 (setq rpl (cdr as))
8552 (cond
8553 ((symbolp rpl) (funcall rpl tag))
8554 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8555 ((string-match "%h" rpl)
8556 (replace-match (url-hexify-string (or tag "")) t t rpl))
8557 (t (concat rpl tag)))))
8558 link))
8560 ;;; Storing and inserting links
8562 (defvar org-insert-link-history nil
8563 "Minibuffer history for links inserted with `org-insert-link'.")
8565 (defvar org-stored-links nil
8566 "Contains the links stored with `org-store-link'.")
8568 (defvar org-store-link-plist nil
8569 "Plist with info about the most recently link created with `org-store-link'.")
8571 (defvar org-link-protocols nil
8572 "Link protocols added to Org-mode using `org-add-link-type'.")
8574 (defvar org-store-link-functions nil
8575 "List of functions that are called to create and store a link.
8576 Each function will be called in turn until one returns a non-nil
8577 value. Each function should check if it is responsible for creating
8578 this link (for example by looking at the major mode).
8579 If not, it must exit and return nil.
8580 If yes, it should return a non-nil value after a calling
8581 `org-store-link-props' with a list of properties and values.
8582 Special properties are:
8584 :type The link prefix, like \"http\". This must be given.
8585 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8586 This is obligatory as well.
8587 :description Optional default description for the second pair
8588 of brackets in an Org-mode link. The user can still change
8589 this when inserting this link into an Org-mode buffer.
8591 In addition to these, any additional properties can be specified
8592 and then used in remember templates.")
8594 (defun org-add-link-type (type &optional follow export)
8595 "Add TYPE to the list of `org-link-types'.
8596 Re-compute all regular expressions depending on `org-link-types'
8598 FOLLOW and EXPORT are two functions.
8600 FOLLOW should take the link path as the single argument and do whatever
8601 is necessary to follow the link, for example find a file or display
8602 a mail message.
8604 EXPORT should format the link path for export to one of the export formats.
8605 It should be a function accepting three arguments:
8607 path the path of the link, the text after the prefix (like \"http:\")
8608 desc the description of the link, if any, or a description added by
8609 org-export-normalize-links if there is none
8610 format the export format, a symbol like `html' or `latex' or `ascii'..
8612 The function may use the FORMAT information to return different values
8613 depending on the format. The return value will be put literally into
8614 the exported file. If the return value is nil, this means Org should
8615 do what it normally does with links which do not have EXPORT defined.
8617 Org-mode has a built-in default for exporting links. If you are happy with
8618 this default, there is no need to define an export function for the link
8619 type. For a simple example of an export function, see `org-bbdb.el'."
8620 (add-to-list 'org-link-types type t)
8621 (org-make-link-regexps)
8622 (if (assoc type org-link-protocols)
8623 (setcdr (assoc type org-link-protocols) (list follow export))
8624 (push (list type follow export) org-link-protocols)))
8626 (defvar org-agenda-buffer-name)
8628 ;;;###autoload
8629 (defun org-store-link (arg)
8630 "\\<org-mode-map>Store an org-link to the current location.
8631 This link is added to `org-stored-links' and can later be inserted
8632 into an org-buffer with \\[org-insert-link].
8634 For some link types, a prefix arg is interpreted:
8635 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8636 For file links, arg negates `org-context-in-file-links'."
8637 (interactive "P")
8638 (org-load-modules-maybe)
8639 (setq org-store-link-plist nil) ; reset
8640 (org-with-limited-levels
8641 (let (link cpltxt desc description search txt custom-id agenda-link)
8642 (cond
8644 ((run-hook-with-args-until-success 'org-store-link-functions)
8645 (setq link (plist-get org-store-link-plist :link)
8646 desc (or (plist-get org-store-link-plist :description) link)))
8648 ((org-src-edit-buffer-p)
8649 (let (label gc)
8650 (while (or (not label)
8651 (save-excursion
8652 (save-restriction
8653 (widen)
8654 (goto-char (point-min))
8655 (re-search-forward
8656 (regexp-quote (format org-coderef-label-format label))
8657 nil t))))
8658 (when label (message "Label exists already") (sit-for 2))
8659 (setq label (read-string "Code line label: " label)))
8660 (end-of-line 1)
8661 (setq link (format org-coderef-label-format label))
8662 (setq gc (- 79 (length link)))
8663 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8664 (insert link)
8665 (setq link (concat "(" label ")") desc nil)))
8667 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8668 ;; We are in the agenda, link to referenced location
8669 (let ((m (or (get-text-property (point) 'org-hd-marker)
8670 (get-text-property (point) 'org-marker))))
8671 (when m
8672 (org-with-point-at m
8673 (setq agenda-link
8674 (if (org-called-interactively-p 'any)
8675 (call-interactively 'org-store-link)
8676 (org-store-link nil)))))))
8678 ((eq major-mode 'calendar-mode)
8679 (let ((cd (calendar-cursor-to-date)))
8680 (setq link
8681 (format-time-string
8682 (car org-time-stamp-formats)
8683 (apply 'encode-time
8684 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8685 nil nil nil))))
8686 (org-store-link-props :type "calendar" :date cd)))
8688 ((eq major-mode 'w3-mode)
8689 (setq cpltxt (if (and (buffer-name)
8690 (not (string-match "Untitled" (buffer-name))))
8691 (buffer-name)
8692 (url-view-url t))
8693 link (org-make-link (url-view-url t)))
8694 (org-store-link-props :type "w3" :url (url-view-url t)))
8696 ((eq major-mode 'w3m-mode)
8697 (setq cpltxt (or w3m-current-title w3m-current-url)
8698 link (org-make-link w3m-current-url))
8699 (org-store-link-props :type "w3m" :url (url-view-url t)))
8701 ((setq search (run-hook-with-args-until-success
8702 'org-create-file-search-functions))
8703 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8704 "::" search))
8705 (setq cpltxt (or description link)))
8707 ((eq major-mode 'image-mode)
8708 (setq cpltxt (concat "file:"
8709 (abbreviate-file-name buffer-file-name))
8710 link (org-make-link cpltxt))
8711 (org-store-link-props :type "image" :file buffer-file-name))
8713 ((eq major-mode 'dired-mode)
8714 ;; link to the file in the current line
8715 (let ((file (dired-get-filename nil t)))
8716 (setq file (if file
8717 (abbreviate-file-name
8718 (expand-file-name (dired-get-filename nil t)))
8719 ;; otherwise, no file so use current directory.
8720 default-directory))
8721 (setq cpltxt (concat "file:" file)
8722 link (org-make-link cpltxt))))
8724 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8725 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8726 (cond
8727 ((org-in-regexp "<<\\(.*?\\)>>")
8728 (setq cpltxt
8729 (concat "file:"
8730 (abbreviate-file-name
8731 (buffer-file-name (buffer-base-buffer)))
8732 "::" (match-string 1))
8733 link (org-make-link cpltxt)))
8734 ((and (featurep 'org-id)
8735 (or (eq org-link-to-org-use-id t)
8736 (and (eq org-link-to-org-use-id 'create-if-interactive)
8737 (org-called-interactively-p 'any))
8738 (and (eq org-link-to-org-use-id
8739 'create-if-interactive-and-no-custom-id)
8740 (org-called-interactively-p 'any)
8741 (not custom-id))
8742 (and org-link-to-org-use-id
8743 (org-entry-get nil "ID"))))
8744 ;; We can make a link using the ID.
8745 (setq link (condition-case nil
8746 (prog1 (org-id-store-link)
8747 (setq desc (plist-get org-store-link-plist
8748 :description)))
8749 (error
8750 ;; probably before first headline, link to file only
8751 (concat "file:"
8752 (abbreviate-file-name
8753 (buffer-file-name (buffer-base-buffer))))))))
8755 ;; Just link to current headline
8756 (setq cpltxt (concat "file:"
8757 (abbreviate-file-name
8758 (buffer-file-name (buffer-base-buffer)))))
8759 ;; Add a context search string
8760 (when (org-xor org-context-in-file-links arg)
8761 (setq txt (cond
8762 ((org-at-heading-p) nil)
8763 ((org-region-active-p)
8764 (buffer-substring (region-beginning) (region-end)))
8765 (t nil)))
8766 (when (or (null txt) (string-match "\\S-" txt))
8767 (setq cpltxt
8768 (concat cpltxt "::"
8769 (condition-case nil
8770 (org-make-org-heading-search-string txt)
8771 (error "")))
8772 desc (or (nth 4 (ignore-errors
8773 (org-heading-components))) "NONE"))))
8774 (if (string-match "::\\'" cpltxt)
8775 (setq cpltxt (substring cpltxt 0 -2)))
8776 (setq link (org-make-link cpltxt)))))
8778 ((buffer-file-name (buffer-base-buffer))
8779 ;; Just link to this file here.
8780 (setq cpltxt (concat "file:"
8781 (abbreviate-file-name
8782 (buffer-file-name (buffer-base-buffer)))))
8783 ;; Add a context string
8784 (when (org-xor org-context-in-file-links arg)
8785 (setq txt (if (org-region-active-p)
8786 (buffer-substring (region-beginning) (region-end))
8787 (buffer-substring (point-at-bol) (point-at-eol))))
8788 ;; Only use search option if there is some text.
8789 (when (string-match "\\S-" txt)
8790 (setq cpltxt
8791 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8792 desc "NONE")))
8793 (setq link (org-make-link cpltxt)))
8795 ((org-called-interactively-p 'interactive)
8796 (error "Cannot link to a buffer which is not visiting a file"))
8798 (t (setq link nil)))
8800 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8801 (setq link (or link cpltxt)
8802 desc (or desc cpltxt))
8803 (if (equal desc "NONE") (setq desc nil))
8805 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8806 (progn
8807 (setq org-stored-links
8808 (cons (list link desc) org-stored-links))
8809 (message "Stored: %s" (or desc link))
8810 (when custom-id
8811 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8812 "::#" custom-id))
8813 (setq org-stored-links
8814 (cons (list link desc) org-stored-links))))
8815 (or agenda-link (and link (org-make-link-string link desc)))))))
8817 (defun org-store-link-props (&rest plist)
8818 "Store link properties, extract names and addresses."
8819 (let (x adr)
8820 (when (setq x (plist-get plist :from))
8821 (setq adr (mail-extract-address-components x))
8822 (setq plist (plist-put plist :fromname (car adr)))
8823 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8824 (when (setq x (plist-get plist :to))
8825 (setq adr (mail-extract-address-components x))
8826 (setq plist (plist-put plist :toname (car adr)))
8827 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8828 (let ((from (plist-get plist :from))
8829 (to (plist-get plist :to)))
8830 (when (and from to org-from-is-user-regexp)
8831 (setq plist
8832 (plist-put plist :fromto
8833 (if (string-match org-from-is-user-regexp from)
8834 (concat "to %t")
8835 (concat "from %f"))))))
8836 (setq org-store-link-plist plist))
8838 (defun org-add-link-props (&rest plist)
8839 "Add these properties to the link property list."
8840 (let (key value)
8841 (while plist
8842 (setq key (pop plist) value (pop plist))
8843 (setq org-store-link-plist
8844 (plist-put org-store-link-plist key value)))))
8846 (defun org-email-link-description (&optional fmt)
8847 "Return the description part of an email link.
8848 This takes information from `org-store-link-plist' and formats it
8849 according to FMT (default from `org-email-link-description-format')."
8850 (setq fmt (or fmt org-email-link-description-format))
8851 (let* ((p org-store-link-plist)
8852 (to (plist-get p :toaddress))
8853 (from (plist-get p :fromaddress))
8854 (table
8855 (list
8856 (cons "%c" (plist-get p :fromto))
8857 (cons "%F" (plist-get p :from))
8858 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8859 (cons "%T" (plist-get p :to))
8860 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8861 (cons "%s" (plist-get p :subject))
8862 (cons "%d" (plist-get p :date))
8863 (cons "%m" (plist-get p :message-id)))))
8864 (when (string-match "%c" fmt)
8865 ;; Check if the user wrote this message
8866 (if (and org-from-is-user-regexp from to
8867 (save-match-data (string-match org-from-is-user-regexp from)))
8868 (setq fmt (replace-match "to %t" t t fmt))
8869 (setq fmt (replace-match "from %f" t t fmt))))
8870 (org-replace-escapes fmt table)))
8872 (defun org-make-org-heading-search-string (&optional string heading)
8873 "Make search string for STRING or current headline."
8874 (interactive)
8875 (let ((s (or string (org-get-heading)))
8876 (lines org-context-in-file-links))
8877 (unless (and string (not heading))
8878 ;; We are using a headline, clean up garbage in there.
8879 (if (string-match org-todo-regexp s)
8880 (setq s (replace-match "" t t s)))
8881 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8882 (setq s (replace-match "" t t s)))
8883 (setq s (org-trim s))
8884 (if (string-match (concat "^\\(" org-quote-string "\\|"
8885 org-comment-string "\\)") s)
8886 (setq s (replace-match "" t t s)))
8887 (while (string-match org-ts-regexp s)
8888 (setq s (replace-match "" t t s))))
8889 (or string (setq s (concat "*" s))) ; Add * for headlines
8890 (when (and string (integerp lines) (> lines 0))
8891 (let ((slines (org-split-string s "\n")))
8892 (when (< lines (length slines))
8893 (setq s (mapconcat
8894 'identity
8895 (reverse (nthcdr (- (length slines) lines)
8896 (reverse slines))) "\n")))))
8897 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8899 (defun org-make-link (&rest strings)
8900 "Concatenate STRINGS."
8901 (apply 'concat strings))
8903 (defun org-make-link-string (link &optional description)
8904 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8905 (unless (string-match "\\S-" link)
8906 (error "Empty link"))
8907 (when (and description
8908 (stringp description)
8909 (not (string-match "\\S-" description)))
8910 (setq description nil))
8911 (when (stringp description)
8912 ;; Remove brackets from the description, they are fatal.
8913 (while (string-match "\\[" description)
8914 (setq description (replace-match "{" t t description)))
8915 (while (string-match "\\]" description)
8916 (setq description (replace-match "}" t t description))))
8917 (when (equal link description)
8918 ;; No description needed, it is identical
8919 (setq description nil))
8920 (when (and (not description)
8921 (not (string-match (org-image-file-name-regexp) link))
8922 (not (equal link (org-link-escape link))))
8923 (setq description (org-extract-attributes link)))
8924 (setq link
8925 (cond ((string-match (org-image-file-name-regexp) link) link)
8926 ((string-match org-link-types-re link)
8927 (concat (match-string 1 link)
8928 (org-link-escape (substring link (match-end 1)))))
8929 (t (org-link-escape link))))
8930 (concat "[[" link "]"
8931 (if description (concat "[" description "]") "")
8932 "]"))
8934 (defconst org-link-escape-chars
8935 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8936 "List of characters that should be escaped in link.
8937 This is the list that is used for internal purposes.")
8939 (defvar org-url-encoding-use-url-hexify nil)
8941 (defconst org-link-escape-chars-browser
8942 '(?\ )
8943 "List of escapes for characters that are problematic in links.
8944 This is the list that is used before handing over to the browser.")
8946 (defun org-link-escape (text &optional table merge)
8947 "Return percent escaped representation of TEXT.
8948 TEXT is a string with the text to escape.
8949 Optional argument TABLE is a list with characters that should be
8950 escaped. When nil, `org-link-escape-chars' is used.
8951 If optional argument MERGE is set, merge TABLE into
8952 `org-link-escape-chars'."
8953 (if (and org-url-encoding-use-url-hexify (not table))
8954 (url-hexify-string text)
8955 (cond
8956 ((and table merge)
8957 (mapc (lambda (defchr)
8958 (unless (member defchr table)
8959 (setq table (cons defchr table)))) org-link-escape-chars))
8960 ((null table)
8961 (setq table org-link-escape-chars)))
8962 (mapconcat
8963 (lambda (char)
8964 (if (or (member char table)
8965 (< char 32) (= char 37) (> char 126))
8966 (mapconcat (lambda (sequence-element)
8967 (format "%%%.2X" sequence-element))
8968 (or (encode-coding-char char 'utf-8)
8969 (error "Unable to percent escape character: %s"
8970 (char-to-string char))) "")
8971 (char-to-string char))) text "")))
8973 (defun org-link-unescape (str)
8974 "Unhex hexified Unicode strings as returned from the JavaScript function
8975 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8976 (unless (and (null str) (string= "" str))
8977 (let ((pos 0) (case-fold-search t) unhexed)
8978 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8979 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8980 (setq str (replace-match unhexed t t str))
8981 (setq pos (+ pos (length unhexed))))))
8982 str)
8984 (defun org-link-unescape-compound (hex)
8985 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8986 Note: this function also decodes single byte encodings like
8987 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8988 (save-match-data
8989 (let* ((bytes (cdr (split-string hex "%")))
8990 (ret "")
8991 (eat 0)
8992 (sum 0))
8993 (while bytes
8994 (let* ((val (string-to-number (pop bytes) 16))
8995 (shift-xor
8996 (if (= 0 eat)
8997 (cond
8998 ((>= val 252) (cons 6 252))
8999 ((>= val 248) (cons 5 248))
9000 ((>= val 240) (cons 4 240))
9001 ((>= val 224) (cons 3 224))
9002 ((>= val 192) (cons 2 192))
9003 (t (cons 0 0)))
9004 (cons 6 128))))
9005 (if (>= val 192) (setq eat (car shift-xor)))
9006 (setq val (logxor val (cdr shift-xor)))
9007 (setq sum (+ (lsh sum (car shift-xor)) val))
9008 (if (> eat 0) (setq eat (- eat 1)))
9009 (cond
9010 ((= 0 eat) ;multi byte
9011 (setq ret (concat ret (org-char-to-string sum)))
9012 (setq sum 0))
9013 ((not bytes) ; single byte(s)
9014 (setq ret (org-link-unescape-single-byte-sequence hex))))
9015 )) ;; end (while bytes
9016 ret )))
9018 (defun org-link-unescape-single-byte-sequence (hex)
9019 "Unhexify hex-encoded single byte character sequences."
9020 (mapconcat (lambda (byte)
9021 (char-to-string (string-to-number byte 16)))
9022 (cdr (split-string hex "%")) ""))
9024 (defun org-xor (a b)
9025 "Exclusive or."
9026 (if a (not b) b))
9028 (defun org-fixup-message-id-for-http (s)
9029 "Replace special characters in a message id, so it can be used in an http query."
9030 (when (string-match "%" s)
9031 (setq s (mapconcat (lambda (c)
9032 (if (eq c ?%)
9033 "%25"
9034 (char-to-string c)))
9035 s "")))
9036 (while (string-match "<" s)
9037 (setq s (replace-match "%3C" t t s)))
9038 (while (string-match ">" s)
9039 (setq s (replace-match "%3E" t t s)))
9040 (while (string-match "@" s)
9041 (setq s (replace-match "%40" t t s)))
9044 ;;;###autoload
9045 (defun org-insert-link-global ()
9046 "Insert a link like Org-mode does.
9047 This command can be called in any mode to insert a link in Org-mode syntax."
9048 (interactive)
9049 (org-load-modules-maybe)
9050 (org-run-like-in-org-mode 'org-insert-link))
9052 (defun org-insert-link (&optional complete-file link-location default-description)
9053 "Insert a link. At the prompt, enter the link.
9055 Completion can be used to insert any of the link protocol prefixes like
9056 http or ftp in use.
9058 The history can be used to select a link previously stored with
9059 `org-store-link'. When the empty string is entered (i.e. if you just
9060 press RET at the prompt), the link defaults to the most recently
9061 stored link. As SPC triggers completion in the minibuffer, you need to
9062 use M-SPC or C-q SPC to force the insertion of a space character.
9064 You will also be prompted for a description, and if one is given, it will
9065 be displayed in the buffer instead of the link.
9067 If there is already a link at point, this command will allow you to edit link
9068 and description parts.
9070 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9071 be selected using completion. The path to the file will be relative to the
9072 current directory if the file is in the current directory or a subdirectory.
9073 Otherwise, the link will be the absolute path as completed in the minibuffer
9074 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9075 option `org-link-file-path-type'.
9077 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9078 the current directory or below.
9080 With three \\[universal-argument] prefixes, negate the meaning of
9081 `org-keep-stored-link-after-insertion'.
9083 If `org-make-link-description-function' is non-nil, this function will be
9084 called with the link target, and the result will be the default
9085 link description.
9087 If the LINK-LOCATION parameter is non-nil, this value will be
9088 used as the link location instead of reading one interactively.
9090 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9091 be used as the default description."
9092 (interactive "P")
9093 (let* ((wcf (current-window-configuration))
9094 (region (if (org-region-active-p)
9095 (buffer-substring (region-beginning) (region-end))))
9096 (remove (and region (list (region-beginning) (region-end))))
9097 (desc region)
9098 tmphist ; byte-compile incorrectly complains about this
9099 (link link-location)
9100 entry file all-prefixes)
9101 (cond
9102 (link-location) ; specified by arg, just use it.
9103 ((org-in-regexp org-bracket-link-regexp 1)
9104 ;; We do have a link at point, and we are going to edit it.
9105 (setq remove (list (match-beginning 0) (match-end 0)))
9106 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9107 (setq link (read-string "Link: "
9108 (org-link-unescape
9109 (org-match-string-no-properties 1)))))
9110 ((or (org-in-regexp org-angle-link-re)
9111 (org-in-regexp org-plain-link-re))
9112 ;; Convert to bracket link
9113 (setq remove (list (match-beginning 0) (match-end 0))
9114 link (read-string "Link: "
9115 (org-remove-angle-brackets (match-string 0)))))
9116 ((member complete-file '((4) (16)))
9117 ;; Completing read for file names.
9118 (setq link (org-file-complete-link complete-file)))
9120 ;; Read link, with completion for stored links.
9121 (with-output-to-temp-buffer "*Org Links*"
9122 (princ "Insert a link.
9123 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9124 (when org-stored-links
9125 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9126 (princ (mapconcat
9127 (lambda (x)
9128 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9129 (reverse org-stored-links) "\n"))))
9130 (let ((cw (selected-window)))
9131 (select-window (get-buffer-window "*Org Links*" 'visible))
9132 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9133 (unless (pos-visible-in-window-p (point-max))
9134 (org-fit-window-to-buffer))
9135 (and (window-live-p cw) (select-window cw)))
9136 ;; Fake a link history, containing the stored links.
9137 (setq tmphist (append (mapcar 'car org-stored-links)
9138 org-insert-link-history))
9139 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9140 (mapcar 'car org-link-abbrev-alist)
9141 org-link-types))
9142 (unwind-protect
9143 (progn
9144 (setq link
9145 (let ((org-completion-use-ido nil)
9146 (org-completion-use-iswitchb nil))
9147 (org-completing-read
9148 "Link: "
9149 (append
9150 (mapcar (lambda (x) (list (concat x ":")))
9151 all-prefixes)
9152 (mapcar 'car org-stored-links))
9153 nil nil nil
9154 'tmphist
9155 (car (car org-stored-links)))))
9156 (if (not (string-match "\\S-" link))
9157 (error "No link selected"))
9158 (if (or (member link all-prefixes)
9159 (and (equal ":" (substring link -1))
9160 (member (substring link 0 -1) all-prefixes)
9161 (setq link (substring link 0 -1))))
9162 (setq link (org-link-try-special-completion link))))
9163 (set-window-configuration wcf)
9164 (kill-buffer "*Org Links*"))
9165 (setq entry (assoc link org-stored-links))
9166 (or entry (push link org-insert-link-history))
9167 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9168 (not org-keep-stored-link-after-insertion))
9169 (setq org-stored-links (delq (assoc link org-stored-links)
9170 org-stored-links)))
9171 (setq desc (or desc (nth 1 entry)))))
9173 (if (string-match org-plain-link-re link)
9174 ;; URL-like link, normalize the use of angular brackets.
9175 (setq link (org-make-link (org-remove-angle-brackets link))))
9177 ;; Check if we are linking to the current file with a search option
9178 ;; If yes, simplify the link by using only the search option.
9179 (when (and buffer-file-name
9180 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9181 (let* ((path (match-string 1 link))
9182 (case-fold-search nil)
9183 (search (match-string 2 link)))
9184 (save-match-data
9185 (if (equal (file-truename buffer-file-name) (file-truename path))
9186 ;; We are linking to this same file, with a search option
9187 (setq link search)))))
9189 ;; Check if we can/should use a relative path. If yes, simplify the link
9190 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9191 (let* ((type (match-string 1 link))
9192 (path (match-string 2 link))
9193 (origpath path)
9194 (case-fold-search nil))
9195 (cond
9196 ((or (eq org-link-file-path-type 'absolute)
9197 (equal complete-file '(16)))
9198 (setq path (abbreviate-file-name (expand-file-name path))))
9199 ((eq org-link-file-path-type 'noabbrev)
9200 (setq path (expand-file-name path)))
9201 ((eq org-link-file-path-type 'relative)
9202 (setq path (file-relative-name path)))
9204 (save-match-data
9205 (if (string-match (concat "^" (regexp-quote
9206 (expand-file-name
9207 (file-name-as-directory
9208 default-directory))))
9209 (expand-file-name path))
9210 ;; We are linking a file with relative path name.
9211 (setq path (substring (expand-file-name path)
9212 (match-end 0)))
9213 (setq path (abbreviate-file-name (expand-file-name path)))))))
9214 (setq link (concat type path))
9215 (if (equal desc origpath)
9216 (setq desc path))))
9218 (if org-make-link-description-function
9219 (setq desc (funcall org-make-link-description-function link desc))
9220 (if default-description (setq desc default-description)))
9222 (setq desc (read-string "Description: " desc))
9223 (unless (string-match "\\S-" desc) (setq desc nil))
9224 (if remove (apply 'delete-region remove))
9225 (insert (org-make-link-string link desc))))
9227 (defun org-link-try-special-completion (type)
9228 "If there is completion support for link type TYPE, offer it."
9229 (let ((fun (intern (concat "org-" type "-complete-link"))))
9230 (if (functionp fun)
9231 (funcall fun)
9232 (read-string "Link (no completion support): " (concat type ":")))))
9234 (defun org-file-complete-link (&optional arg)
9235 "Create a file link using completion."
9236 (let (file link)
9237 (setq file (read-file-name "File: "))
9238 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9239 (pwd1 (file-name-as-directory (abbreviate-file-name
9240 (expand-file-name ".")))))
9241 (cond
9242 ((equal arg '(16))
9243 (setq link (org-make-link
9244 "file:"
9245 (abbreviate-file-name (expand-file-name file)))))
9246 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9247 (setq link (org-make-link "file:" (match-string 1 file))))
9248 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9249 (expand-file-name file))
9250 (setq link (org-make-link
9251 "file:" (match-string 1 (expand-file-name file)))))
9252 (t (setq link (org-make-link "file:" file)))))
9253 link))
9255 (defun org-completing-read (&rest args)
9256 "Completing-read with SPACE being a normal character."
9257 (let ((enable-recursive-minibuffers t)
9258 (minibuffer-local-completion-map
9259 (copy-keymap minibuffer-local-completion-map)))
9260 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9261 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9262 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9263 (apply 'org-icompleting-read args)))
9265 (defun org-completing-read-no-i (&rest args)
9266 (let (org-completion-use-ido org-completion-use-iswitchb)
9267 (apply 'org-completing-read args)))
9269 (defun org-iswitchb-completing-read (prompt choices &rest args)
9270 "Use iswitch as a completing-read replacement to choose from choices.
9271 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9272 from."
9273 (let* ((iswitchb-use-virtual-buffers nil)
9274 (iswitchb-make-buflist-hook
9275 (lambda ()
9276 (setq iswitchb-temp-buflist choices))))
9277 (iswitchb-read-buffer prompt)))
9279 (defun org-icompleting-read (&rest args)
9280 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9281 (org-without-partial-completion
9282 (if (and org-completion-use-ido
9283 (fboundp 'ido-completing-read)
9284 (boundp 'ido-mode) ido-mode
9285 (listp (second args)))
9286 (let ((ido-enter-matching-directory nil))
9287 (apply 'ido-completing-read (concat (car args))
9288 (if (consp (car (nth 1 args)))
9289 (mapcar 'car (nth 1 args))
9290 (nth 1 args))
9291 (cddr args)))
9292 (if (and org-completion-use-iswitchb
9293 (boundp 'iswitchb-mode) iswitchb-mode
9294 (listp (second args)))
9295 (apply 'org-iswitchb-completing-read (concat (car args))
9296 (if (consp (car (nth 1 args)))
9297 (mapcar 'car (nth 1 args))
9298 (nth 1 args))
9299 (cddr args))
9300 (apply 'completing-read args)))))
9302 (defun org-extract-attributes (s)
9303 "Extract the attributes cookie from a string and set as text property."
9304 (let (a attr (start 0) key value)
9305 (save-match-data
9306 (when (string-match "{{\\([^}]+\\)}}$" s)
9307 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9308 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9309 (setq key (match-string 1 a) value (match-string 2 a)
9310 start (match-end 0)
9311 attr (plist-put attr (intern key) value))))
9312 (org-add-props s nil 'org-attr attr))
9315 (defun org-extract-attributes-from-string (tag)
9316 (let (key value attr)
9317 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9318 (setq key (match-string 1 tag) value (match-string 2 tag)
9319 tag (replace-match "" t t tag)
9320 attr (plist-put attr (intern key) value)))
9321 (cons tag attr)))
9323 (defun org-attributes-to-string (plist)
9324 "Format a property list into an HTML attribute list."
9325 (let ((s "") key value)
9326 (while plist
9327 (setq key (pop plist) value (pop plist))
9328 (and value
9329 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9332 ;;; Opening/following a link
9334 (defvar org-link-search-failed nil)
9336 (defvar org-open-link-functions nil
9337 "Hook for functions finding a plain text link.
9338 These functions must take a single argument, the link content.
9339 They will be called for links that look like [[link text][description]]
9340 when LINK TEXT does not have a protocol like \"http:\" and does not look
9341 like a filename (e.g. \"./blue.png\").
9343 These functions will be called *before* Org attempts to resolve the
9344 link by doing text searches in the current buffer - so if you want a
9345 link \"[[target]]\" to still find \"<<target>>\", your function should
9346 handle this as a special case.
9348 When the function does handle the link, it must return a non-nil value.
9349 If it decides that it is not responsible for this link, it must return
9350 nil to indicate that that Org-mode can continue with other options
9351 like exact and fuzzy text search.")
9353 (defun org-next-link ()
9354 "Move forward to the next link.
9355 If the link is in hidden text, expose it."
9356 (interactive)
9357 (when (and org-link-search-failed (eq this-command last-command))
9358 (goto-char (point-min))
9359 (message "Link search wrapped back to beginning of buffer"))
9360 (setq org-link-search-failed nil)
9361 (let* ((pos (point))
9362 (ct (org-context))
9363 (a (assoc :link ct)))
9364 (if a (goto-char (nth 2 a)))
9365 (if (re-search-forward org-any-link-re nil t)
9366 (progn
9367 (goto-char (match-beginning 0))
9368 (if (outline-invisible-p) (org-show-context)))
9369 (goto-char pos)
9370 (setq org-link-search-failed t)
9371 (error "No further link found"))))
9373 (defun org-previous-link ()
9374 "Move backward to the previous link.
9375 If the link is in hidden text, expose it."
9376 (interactive)
9377 (when (and org-link-search-failed (eq this-command last-command))
9378 (goto-char (point-max))
9379 (message "Link search wrapped back to end of buffer"))
9380 (setq org-link-search-failed nil)
9381 (let* ((pos (point))
9382 (ct (org-context))
9383 (a (assoc :link ct)))
9384 (if a (goto-char (nth 1 a)))
9385 (if (re-search-backward org-any-link-re nil t)
9386 (progn
9387 (goto-char (match-beginning 0))
9388 (if (outline-invisible-p) (org-show-context)))
9389 (goto-char pos)
9390 (setq org-link-search-failed t)
9391 (error "No further link found"))))
9393 (defun org-translate-link (s)
9394 "Translate a link string if a translation function has been defined."
9395 (if (and org-link-translation-function
9396 (fboundp org-link-translation-function)
9397 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9398 (progn
9399 (setq s (funcall org-link-translation-function
9400 (match-string 1) (match-string 2)))
9401 (concat (car s) ":" (cdr s)))
9404 (defun org-translate-link-from-planner (type path)
9405 "Translate a link from Emacs Planner syntax so that Org can follow it.
9406 This is still an experimental function, your mileage may vary."
9407 (cond
9408 ((member type '("http" "https" "news" "ftp"))
9409 ;; standard Internet links are the same.
9410 nil)
9411 ((and (equal type "irc") (string-match "^//" path))
9412 ;; Planner has two / at the beginning of an irc link, we have 1.
9413 ;; We should have zero, actually....
9414 (setq path (substring path 1)))
9415 ((and (equal type "lisp") (string-match "^/" path))
9416 ;; Planner has a slash, we do not.
9417 (setq type "elisp" path (substring path 1)))
9418 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9419 ;; A typical message link. Planner has the id after the final slash,
9420 ;; we separate it with a hash mark
9421 (setq path (concat (match-string 1 path) "#"
9422 (org-remove-angle-brackets (match-string 2 path)))))
9424 (cons type path))
9426 (defun org-find-file-at-mouse (ev)
9427 "Open file link or URL at mouse."
9428 (interactive "e")
9429 (mouse-set-point ev)
9430 (org-open-at-point 'in-emacs))
9432 (defun org-open-at-mouse (ev)
9433 "Open file link or URL at mouse.
9434 See the docstring of `org-open-file' for details."
9435 (interactive "e")
9436 (mouse-set-point ev)
9437 (if (eq major-mode 'org-agenda-mode)
9438 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9439 (org-open-at-point))
9441 (defvar org-window-config-before-follow-link nil
9442 "The window configuration before following a link.
9443 This is saved in case the need arises to restore it.")
9445 (defvar org-open-link-marker (make-marker)
9446 "Marker pointing to the location where `org-open-at-point; was called.")
9448 ;;;###autoload
9449 (defun org-open-at-point-global ()
9450 "Follow a link like Org-mode does.
9451 This command can be called in any mode to follow a link that has
9452 Org-mode syntax."
9453 (interactive)
9454 (org-run-like-in-org-mode 'org-open-at-point))
9456 ;;;###autoload
9457 (defun org-open-link-from-string (s &optional arg reference-buffer)
9458 "Open a link in the string S, as if it was in Org-mode."
9459 (interactive "sLink: \nP")
9460 (let ((reference-buffer (or reference-buffer (current-buffer))))
9461 (with-temp-buffer
9462 (let ((org-inhibit-startup (not reference-buffer)))
9463 (org-mode)
9464 (insert s)
9465 (goto-char (point-min))
9466 (when reference-buffer
9467 (setq org-link-abbrev-alist-local
9468 (with-current-buffer reference-buffer
9469 org-link-abbrev-alist-local)))
9470 (org-open-at-point arg reference-buffer)))))
9472 (defvar org-open-at-point-functions nil
9473 "Hook that is run when following a link at point.
9475 Functions in this hook must return t if they identify and follow
9476 a link at point. If they don't find anything interesting at point,
9477 they must return nil.")
9479 (defun org-open-at-point (&optional arg reference-buffer)
9480 "Open link at or after point.
9481 If there is no link at point, this function will search forward up to
9482 the end of the current line.
9483 Normally, files will be opened by an appropriate application. If the
9484 optional prefix argument ARG is non-nil, Emacs will visit the file.
9485 With a double prefix argument, try to open outside of Emacs, in the
9486 application the system uses for this file type."
9487 (interactive "P")
9488 ;; if in a code block, then open the block's results
9489 (unless (call-interactively #'org-babel-open-src-block-result)
9490 (org-load-modules-maybe)
9491 (move-marker org-open-link-marker (point))
9492 (setq org-window-config-before-follow-link (current-window-configuration))
9493 (org-remove-occur-highlights nil nil t)
9494 (cond
9495 ((and (org-at-heading-p)
9496 (not (org-in-regexp
9497 (concat org-plain-link-re "\\|"
9498 org-bracket-link-regexp "\\|"
9499 org-angle-link-re "\\|"
9500 "[ \t]:[^ \t\n]+:[ \t]*$")))
9501 (not (get-text-property (point) 'org-linked-text)))
9502 (or (org-offer-links-in-entry arg)
9503 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9504 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9505 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9506 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9507 (not (org-in-regexp org-bracket-link-regexp)))
9508 (org-footnote-action))
9510 (let (type path link line search (pos (point)))
9511 (catch 'match
9512 (save-excursion
9513 (skip-chars-forward "^]\n\r")
9514 (when (org-in-regexp org-bracket-link-regexp 1)
9515 (setq link (org-extract-attributes
9516 (org-link-unescape (org-match-string-no-properties 1))))
9517 (while (string-match " *\n *" link)
9518 (setq link (replace-match " " t t link)))
9519 (setq link (org-link-expand-abbrev link))
9520 (cond
9521 ((or (file-name-absolute-p link)
9522 (string-match "^\\.\\.?/" link))
9523 (setq type "file" path link))
9524 ((string-match org-link-re-with-space3 link)
9525 (setq type (match-string 1 link) path (match-string 2 link)))
9526 (t (setq type "thisfile" path link)))
9527 (throw 'match t)))
9529 (when (get-text-property (point) 'org-linked-text)
9530 (setq type "thisfile"
9531 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9532 (1+ (point)) (point))
9533 path (buffer-substring
9534 (or (previous-single-property-change pos 'org-linked-text)
9535 (point-min))
9536 (or (next-single-property-change pos 'org-linked-text)
9537 (point-max))))
9538 (throw 'match t))
9540 (save-excursion
9541 (when (or (org-in-regexp org-angle-link-re)
9542 (org-in-regexp org-plain-link-re))
9543 (setq type (match-string 1)
9544 path (org-link-unescape (match-string 2)))
9545 (throw 'match t)))
9546 (save-excursion
9547 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9548 (setq type "tags"
9549 path (match-string 1))
9550 (while (string-match ":" path)
9551 (setq path (replace-match "+" t t path)))
9552 (throw 'match t)))
9553 (when (org-in-regexp "<\\([^><\n]+\\)>")
9554 (setq type "tree-match"
9555 path (match-string 1))
9556 (throw 'match t)))
9557 (unless path
9558 (error "No link found"))
9560 ;; switch back to reference buffer
9561 ;; needed when if called in a temporary buffer through
9562 ;; org-open-link-from-string
9563 (with-current-buffer (or reference-buffer (current-buffer))
9565 ;; Remove any trailing spaces in path
9566 (if (string-match " +\\'" path)
9567 (setq path (replace-match "" t t path)))
9568 (if (and org-link-translation-function
9569 (fboundp org-link-translation-function))
9570 ;; Check if we need to translate the link
9571 (let ((tmp (funcall org-link-translation-function type path)))
9572 (setq type (car tmp) path (cdr tmp))))
9574 (cond
9576 ((assoc type org-link-protocols)
9577 (funcall (nth 1 (assoc type org-link-protocols)) path))
9579 ((equal type "mailto")
9580 (let ((cmd (car org-link-mailto-program))
9581 (args (cdr org-link-mailto-program)) args1
9582 (address path) (subject "") a)
9583 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9584 (setq address (match-string 1 path)
9585 subject (org-link-escape (match-string 2 path))))
9586 (while args
9587 (cond
9588 ((not (stringp (car args))) (push (pop args) args1))
9589 (t (setq a (pop args))
9590 (if (string-match "%a" a)
9591 (setq a (replace-match address t t a)))
9592 (if (string-match "%s" a)
9593 (setq a (replace-match subject t t a)))
9594 (push a args1))))
9595 (apply cmd (nreverse args1))))
9597 ((member type '("http" "https" "ftp" "news"))
9598 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9599 (org-link-escape
9600 path org-link-escape-chars-browser)
9601 path))))
9603 ((string= type "doi")
9604 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9605 (org-link-escape
9606 path org-link-escape-chars-browser)
9607 path))))
9609 ((member type '("message"))
9610 (browse-url (concat type ":" path)))
9612 ((string= type "tags")
9613 (org-tags-view arg path))
9615 ((string= type "tree-match")
9616 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9618 ((string= type "file")
9619 (if (string-match "::\\([0-9]+\\)\\'" path)
9620 (setq line (string-to-number (match-string 1 path))
9621 path (substring path 0 (match-beginning 0)))
9622 (if (string-match "::\\(.+\\)\\'" path)
9623 (setq search (match-string 1 path)
9624 path (substring path 0 (match-beginning 0)))))
9625 (if (string-match "[*?{]" (file-name-nondirectory path))
9626 (dired path)
9627 (org-open-file path arg line search)))
9629 ((string= type "shell")
9630 (let ((cmd path))
9631 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9632 (string-match org-confirm-shell-link-not-regexp cmd))
9633 (not org-confirm-shell-link-function)
9634 (funcall org-confirm-shell-link-function
9635 (format "Execute \"%s\" in shell? "
9636 (org-add-props cmd nil
9637 'face 'org-warning))))
9638 (progn
9639 (message "Executing %s" cmd)
9640 (shell-command cmd))
9641 (error "Abort"))))
9643 ((string= type "elisp")
9644 (let ((cmd path))
9645 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9646 (string-match org-confirm-elisp-link-not-regexp cmd))
9647 (not org-confirm-elisp-link-function)
9648 (funcall org-confirm-elisp-link-function
9649 (format "Execute \"%s\" as elisp? "
9650 (org-add-props cmd nil
9651 'face 'org-warning))))
9652 (message "%s => %s" cmd
9653 (if (equal (string-to-char cmd) ?\()
9654 (eval (read cmd))
9655 (call-interactively (read cmd))))
9656 (error "Abort"))))
9658 ((and (string= type "thisfile")
9659 (run-hook-with-args-until-success
9660 'org-open-link-functions path)))
9662 ((string= type "thisfile")
9663 (if arg
9664 (switch-to-buffer-other-window
9665 (org-get-buffer-for-internal-link (current-buffer)))
9666 (org-mark-ring-push))
9667 (let ((cmd `(org-link-search
9668 ,path
9669 ,(cond ((equal arg '(4)) ''occur)
9670 ((equal arg '(16)) ''org-occur)
9671 (t nil))
9672 ,pos)))
9673 (condition-case nil (let ((org-link-search-inhibit-query t))
9674 (eval cmd))
9675 (error (progn (widen) (eval cmd))))))
9678 (browse-url-at-point)))))))
9679 (move-marker org-open-link-marker nil)
9680 (run-hook-with-args 'org-follow-link-hook)))
9682 (defun org-offer-links-in-entry (&optional nth zero)
9683 "Offer links in the current entry and follow the selected link.
9684 If there is only one link, follow it immediately as well.
9685 If NTH is an integer, immediately pick the NTH link found.
9686 If ZERO is a string, check also this string for a link, and if
9687 there is one, offer it as link number zero."
9688 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9689 "\\(" org-angle-link-re "\\)\\|"
9690 "\\(" org-plain-link-re "\\)"))
9691 (cnt ?0)
9692 (in-emacs (if (integerp nth) nil nth))
9693 have-zero end links link c)
9694 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9695 (push (match-string 0 zero) links)
9696 (setq cnt (1- cnt) have-zero t))
9697 (save-excursion
9698 (org-back-to-heading t)
9699 (setq end (save-excursion (outline-next-heading) (point)))
9700 (while (re-search-forward re end t)
9701 (push (match-string 0) links))
9702 (setq links (org-uniquify (reverse links))))
9704 (cond
9705 ((null links)
9706 (message "No links"))
9707 ((equal (length links) 1)
9708 (setq link (list (car links))))
9709 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9710 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9711 (t ; we have to select a link
9712 (save-excursion
9713 (save-window-excursion
9714 (delete-other-windows)
9715 (with-output-to-temp-buffer "*Select Link*"
9716 (mapc (lambda (l)
9717 (if (not (string-match org-bracket-link-regexp l))
9718 (princ (format "[%c] %s\n" (incf cnt)
9719 (org-remove-angle-brackets l)))
9720 (if (match-end 3)
9721 (princ (format "[%c] %s (%s)\n" (incf cnt)
9722 (match-string 3 l) (match-string 1 l)))
9723 (princ (format "[%c] %s\n" (incf cnt)
9724 (match-string 1 l))))))
9725 links))
9726 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9727 (message "Select link to open, RET to open all:")
9728 (setq c (read-char-exclusive))
9729 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9730 (when (equal c ?q) (error "Abort"))
9731 (if (equal c ?\C-m)
9732 (setq link links)
9733 (setq nth (- c ?0))
9734 (if have-zero (setq nth (1+ nth)))
9735 (unless (and (integerp nth) (>= (length links) nth))
9736 (error "Invalid link selection"))
9737 (setq link (list (nth (1- nth) links))))))
9738 (if link
9739 (let ((buf (current-buffer)))
9740 (dolist (l link)
9741 (org-open-link-from-string l in-emacs buf))
9743 nil)))
9745 ;; Add special file links that specify the way of opening
9747 (org-add-link-type "file+sys" 'org-open-file-with-system)
9748 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9749 (defun org-open-file-with-system (path)
9750 "Open file at PATH using the system way of opening it."
9751 (org-open-file path 'system))
9752 (defun org-open-file-with-emacs (path)
9753 "Open file at PATH in Emacs."
9754 (org-open-file path 'emacs))
9755 (defun org-remove-file-link-modifiers ()
9756 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9757 (goto-char (point-min))
9758 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9759 (org-if-unprotected
9760 (replace-match "file:" t t))))
9761 (eval-after-load "org-exp"
9762 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9763 'org-remove-file-link-modifiers))
9765 ;;;; Time estimates
9767 (defun org-get-effort (&optional pom)
9768 "Get the effort estimate for the current entry."
9769 (org-entry-get pom org-effort-property))
9771 ;;; File search
9773 (defvar org-create-file-search-functions nil
9774 "List of functions to construct the right search string for a file link.
9775 These functions are called in turn with point at the location to
9776 which the link should point.
9778 A function in the hook should first test if it would like to
9779 handle this file type, for example by checking the `major-mode'
9780 or the file extension. If it decides not to handle this file, it
9781 should just return nil to give other functions a chance. If it
9782 does handle the file, it must return the search string to be used
9783 when following the link. The search string will be part of the
9784 file link, given after a double colon, and `org-open-at-point'
9785 will automatically search for it. If special measures must be
9786 taken to make the search successful, another function should be
9787 added to the companion hook `org-execute-file-search-functions',
9788 which see.
9790 A function in this hook may also use `setq' to set the variable
9791 `description' to provide a suggestion for the descriptive text to
9792 be used for this link when it gets inserted into an Org-mode
9793 buffer with \\[org-insert-link].")
9795 (defvar org-execute-file-search-functions nil
9796 "List of functions to execute a file search triggered by a link.
9798 Functions added to this hook must accept a single argument, the
9799 search string that was part of the file link, the part after the
9800 double colon. The function must first check if it would like to
9801 handle this search, for example by checking the `major-mode' or
9802 the file extension. If it decides not to handle this search, it
9803 should just return nil to give other functions a chance. If it
9804 does handle the search, it must return a non-nil value to keep
9805 other functions from trying.
9807 Each function can access the current prefix argument through the
9808 variable `current-prefix-argument'. Note that a single prefix is
9809 used to force opening a link in Emacs, so it may be good to only
9810 use a numeric or double prefix to guide the search function.
9812 In case this is needed, a function in this hook can also restore
9813 the window configuration before `org-open-at-point' was called using:
9815 (set-window-configuration org-window-config-before-follow-link)")
9817 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9818 (defun org-link-search (s &optional type avoid-pos stealth)
9819 "Search for a link search option.
9820 If S is surrounded by forward slashes, it is interpreted as a
9821 regular expression. In org-mode files, this will create an `org-occur'
9822 sparse tree. In ordinary files, `occur' will be used to list matches.
9823 If the current buffer is in `dired-mode', grep will be used to search
9824 in all files. If AVOID-POS is given, ignore matches near that position.
9826 When optional argument STEALTH is non-nil, do not modify
9827 visibility around point, thus ignoring
9828 `org-show-hierarchy-above', `org-show-following-heading' and
9829 `org-show-siblings' variables."
9830 (let ((case-fold-search t)
9831 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9832 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9833 (append '(("") (" ") ("\t") ("\n"))
9834 org-emphasis-alist)
9835 "\\|") "\\)"))
9836 (pos (point))
9837 (pre nil) (post nil)
9838 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9839 (cond
9840 ;; First check if there are any special search functions
9841 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9842 ;; Now try the builtin stuff
9843 ((and (equal (string-to-char s0) ?#)
9844 (> (length s0) 1)
9845 (save-excursion
9846 (goto-char (point-min))
9847 (and
9848 (re-search-forward
9849 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9850 (setq type 'dedicated
9851 pos (match-beginning 0))))
9852 ;; There is an exact target for this
9853 (goto-char pos)
9854 (org-back-to-heading t)))
9855 ((save-excursion
9856 (goto-char (point-min))
9857 (and
9858 (re-search-forward
9859 (concat "<<" (regexp-quote s0) ">>") nil t)
9860 (setq type 'dedicated
9861 pos (match-beginning 0))))
9862 ;; There is an exact target for this
9863 (goto-char pos))
9864 ((and (string-match "^(\\(.*\\))$" s0)
9865 (save-excursion
9866 (goto-char (point-min))
9867 (and
9868 (re-search-forward
9869 (concat "[^[]" (regexp-quote
9870 (format org-coderef-label-format
9871 (match-string 1 s0))))
9872 nil t)
9873 (setq type 'dedicated
9874 pos (1+ (match-beginning 0))))))
9875 ;; There is a coderef target for this
9876 (goto-char pos))
9877 ((string-match "^/\\(.*\\)/$" s)
9878 ;; A regular expression
9879 (cond
9880 ((eq major-mode 'org-mode)
9881 (org-occur (match-string 1 s)))
9882 ;;((eq major-mode 'dired-mode)
9883 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9884 (t (org-do-occur (match-string 1 s)))))
9885 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9886 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9887 (goto-char (point-min))
9888 (cond
9889 ((let (case-fold-search)
9890 (re-search-forward (format org-complex-heading-regexp-format
9891 (regexp-quote s))
9892 nil t))
9893 ;; OK, found a match
9894 (setq type 'dedicated)
9895 (goto-char (match-beginning 0)))
9896 ((and (not org-link-search-inhibit-query)
9897 (eq org-link-search-must-match-exact-headline 'query-to-create)
9898 (y-or-n-p "No match - create this as a new heading? "))
9899 (goto-char (point-max))
9900 (or (bolp) (newline))
9901 (insert "* " s "\n")
9902 (beginning-of-line 0))
9904 (goto-char pos)
9905 (error "No match"))))
9907 ;; A normal search string
9908 (when (equal (string-to-char s) ?*)
9909 ;; Anchor on headlines, post may include tags.
9910 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9911 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9912 s (substring s 1)))
9913 (remove-text-properties
9914 0 (length s)
9915 '(face nil mouse-face nil keymap nil fontified nil) s)
9916 ;; Make a series of regular expressions to find a match
9917 (setq words (org-split-string s "[ \n\r\t]+")
9919 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9920 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9921 "\\)" markers)
9922 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9923 re2a (concat "[ \t\r\n]" re2a_)
9924 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9925 re4 (concat "[^a-zA-Z_]" re4_)
9927 re1 (concat pre re2 post)
9928 re3 (concat pre (if pre re4_ re4) post)
9929 re5 (concat pre ".*" re4)
9930 re2 (concat pre re2)
9931 re2a (concat pre (if pre re2a_ re2a))
9932 re4 (concat pre (if pre re4_ re4))
9933 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9934 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9935 re5 "\\)"
9937 (cond
9938 ((eq type 'org-occur) (org-occur reall))
9939 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9940 (t (goto-char (point-min))
9941 (setq type 'fuzzy)
9942 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9943 (org-search-not-self 1 re1 nil t)
9944 (org-search-not-self 1 re2 nil t)
9945 (org-search-not-self 1 re2a nil t)
9946 (org-search-not-self 1 re3 nil t)
9947 (org-search-not-self 1 re4 nil t)
9948 (org-search-not-self 1 re5 nil t)
9950 (goto-char (match-beginning 1))
9951 (goto-char pos)
9952 (error "No match"))))))
9953 (and (eq major-mode 'org-mode)
9954 (not stealth)
9955 (org-show-context 'link-search))
9956 type))
9958 (defun org-search-not-self (group &rest args)
9959 "Execute `re-search-forward', but only accept matches that do not
9960 enclose the position of `org-open-link-marker'."
9961 (let ((m org-open-link-marker))
9962 (catch 'exit
9963 (while (apply 're-search-forward args)
9964 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9965 (goto-char (match-end group))
9966 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9967 (> (match-beginning 0) (marker-position m))
9968 (< (match-end 0) (marker-position m)))
9969 (save-match-data
9970 (or (not (org-in-regexp
9971 org-bracket-link-analytic-regexp 1))
9972 (not (match-end 4)) ; no description
9973 (and (<= (match-beginning 4) (point))
9974 (>= (match-end 4) (point))))))
9975 (throw 'exit (point))))))))
9977 (defun org-get-buffer-for-internal-link (buffer)
9978 "Return a buffer to be used for displaying the link target of internal links."
9979 (cond
9980 ((not org-display-internal-link-with-indirect-buffer)
9981 buffer)
9982 ((string-match "(Clone)$" (buffer-name buffer))
9983 (message "Buffer is already a clone, not making another one")
9984 ;; we also do not modify visibility in this case
9985 buffer)
9986 (t ; make a new indirect buffer for displaying the link
9987 (let* ((bn (buffer-name buffer))
9988 (ibn (concat bn "(Clone)"))
9989 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9990 (with-current-buffer ib (org-overview))
9991 ib))))
9993 (defun org-do-occur (regexp &optional cleanup)
9994 "Call the Emacs command `occur'.
9995 If CLEANUP is non-nil, remove the printout of the regular expression
9996 in the *Occur* buffer. This is useful if the regex is long and not useful
9997 to read."
9998 (occur regexp)
9999 (when cleanup
10000 (let ((cwin (selected-window)) win beg end)
10001 (when (setq win (get-buffer-window "*Occur*"))
10002 (select-window win))
10003 (goto-char (point-min))
10004 (when (re-search-forward "match[a-z]+" nil t)
10005 (setq beg (match-end 0))
10006 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10007 (setq end (1- (match-beginning 0)))))
10008 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10009 (goto-char (point-min))
10010 (select-window cwin))))
10012 ;;; The mark ring for links jumps
10014 (defvar org-mark-ring nil
10015 "Mark ring for positions before jumps in Org-mode.")
10016 (defvar org-mark-ring-last-goto nil
10017 "Last position in the mark ring used to go back.")
10018 ;; Fill and close the ring
10019 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10020 (loop for i from 1 to org-mark-ring-length do
10021 (push (make-marker) org-mark-ring))
10022 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10023 org-mark-ring)
10025 (defun org-mark-ring-push (&optional pos buffer)
10026 "Put the current position or POS into the mark ring and rotate it."
10027 (interactive)
10028 (setq pos (or pos (point)))
10029 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10030 (move-marker (car org-mark-ring)
10031 (or pos (point))
10032 (or buffer (current-buffer)))
10033 (message "%s"
10034 (substitute-command-keys
10035 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10037 (defun org-mark-ring-goto (&optional n)
10038 "Jump to the previous position in the mark ring.
10039 With prefix arg N, jump back that many stored positions. When
10040 called several times in succession, walk through the entire ring.
10041 Org-mode commands jumping to a different position in the current file,
10042 or to another Org-mode file, automatically push the old position
10043 onto the ring."
10044 (interactive "p")
10045 (let (p m)
10046 (if (eq last-command this-command)
10047 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10048 (setq p org-mark-ring))
10049 (setq org-mark-ring-last-goto p)
10050 (setq m (car p))
10051 (org-pop-to-buffer-same-window (marker-buffer m))
10052 (goto-char m)
10053 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10055 (defun org-remove-angle-brackets (s)
10056 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10057 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10059 (defun org-add-angle-brackets (s)
10060 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10061 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10063 (defun org-remove-double-quotes (s)
10064 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10065 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10068 ;;; Following specific links
10070 (defun org-follow-timestamp-link ()
10071 (cond
10072 ((org-at-date-range-p t)
10073 (let ((org-agenda-start-on-weekday)
10074 (t1 (match-string 1))
10075 (t2 (match-string 2)))
10076 (setq t1 (time-to-days (org-time-string-to-time t1))
10077 t2 (time-to-days (org-time-string-to-time t2)))
10078 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10079 ((org-at-timestamp-p t)
10080 (org-agenda-list nil (time-to-days (org-time-string-to-time
10081 (substring (match-string 1) 0 10)))
10083 (t (error "This should not happen"))))
10086 ;;; Following file links
10087 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10088 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10089 (declare-function mailcap-mime-info
10090 "mailcap" (string &optional request no-decode))
10091 (defvar org-wait nil)
10092 (defun org-open-file (path &optional in-emacs line search)
10093 "Open the file at PATH.
10094 First, this expands any special file name abbreviations. Then the
10095 configuration variable `org-file-apps' is checked if it contains an
10096 entry for this file type, and if yes, the corresponding command is launched.
10098 If no application is found, Emacs simply visits the file.
10100 With optional prefix argument IN-EMACS, Emacs will visit the file.
10101 With a double \\[universal-argument] \\[universal-argument] \
10102 prefix arg, Org tries to avoid opening in Emacs
10103 and to use an external application to visit the file.
10105 Optional LINE specifies a line to go to, optional SEARCH a string
10106 to search for. If LINE or SEARCH is given, the file will be
10107 opened in Emacs, unless an entry from org-file-apps that makes
10108 use of groups in a regexp matches.
10110 If you want to change the way frames are used when following a
10111 link, please customize `org-link-frame-setup'.
10113 If the file does not exist, an error is thrown."
10114 (let* ((file (if (equal path "")
10115 buffer-file-name
10116 (substitute-in-file-name (expand-file-name path))))
10117 (file-apps (append org-file-apps (org-default-apps)))
10118 (apps (org-remove-if
10119 'org-file-apps-entry-match-against-dlink-p file-apps))
10120 (apps-dlink (org-remove-if-not
10121 'org-file-apps-entry-match-against-dlink-p file-apps))
10122 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10123 (dirp (if remp nil (file-directory-p file)))
10124 (file (if (and dirp org-open-directory-means-index-dot-org)
10125 (concat (file-name-as-directory file) "index.org")
10126 file))
10127 (a-m-a-p (assq 'auto-mode apps))
10128 (dfile (downcase file))
10129 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10130 (link (cond ((and (eq line nil)
10131 (eq search nil))
10132 file)
10133 (line
10134 (concat file "::" (number-to-string line)))
10135 (search
10136 (concat file "::" search))))
10137 (dlink (downcase link))
10138 (old-buffer (current-buffer))
10139 (old-pos (point))
10140 (old-mode major-mode)
10141 ext cmd link-match-data)
10142 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10143 (setq ext (match-string 1 dfile))
10144 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10145 (setq ext (match-string 1 dfile))))
10146 (cond
10147 ((member in-emacs '((16) system))
10148 (setq cmd (cdr (assoc 'system apps))))
10149 (in-emacs (setq cmd 'emacs))
10151 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10152 (and dirp (cdr (assoc 'directory apps)))
10153 ; first, try matching against apps-dlink
10154 ; if we get a match here, store the match data for later
10155 (let ((match (assoc-default dlink apps-dlink
10156 'string-match)))
10157 (if match
10158 (progn (setq link-match-data (match-data))
10159 match)
10160 (progn (setq in-emacs (or in-emacs line search))
10161 nil))) ; if we have no match in apps-dlink,
10162 ; always open the file in emacs if line or search
10163 ; is given (for backwards compatibility)
10164 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10165 'string-match)
10166 (cdr (assoc ext apps))
10167 (cdr (assoc t apps))))))
10168 (when (eq cmd 'system)
10169 (setq cmd (cdr (assoc 'system apps))))
10170 (when (eq cmd 'default)
10171 (setq cmd (cdr (assoc t apps))))
10172 (when (eq cmd 'mailcap)
10173 (require 'mailcap)
10174 (mailcap-parse-mailcaps)
10175 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10176 (command (mailcap-mime-info mime-type)))
10177 (if (stringp command)
10178 (setq cmd command)
10179 (setq cmd 'emacs))))
10180 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10181 (not (file-exists-p file))
10182 (not org-open-non-existing-files))
10183 (error "No such file: %s" file))
10184 (cond
10185 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10186 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10187 (while (string-match "['\"]%s['\"]" cmd)
10188 (setq cmd (replace-match "%s" t t cmd)))
10189 (while (string-match "%s" cmd)
10190 (setq cmd (replace-match
10191 (save-match-data
10192 (shell-quote-argument
10193 (convert-standard-filename file)))
10194 t t cmd)))
10196 ;; Replace "%1", "%2" etc. in command with group matches from regex
10197 (save-match-data
10198 (let ((match-index 1)
10199 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10200 (set-match-data link-match-data)
10201 (while (<= match-index number-of-groups)
10202 (let ((regex (concat "%" (number-to-string match-index)))
10203 (replace-with (match-string match-index dlink)))
10204 (while (string-match regex cmd)
10205 (setq cmd (replace-match replace-with t t cmd))))
10206 (setq match-index (+ match-index 1)))))
10208 (save-window-excursion
10209 (start-process-shell-command cmd nil cmd)
10210 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10212 ((or (stringp cmd)
10213 (eq cmd 'emacs))
10214 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10215 (widen)
10216 (if line (org-goto-line line)
10217 (if search (org-link-search search))))
10218 ((consp cmd)
10219 (let ((file (convert-standard-filename file)))
10220 (save-match-data
10221 (set-match-data link-match-data)
10222 (eval cmd))))
10223 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10224 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10225 (or (not (equal old-buffer (current-buffer)))
10226 (not (equal old-pos (point))))
10227 (org-mark-ring-push old-pos old-buffer))))
10229 (defun org-file-apps-entry-match-against-dlink-p (entry)
10230 "This function returns non-nil if `entry' uses a regular
10231 expression which should be matched against the whole link by
10232 org-open-file.
10234 It assumes that is the case when the entry uses a regular
10235 expression which has at least one grouping construct and the
10236 action is either a lisp form or a command string containing
10237 '%1', i.e. using at least one subexpression match as a
10238 parameter."
10239 (let ((selector (car entry))
10240 (action (cdr entry)))
10241 (if (stringp selector)
10242 (and (> (regexp-opt-depth selector) 0)
10243 (or (and (stringp action)
10244 (string-match "%[0-9]" action))
10245 (consp action)))
10246 nil)))
10248 (defun org-default-apps ()
10249 "Return the default applications for this operating system."
10250 (cond
10251 ((eq system-type 'darwin)
10252 org-file-apps-defaults-macosx)
10253 ((eq system-type 'windows-nt)
10254 org-file-apps-defaults-windowsnt)
10255 (t org-file-apps-defaults-gnu)))
10257 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10258 "Convert extensions to regular expressions in the cars of LIST.
10259 Also, weed out any non-string entries, because the return value is used
10260 only for regexp matching.
10261 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10262 point to the symbol `emacs', indicating that the file should
10263 be opened in Emacs."
10264 (append
10265 (delq nil
10266 (mapcar (lambda (x)
10267 (if (not (stringp (car x)))
10269 (if (string-match "\\W" (car x))
10271 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10272 list))
10273 (if add-auto-mode
10274 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10276 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10277 (defun org-file-remote-p (file)
10278 "Test whether FILE specifies a location on a remote system.
10279 Return non-nil if the location is indeed remote.
10281 For example, the filename \"/user@host:/foo\" specifies a location
10282 on the system \"/user@host:\"."
10283 (cond ((fboundp 'file-remote-p)
10284 (file-remote-p file))
10285 ((fboundp 'tramp-handle-file-remote-p)
10286 (tramp-handle-file-remote-p file))
10287 ((and (boundp 'ange-ftp-name-format)
10288 (string-match (car ange-ftp-name-format) file))
10290 (t nil)))
10293 ;;;; Refiling
10295 (defun org-get-org-file ()
10296 "Read a filename, with default directory `org-directory'."
10297 (let ((default (or org-default-notes-file remember-data-file)))
10298 (read-file-name (format "File name [%s]: " default)
10299 (file-name-as-directory org-directory)
10300 default)))
10302 (defun org-notes-order-reversed-p ()
10303 "Check if the current file should receive notes in reversed order."
10304 (cond
10305 ((not org-reverse-note-order) nil)
10306 ((eq t org-reverse-note-order) t)
10307 ((not (listp org-reverse-note-order)) nil)
10308 (t (catch 'exit
10309 (let ((all org-reverse-note-order)
10310 entry)
10311 (while (setq entry (pop all))
10312 (if (string-match (car entry) buffer-file-name)
10313 (throw 'exit (cdr entry))))
10314 nil)))))
10316 (defvar org-refile-target-table nil
10317 "The list of refile targets, created by `org-refile'.")
10319 (defvar org-agenda-new-buffers nil
10320 "Buffers created to visit agenda files.")
10322 (defvar org-refile-cache nil
10323 "Cache for refile targets.")
10325 (defvar org-refile-markers nil
10326 "All the markers used for caching refile locations.")
10328 (defun org-refile-marker (pos)
10329 "Get a new refile marker, but only if caching is in use."
10330 (if (not org-refile-use-cache)
10332 (let ((m (make-marker)))
10333 (move-marker m pos)
10334 (push m org-refile-markers)
10335 m)))
10337 (defun org-refile-cache-clear ()
10338 "Clear the refile cache and disable all the markers."
10339 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10340 (setq org-refile-markers nil)
10341 (setq org-refile-cache nil)
10342 (message "Refile cache has been cleared"))
10344 (defun org-refile-cache-check-set (set)
10345 "Check if all the markers in the cache still have live buffers."
10346 (let (marker)
10347 (catch 'exit
10348 (while (and set (setq marker (nth 3 (pop set))))
10349 ;; if org-refile-use-outline-path is 'file, marker may be nil
10350 (when (and marker (null (marker-buffer marker)))
10351 (message "not found") (sit-for 3)
10352 (throw 'exit nil)))
10353 t)))
10355 (defun org-refile-cache-put (set &rest identifiers)
10356 "Push the refile targets SET into the cache, under IDENTIFIERS."
10357 (let* ((key (sha1 (prin1-to-string identifiers)))
10358 (entry (assoc key org-refile-cache)))
10359 (if entry
10360 (setcdr entry set)
10361 (push (cons key set) org-refile-cache))))
10363 (defun org-refile-cache-get (&rest identifiers)
10364 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10365 (cond
10366 ((not org-refile-cache) nil)
10367 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10369 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10370 org-refile-cache))))
10371 (and set (org-refile-cache-check-set set) set)))))
10373 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10374 "Produce a table with refile targets."
10375 (let ((case-fold-search nil)
10376 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10377 (entries (or org-refile-targets '((nil . (:level . 1)))))
10378 targets tgs txt re files f desc descre fast-path-p level pos0)
10379 (message "Getting targets...")
10380 (with-current-buffer (or default-buffer (current-buffer))
10381 (while (setq entry (pop entries))
10382 (setq files (car entry) desc (cdr entry))
10383 (setq fast-path-p nil)
10384 (cond
10385 ((null files) (setq files (list (current-buffer))))
10386 ((eq files 'org-agenda-files)
10387 (setq files (org-agenda-files 'unrestricted)))
10388 ((and (symbolp files) (fboundp files))
10389 (setq files (funcall files)))
10390 ((and (symbolp files) (boundp files))
10391 (setq files (symbol-value files))))
10392 (if (stringp files) (setq files (list files)))
10393 (cond
10394 ((eq (car desc) :tag)
10395 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10396 ((eq (car desc) :todo)
10397 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10398 ((eq (car desc) :regexp)
10399 (setq descre (cdr desc)))
10400 ((eq (car desc) :level)
10401 (setq descre (concat "^\\*\\{" (number-to-string
10402 (if org-odd-levels-only
10403 (1- (* 2 (cdr desc)))
10404 (cdr desc)))
10405 "\\}[ \t]")))
10406 ((eq (car desc) :maxlevel)
10407 (setq fast-path-p t)
10408 (setq descre (concat "^\\*\\{1," (number-to-string
10409 (if org-odd-levels-only
10410 (1- (* 2 (cdr desc)))
10411 (cdr desc)))
10412 "\\}[ \t]")))
10413 (t (error "Bad refiling target description %s" desc)))
10414 (while (setq f (pop files))
10415 (with-current-buffer
10416 (if (bufferp f) f (org-get-agenda-file-buffer f))
10418 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10419 (progn
10420 (if (bufferp f) (setq f (buffer-file-name
10421 (buffer-base-buffer f))))
10422 (setq f (and f (expand-file-name f)))
10423 (if (eq org-refile-use-outline-path 'file)
10424 (push (list (file-name-nondirectory f) f nil nil) tgs))
10425 (save-excursion
10426 (save-restriction
10427 (widen)
10428 (goto-char (point-min))
10429 (while (re-search-forward descre nil t)
10430 (goto-char (setq pos0 (point-at-bol)))
10431 (catch 'next
10432 (when org-refile-target-verify-function
10433 (save-match-data
10434 (or (funcall org-refile-target-verify-function)
10435 (throw 'next t))))
10436 (when (and (looking-at org-complex-heading-regexp)
10437 (not (member (match-string 4) excluded-entries))
10438 (match-string 4))
10439 (setq level (org-reduced-level
10440 (- (match-end 1) (match-beginning 1)))
10441 txt (org-link-display-format (match-string 4))
10442 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10443 re (format org-complex-heading-regexp-format
10444 (regexp-quote (match-string 4))))
10445 (when org-refile-use-outline-path
10446 (setq txt (mapconcat
10447 'org-protect-slash
10448 (append
10449 (if (eq org-refile-use-outline-path
10450 'file)
10451 (list (file-name-nondirectory
10452 (buffer-file-name
10453 (buffer-base-buffer))))
10454 (if (eq org-refile-use-outline-path
10455 'full-file-path)
10456 (list (buffer-file-name
10457 (buffer-base-buffer)))))
10458 (org-get-outline-path fast-path-p
10459 level txt)
10460 (list txt))
10461 "/")))
10462 (push (list txt f re (org-refile-marker (point)))
10463 tgs)))
10464 (when (= (point) pos0)
10465 ;; verification function has not moved point
10466 (goto-char (point-at-eol))))))))
10467 (when org-refile-use-cache
10468 (org-refile-cache-put tgs (buffer-file-name) descre))
10469 (setq targets (append tgs targets))
10470 ))))
10471 (message "Getting targets...done")
10472 (nreverse targets)))
10474 (defun org-protect-slash (s)
10475 (while (string-match "/" s)
10476 (setq s (replace-match "\\" t t s)))
10479 (defvar org-olpa (make-vector 20 nil))
10481 (defun org-get-outline-path (&optional fastp level heading)
10482 "Return the outline path to the current entry, as a list.
10484 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10485 routine which makes outline path derivations for an entire file,
10486 avoiding backtracing. Refile target collection makes use of that."
10487 (if fastp
10488 (progn
10489 (if (> level 19)
10490 (error "Outline path failure, more than 19 levels"))
10491 (loop for i from level upto 19 do
10492 (aset org-olpa i nil))
10493 (prog1
10494 (delq nil (append org-olpa nil))
10495 (aset org-olpa level heading)))
10496 (let (rtn case-fold-search)
10497 (save-excursion
10498 (save-restriction
10499 (widen)
10500 (while (org-up-heading-safe)
10501 (when (looking-at org-complex-heading-regexp)
10502 (push (org-match-string-no-properties 4) rtn)))
10503 rtn)))))
10505 (defun org-format-outline-path (path &optional width prefix)
10506 "Format the outline path PATH for display.
10507 Width is the maximum number of characters that is available.
10508 Prefix is a prefix to be included in the returned string,
10509 such as the file name."
10510 (setq width (or width 79))
10511 (if prefix (setq width (- width (length prefix))))
10512 (if (not path)
10513 (or prefix "")
10514 (let* ((nsteps (length path))
10515 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10516 (maxwidth (if (<= total-width width)
10517 10000 ;; everything fits
10518 ;; we need to shorten the level headings
10519 (/ (- width nsteps) nsteps)))
10520 (org-odd-levels-only nil)
10521 (n 0)
10522 (total (1+ (length prefix))))
10523 (setq maxwidth (max maxwidth 10))
10524 (concat prefix
10525 (mapconcat
10526 (lambda (h)
10527 (setq n (1+ n))
10528 (if (and (= n nsteps) (< maxwidth 10000))
10529 (setq maxwidth (- total-width total)))
10530 (if (< (length h) maxwidth)
10531 (progn (setq total (+ total (length h) 1)) h)
10532 (setq h (substring h 0 (- maxwidth 2))
10533 total (+ total maxwidth 1))
10534 (if (string-match "[ \t]+\\'" h)
10535 (setq h (substring h 0 (match-beginning 0))))
10536 (setq h (concat h "..")))
10537 (org-add-props h nil 'face
10538 (nth (% (1- n) org-n-level-faces)
10539 org-level-faces))
10541 path "/")))))
10543 (defun org-display-outline-path (&optional file current)
10544 "Display the current outline path in the echo area."
10545 (interactive "P")
10546 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10547 (case-fold-search nil)
10548 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10549 (if current (setq path (append path
10550 (save-excursion
10551 (org-back-to-heading t)
10552 (if (looking-at org-complex-heading-regexp)
10553 (list (match-string 4)))))))
10554 (message "%s"
10555 (org-format-outline-path
10556 path
10557 (1- (frame-width))
10558 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10560 (defvar org-refile-history nil
10561 "History for refiling operations.")
10563 (defvar org-after-refile-insert-hook nil
10564 "Hook run after `org-refile' has inserted its stuff at the new location.
10565 Note that this is still *before* the stuff will be removed from
10566 the *old* location.")
10568 (defvar org-capture-last-stored-marker)
10569 (defun org-refile (&optional goto default-buffer rfloc)
10570 "Move the entry or entries at point to another heading.
10571 The list of target headings is compiled using the information in
10572 `org-refile-targets', which see.
10574 At the target location, the entry is filed as a subitem of the target
10575 heading. Depending on `org-reverse-note-order', the new subitem will
10576 either be the first or the last subitem.
10578 If there is an active region, all entries in that region will be moved.
10579 However, the region must fulfill the requirement that the first heading
10580 is the first one sets the top-level of the moved text - at most siblings
10581 below it are allowed.
10583 With prefix arg GOTO, the command will only visit the target location
10584 and not actually move anything.
10586 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10587 go to the location where the last refiling operation has put the subtree.
10588 With a prefix argument of `2', refile to the running clock.
10590 RFLOC can be a refile location obtained in a different way.
10592 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10594 If you are using target caching (see `org-refile-use-cache'),
10595 You have to clear the target cache in order to find new targets.
10596 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10597 prefix argument (`C-u C-u C-u C-c C-w')."
10599 (interactive "P")
10600 (if (member goto '(0 (64)))
10601 (org-refile-cache-clear)
10602 (let* ((cbuf (current-buffer))
10603 (regionp (org-region-active-p))
10604 (region-start (and regionp (region-beginning)))
10605 (region-end (and regionp (region-end)))
10606 (region-length (and regionp (- region-end region-start)))
10607 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10608 pos it nbuf file re level reversed)
10609 (setq last-command nil)
10610 (when regionp
10611 (goto-char region-start)
10612 (or (bolp) (goto-char (point-at-bol)))
10613 (setq region-start (point))
10614 (unless (or (org-kill-is-subtree-p
10615 (buffer-substring region-start region-end))
10616 (prog1 org-refile-active-region-within-subtree
10617 (org-toggle-heading)))
10618 (error "The region is not a (sequence of) subtree(s)")))
10619 (if (equal goto '(16))
10620 (org-refile-goto-last-stored)
10621 (when (or
10622 (and (equal goto 2)
10623 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10624 (prog1
10625 (setq it (list (or org-clock-heading "running clock")
10626 (buffer-file-name
10627 (marker-buffer org-clock-hd-marker))
10629 (marker-position org-clock-hd-marker)))
10630 (setq goto nil)))
10631 (setq it (or rfloc
10632 (let (heading-text)
10633 (save-excursion
10634 (unless goto
10635 (org-back-to-heading t)
10636 (setq heading-text
10637 (nth 4 (org-heading-components))))
10638 (org-refile-get-location
10639 (cond (goto "Goto")
10640 (regionp "Refile region to")
10641 (t (concat "Refile subtree \""
10642 heading-text "\" to")))
10643 default-buffer
10644 org-refile-allow-creating-parent-nodes
10645 goto))))))
10646 (setq file (nth 1 it)
10647 re (nth 2 it)
10648 pos (nth 3 it))
10649 (if (and (not goto)
10651 (equal (buffer-file-name) file)
10652 (if regionp
10653 (and (>= pos region-start)
10654 (<= pos region-end))
10655 (and (>= pos (point))
10656 (< pos (save-excursion
10657 (org-end-of-subtree t t))))))
10658 (error "Cannot refile to position inside the tree or region"))
10660 (setq nbuf (or (find-buffer-visiting file)
10661 (find-file-noselect file)))
10662 (if goto
10663 (progn
10664 (org-pop-to-buffer-same-window nbuf)
10665 (goto-char pos)
10666 (org-show-context 'org-goto))
10667 (if regionp
10668 (progn
10669 (org-kill-new (buffer-substring region-start region-end))
10670 (org-save-markers-in-region region-start region-end))
10671 (org-copy-subtree 1 nil t))
10672 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10673 (find-file-noselect file)))
10674 (setq reversed (org-notes-order-reversed-p))
10675 (save-excursion
10676 (save-restriction
10677 (widen)
10678 (if pos
10679 (progn
10680 (goto-char pos)
10681 (looking-at org-outline-regexp)
10682 (setq level (org-get-valid-level (funcall outline-level) 1))
10683 (goto-char
10684 (if reversed
10685 (or (outline-next-heading) (point-max))
10686 (or (save-excursion (org-get-next-sibling))
10687 (org-end-of-subtree t t)
10688 (point-max)))))
10689 (setq level 1)
10690 (if (not reversed)
10691 (goto-char (point-max))
10692 (goto-char (point-min))
10693 (or (outline-next-heading) (goto-char (point-max)))))
10694 (if (not (bolp)) (newline))
10695 (org-paste-subtree level)
10696 (when org-log-refile
10697 (org-add-log-setup 'refile nil nil 'findpos
10698 org-log-refile)
10699 (unless (eq org-log-refile 'note)
10700 (save-excursion (org-add-log-note))))
10701 (and org-auto-align-tags (org-set-tags nil t))
10702 (bookmark-set "org-refile-last-stored")
10703 ;; If we are refiling for capture, make sure that the
10704 ;; last-capture pointers point here
10705 (when (org-bound-and-true-p org-refile-for-capture)
10706 (bookmark-set "org-capture-last-stored-marker")
10707 (move-marker org-capture-last-stored-marker (point)))
10708 (if (fboundp 'deactivate-mark) (deactivate-mark))
10709 (run-hooks 'org-after-refile-insert-hook))))
10710 (if regionp
10711 (delete-region (point) (+ (point) region-length))
10712 (org-cut-subtree))
10713 (when (featurep 'org-inlinetask)
10714 (org-inlinetask-remove-END-maybe))
10715 (setq org-markers-to-move nil)
10716 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10718 (defun org-refile-goto-last-stored ()
10719 "Go to the location where the last refile was stored."
10720 (interactive)
10721 (bookmark-jump "org-refile-last-stored")
10722 (message "This is the location of the last refile"))
10724 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10725 no-exclude)
10726 "Prompt the user for a refile location, using PROMPT.
10727 PROMPT should not be suffixed with a colon and a space, because
10728 this function appends the default value from
10729 `org-refile-history' automatically, if that is not empty.
10730 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10731 this is used for the GOTO interface."
10732 (let ((org-refile-targets org-refile-targets)
10733 (org-refile-use-outline-path org-refile-use-outline-path)
10734 excluded-entries)
10735 (when (and (eq major-mode 'org-mode)
10736 (not org-refile-use-cache)
10737 (not no-exclude))
10738 (org-map-tree
10739 (lambda()
10740 (setq excluded-entries
10741 (append excluded-entries (list (org-get-heading t t)))))))
10742 (setq org-refile-target-table
10743 (org-refile-get-targets default-buffer excluded-entries)))
10744 (unless org-refile-target-table
10745 (error "No refile targets"))
10746 (let* ((prompt (concat prompt
10747 (and (car org-refile-history)
10748 (concat " (default " (car org-refile-history) ")"))
10749 ": "))
10750 (cbuf (current-buffer))
10751 (partial-completion-mode nil)
10752 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10753 (cfunc (if (and org-refile-use-outline-path
10754 org-outline-path-complete-in-steps)
10755 'org-olpath-completing-read
10756 'org-icompleting-read))
10757 (extra (if org-refile-use-outline-path "/" ""))
10758 (filename (and cfn (expand-file-name cfn)))
10759 (tbl (mapcar
10760 (lambda (x)
10761 (if (and (not (member org-refile-use-outline-path
10762 '(file full-file-path)))
10763 (not (equal filename (nth 1 x))))
10764 (cons (concat (car x) extra " ("
10765 (file-name-nondirectory (nth 1 x)) ")")
10766 (cdr x))
10767 (cons (concat (car x) extra) (cdr x))))
10768 org-refile-target-table))
10769 (completion-ignore-case t)
10770 pa answ parent-target child parent old-hist)
10771 (setq old-hist org-refile-history)
10772 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10773 nil 'org-refile-history (car org-refile-history)))
10774 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10775 (org-refile-check-position pa)
10776 (if pa
10777 (progn
10778 (when (or (not org-refile-history)
10779 (not (eq old-hist org-refile-history))
10780 (not (equal (car pa) (car org-refile-history))))
10781 (setq org-refile-history
10782 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10783 org-refile-history
10784 (cdr org-refile-history))))
10785 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10786 (pop org-refile-history)))
10788 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10789 (progn
10790 (setq parent (match-string 1 answ)
10791 child (match-string 2 answ))
10792 (setq parent-target (or (assoc parent tbl)
10793 (assoc (concat parent "/") tbl)))
10794 (when (and parent-target
10795 (or (eq new-nodes t)
10796 (and (eq new-nodes 'confirm)
10797 (y-or-n-p (format "Create new node \"%s\"? "
10798 child)))))
10799 (org-refile-new-child parent-target child)))
10800 (error "Invalid target location")))))
10802 (defun org-refile-check-position (refile-pointer)
10803 "Check if the refile pointer matches the readline to which it points."
10804 (let* ((file (nth 1 refile-pointer))
10805 (re (nth 2 refile-pointer))
10806 (pos (nth 3 refile-pointer))
10807 buffer)
10808 (when (org-string-nw-p re)
10809 (setq buffer (if (markerp pos)
10810 (marker-buffer pos)
10811 (or (find-buffer-visiting file)
10812 (find-file-noselect file))))
10813 (with-current-buffer buffer
10814 (save-excursion
10815 (save-restriction
10816 (widen)
10817 (goto-char pos)
10818 (beginning-of-line 1)
10819 (unless (org-looking-at-p re)
10820 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10822 (defun org-refile-new-child (parent-target child)
10823 "Use refile target PARENT-TARGET to add new CHILD below it."
10824 (unless parent-target
10825 (error "Cannot find parent for new node"))
10826 (let ((file (nth 1 parent-target))
10827 (pos (nth 3 parent-target))
10828 level)
10829 (with-current-buffer (or (find-buffer-visiting file)
10830 (find-file-noselect file))
10831 (save-excursion
10832 (save-restriction
10833 (widen)
10834 (if pos
10835 (goto-char pos)
10836 (goto-char (point-max))
10837 (if (not (bolp)) (newline)))
10838 (when (looking-at org-outline-regexp)
10839 (setq level (funcall outline-level))
10840 (org-end-of-subtree t t))
10841 (org-back-over-empty-lines)
10842 (insert "\n" (make-string
10843 (if pos (org-get-valid-level level 1) 1) ?*)
10844 " " child "\n")
10845 (beginning-of-line 0)
10846 (list (concat (car parent-target) "/" child) file "" (point)))))))
10848 (defun org-olpath-completing-read (prompt collection &rest args)
10849 "Read an outline path like a file name."
10850 (let ((thetable collection)
10851 (org-completion-use-ido nil) ; does not work with ido.
10852 (org-completion-use-iswitchb nil)) ; or iswitchb
10853 (apply
10854 'org-icompleting-read prompt
10855 (lambda (string predicate &optional flag)
10856 (let (rtn r f (l (length string)))
10857 (cond
10858 ((eq flag nil)
10859 ;; try completion
10860 (try-completion string thetable))
10861 ((eq flag t)
10862 ;; all-completions
10863 (setq rtn (all-completions string thetable predicate))
10864 (mapcar
10865 (lambda (x)
10866 (setq r (substring x l))
10867 (if (string-match " ([^)]*)$" x)
10868 (setq f (match-string 0 x))
10869 (setq f ""))
10870 (if (string-match "/" r)
10871 (concat string (substring r 0 (match-end 0)) f)
10873 rtn))
10874 ((eq flag 'lambda)
10875 ;; exact match?
10876 (assoc string thetable)))
10878 args)))
10880 ;;;; Dynamic blocks
10882 (defun org-find-dblock (name)
10883 "Find the first dynamic block with name NAME in the buffer.
10884 If not found, stay at current position and return nil."
10885 (let (pos)
10886 (save-excursion
10887 (goto-char (point-min))
10888 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10889 nil t)
10890 (match-beginning 0))))
10891 (if pos (goto-char pos))
10892 pos))
10894 (defconst org-dblock-start-re
10895 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10896 "Matches the start line of a dynamic block, with parameters.")
10898 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10899 "Matches the end of a dynamic block.")
10901 (defun org-create-dblock (plist)
10902 "Create a dynamic block section, with parameters taken from PLIST.
10903 PLIST must contain a :name entry which is used as name of the block."
10904 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10905 (end-of-line 1)
10906 (newline))
10907 (let ((col (current-column))
10908 (name (plist-get plist :name)))
10909 (insert "#+BEGIN: " name)
10910 (while plist
10911 (if (eq (car plist) :name)
10912 (setq plist (cddr plist))
10913 (insert " " (prin1-to-string (pop plist)))))
10914 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10915 (beginning-of-line -2)))
10917 (defun org-prepare-dblock ()
10918 "Prepare dynamic block for refresh.
10919 This empties the block, puts the cursor at the insert position and returns
10920 the property list including an extra property :name with the block name."
10921 (unless (looking-at org-dblock-start-re)
10922 (error "Not at a dynamic block"))
10923 (let* ((begdel (1+ (match-end 0)))
10924 (name (org-no-properties (match-string 1)))
10925 (params (append (list :name name)
10926 (read (concat "(" (match-string 3) ")")))))
10927 (save-excursion
10928 (beginning-of-line 1)
10929 (skip-chars-forward " \t")
10930 (setq params (plist-put params :indentation-column (current-column))))
10931 (unless (re-search-forward org-dblock-end-re nil t)
10932 (error "Dynamic block not terminated"))
10933 (setq params
10934 (append params
10935 (list :content (buffer-substring
10936 begdel (match-beginning 0)))))
10937 (delete-region begdel (match-beginning 0))
10938 (goto-char begdel)
10939 (open-line 1)
10940 params))
10942 (defun org-map-dblocks (&optional command)
10943 "Apply COMMAND to all dynamic blocks in the current buffer.
10944 If COMMAND is not given, use `org-update-dblock'."
10945 (let ((cmd (or command 'org-update-dblock)))
10946 (save-excursion
10947 (goto-char (point-min))
10948 (while (re-search-forward org-dblock-start-re nil t)
10949 (goto-char (match-beginning 0))
10950 (save-excursion
10951 (condition-case nil
10952 (funcall cmd)
10953 (error (message "Error during update of dynamic block"))))
10954 (unless (re-search-forward org-dblock-end-re nil t)
10955 (error "Dynamic block not terminated"))))))
10957 (defun org-dblock-update (&optional arg)
10958 "User command for updating dynamic blocks.
10959 Update the dynamic block at point. With prefix ARG, update all dynamic
10960 blocks in the buffer."
10961 (interactive "P")
10962 (if arg
10963 (org-update-all-dblocks)
10964 (or (looking-at org-dblock-start-re)
10965 (org-beginning-of-dblock))
10966 (org-update-dblock)))
10968 (defun org-update-dblock ()
10969 "Update the dynamic block at point.
10970 This means to empty the block, parse for parameters and then call
10971 the correct writing function."
10972 (interactive)
10973 (save-window-excursion
10974 (let* ((pos (point))
10975 (line (org-current-line))
10976 (params (org-prepare-dblock))
10977 (name (plist-get params :name))
10978 (indent (plist-get params :indentation-column))
10979 (cmd (intern (concat "org-dblock-write:" name))))
10980 (message "Updating dynamic block `%s' at line %d..." name line)
10981 (funcall cmd params)
10982 (message "Updating dynamic block `%s' at line %d...done" name line)
10983 (goto-char pos)
10984 (when (and indent (> indent 0))
10985 (setq indent (make-string indent ?\ ))
10986 (save-excursion
10987 (org-beginning-of-dblock)
10988 (forward-line 1)
10989 (while (not (looking-at org-dblock-end-re))
10990 (insert indent)
10991 (beginning-of-line 2))
10992 (when (looking-at org-dblock-end-re)
10993 (and (looking-at "[ \t]+")
10994 (replace-match ""))
10995 (insert indent)))))))
10997 (defun org-beginning-of-dblock ()
10998 "Find the beginning of the dynamic block at point.
10999 Error if there is no such block at point."
11000 (let ((pos (point))
11001 beg)
11002 (end-of-line 1)
11003 (if (and (re-search-backward org-dblock-start-re nil t)
11004 (setq beg (match-beginning 0))
11005 (re-search-forward org-dblock-end-re nil t)
11006 (> (match-end 0) pos))
11007 (goto-char beg)
11008 (goto-char pos)
11009 (error "Not in a dynamic block"))))
11011 (defun org-update-all-dblocks ()
11012 "Update all dynamic blocks in the buffer.
11013 This function can be used in a hook."
11014 (interactive)
11015 (when (eq major-mode 'org-mode)
11016 (org-map-dblocks 'org-update-dblock)))
11019 ;;;; Completion
11021 (defconst org-additional-option-like-keywords
11022 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11023 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11024 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11025 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11026 "BEGIN:" "END:"
11027 "ORGTBL" "TBLFM:" "TBLNAME:"
11028 "BEGIN_EXAMPLE" "END_EXAMPLE"
11029 "BEGIN_QUOTE" "END_QUOTE"
11030 "BEGIN_VERSE" "END_VERSE"
11031 "BEGIN_CENTER" "END_CENTER"
11032 "BEGIN_SRC" "END_SRC"
11033 "BEGIN_RESULT" "END_RESULT"
11034 "NAME:" "RESULTS:"
11035 "HEADER:" "HEADERS:"
11036 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11037 "CAPTION:" "LABEL:"
11038 "SETUPFILE:"
11039 "INCLUDE:"
11040 "BIND:"
11041 "MACRO:"))
11043 (defcustom org-structure-template-alist
11045 ("s" "#+begin_src ?\n\n#+end_src"
11046 "<src lang=\"?\">\n\n</src>")
11047 ("e" "#+begin_example\n?\n#+end_example"
11048 "<example>\n?\n</example>")
11049 ("q" "#+begin_quote\n?\n#+end_quote"
11050 "<quote>\n?\n</quote>")
11051 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11052 "<verse>\n?\n</verse>")
11053 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11054 "<center>\n?\n</center>")
11055 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11056 "<literal style=\"latex\">\n?\n</literal>")
11057 ("L" "#+latex: "
11058 "<literal style=\"latex\">?</literal>")
11059 ("h" "#+begin_html\n?\n#+end_html"
11060 "<literal style=\"html\">\n?\n</literal>")
11061 ("H" "#+html: "
11062 "<literal style=\"html\">?</literal>")
11063 ("a" "#+begin_ascii\n?\n#+end_ascii")
11064 ("A" "#+ascii: ")
11065 ("i" "#+index: ?"
11066 "#+index: ?")
11067 ("I" "#+include %file ?"
11068 "<include file=%file markup=\"?\">")
11070 "Structure completion elements.
11071 This is a list of abbreviation keys and values. The value gets inserted
11072 if you type `<' followed by the key and then press the completion key,
11073 usually `M-TAB'. %file will be replaced by a file name after prompting
11074 for the file using completion. The cursor will be placed at the position
11075 of the `?` in the template.
11076 There are two templates for each key, the first uses the original Org syntax,
11077 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11078 the default when the /org-mtags.el/ module has been loaded. See also the
11079 variable `org-mtags-prefer-muse-templates'.
11080 This is an experimental feature, it is undecided if it is going to stay in."
11081 :group 'org-completion
11082 :type '(repeat
11083 (string :tag "Key")
11084 (string :tag "Template")
11085 (string :tag "Muse Template")))
11087 (defun org-try-structure-completion ()
11088 "Try to complete a structure template before point.
11089 This looks for strings like \"<e\" on an otherwise empty line and
11090 expands them."
11091 (let ((l (buffer-substring (point-at-bol) (point)))
11093 (when (and (looking-at "[ \t]*$")
11094 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11095 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11096 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11097 (match-beginning 1)) a)
11098 t)))
11100 (defun org-complete-expand-structure-template (start cell)
11101 "Expand a structure template."
11102 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11103 (rpl (nth (if musep 2 1) cell))
11104 (ind ""))
11105 (delete-region start (point))
11106 (when (string-match "\\`#\\+" rpl)
11107 (cond
11108 ((bolp))
11109 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11110 (setq ind (buffer-substring (point-at-bol) (point))))
11111 (t (newline))))
11112 (setq start (point))
11113 (if (string-match "%file" rpl)
11114 (setq rpl (replace-match
11115 (concat
11116 "\""
11117 (save-match-data
11118 (abbreviate-file-name (read-file-name "Include file: ")))
11119 "\"")
11120 t t rpl)))
11121 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11122 (concat "\n" ind)))
11123 (insert rpl)
11124 (if (re-search-backward "\\?" start t) (delete-char 1))))
11126 ;;;; TODO, DEADLINE, Comments
11128 (defun org-toggle-comment ()
11129 "Change the COMMENT state of an entry."
11130 (interactive)
11131 (save-excursion
11132 (org-back-to-heading)
11133 (let (case-fold-search)
11134 (cond
11135 ((looking-at (format org-heading-keyword-regexp-format
11136 org-comment-string))
11137 (goto-char (match-end 1))
11138 (looking-at (concat " +" org-comment-string))
11139 (replace-match "" t t)
11140 (when (eolp) (insert " ")))
11141 ((looking-at org-outline-regexp)
11142 (goto-char (match-end 0))
11143 (insert org-comment-string " "))))))
11145 (defvar org-last-todo-state-is-todo nil
11146 "This is non-nil when the last TODO state change led to a TODO state.
11147 If the last change removed the TODO tag or switched to DONE, then
11148 this is nil.")
11150 (defvar org-setting-tags nil) ; dynamically skipped
11152 (defvar org-todo-setup-filter-hook nil
11153 "Hook for functions that pre-filter todo specs.
11154 Each function takes a todo spec and returns either nil or the spec
11155 transformed into canonical form." )
11157 (defvar org-todo-get-default-hook nil
11158 "Hook for functions that get a default item for todo.
11159 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11160 nil or a string to be used for the todo mark." )
11162 (defvar org-agenda-headline-snapshot-before-repeat)
11164 (defun org-current-effective-time ()
11165 "Return current time adjusted for `org-extend-today-until' variable"
11166 (let* ((ct (org-current-time))
11167 (dct (decode-time ct))
11168 (ct1
11169 (if (and org-use-effective-time
11170 (< (nth 2 dct) org-extend-today-until))
11171 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11172 ct)))
11173 ct1))
11175 (defun org-todo-yesterday (&optional arg)
11176 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11177 (interactive "P")
11178 (if (eq major-mode 'org-agenda-mode)
11179 (apply 'org-agenda-todo-yesterday arg)
11180 (let* ((hour (third (decode-time
11181 (org-current-time))))
11182 (org-extend-today-until (1+ hour)))
11183 (org-todo arg))))
11185 (defun org-todo (&optional arg)
11186 "Change the TODO state of an item.
11187 The state of an item is given by a keyword at the start of the heading,
11188 like
11189 *** TODO Write paper
11190 *** DONE Call mom
11192 The different keywords are specified in the variable `org-todo-keywords'.
11193 By default the available states are \"TODO\" and \"DONE\".
11194 So for this example: when the item starts with TODO, it is changed to DONE.
11195 When it starts with DONE, the DONE is removed. And when neither TODO nor
11196 DONE are present, add TODO at the beginning of the heading.
11198 With \\[universal-argument] prefix arg, use completion to determine the new \
11199 state.
11200 With numeric prefix arg, switch to that state.
11201 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11202 keywords (nextset).
11203 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11204 With a numeric prefix arg of 0, inhibit note taking for the change.
11206 For calling through lisp, arg is also interpreted in the following way:
11207 'none -> empty state
11208 \"\"(empty string) -> switch to empty state
11209 'done -> switch to DONE
11210 'nextset -> switch to the next set of keywords
11211 'previousset -> switch to the previous set of keywords
11212 \"WAITING\" -> switch to the specified keyword, but only if it
11213 really is a member of `org-todo-keywords'."
11214 (interactive "P")
11215 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11216 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11217 'region-start-level 'region))
11218 org-loop-over-headlines-in-active-region)
11219 (org-map-entries
11220 `(org-todo ,arg)
11221 org-loop-over-headlines-in-active-region
11222 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11223 (if (equal arg '(16)) (setq arg 'nextset))
11224 (let ((org-blocker-hook org-blocker-hook)
11225 (case-fold-search nil))
11226 (when (equal arg '(64))
11227 (setq arg nil org-blocker-hook nil))
11228 (when (and org-blocker-hook
11229 (or org-inhibit-blocking
11230 (org-entry-get nil "NOBLOCKING")))
11231 (setq org-blocker-hook nil))
11232 (save-excursion
11233 (catch 'exit
11234 (org-back-to-heading t)
11235 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11236 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11237 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11238 (let* ((match-data (match-data))
11239 (startpos (point-at-bol))
11240 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11241 (org-log-done org-log-done)
11242 (org-log-repeat org-log-repeat)
11243 (org-todo-log-states org-todo-log-states)
11244 (org-inhibit-logging
11245 (if (equal arg 0)
11246 (progn (setq arg nil) 'note) org-inhibit-logging))
11247 (this (match-string 1))
11248 (hl-pos (match-beginning 0))
11249 (head (org-get-todo-sequence-head this))
11250 (ass (assoc head org-todo-kwd-alist))
11251 (interpret (nth 1 ass))
11252 (done-word (nth 3 ass))
11253 (final-done-word (nth 4 ass))
11254 (last-state (or this ""))
11255 (completion-ignore-case t)
11256 (member (member this org-todo-keywords-1))
11257 (tail (cdr member))
11258 (state (cond
11259 ((and org-todo-key-trigger
11260 (or (and (equal arg '(4))
11261 (eq org-use-fast-todo-selection 'prefix))
11262 (and (not arg) org-use-fast-todo-selection
11263 (not (eq org-use-fast-todo-selection
11264 'prefix)))))
11265 ;; Use fast selection
11266 (org-fast-todo-selection))
11267 ((and (equal arg '(4))
11268 (or (not org-use-fast-todo-selection)
11269 (not org-todo-key-trigger)))
11270 ;; Read a state with completion
11271 (org-icompleting-read
11272 "State: " (mapcar (lambda(x) (list x))
11273 org-todo-keywords-1)
11274 nil t))
11275 ((eq arg 'right)
11276 (if this
11277 (if tail (car tail) nil)
11278 (car org-todo-keywords-1)))
11279 ((eq arg 'left)
11280 (if (equal member org-todo-keywords-1)
11282 (if this
11283 (nth (- (length org-todo-keywords-1)
11284 (length tail) 2)
11285 org-todo-keywords-1)
11286 (org-last org-todo-keywords-1))))
11287 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11288 (setq arg nil))) ; hack to fall back to cycling
11289 (arg
11290 ;; user or caller requests a specific state
11291 (cond
11292 ((equal arg "") nil)
11293 ((eq arg 'none) nil)
11294 ((eq arg 'done) (or done-word (car org-done-keywords)))
11295 ((eq arg 'nextset)
11296 (or (car (cdr (member head org-todo-heads)))
11297 (car org-todo-heads)))
11298 ((eq arg 'previousset)
11299 (let ((org-todo-heads (reverse org-todo-heads)))
11300 (or (car (cdr (member head org-todo-heads)))
11301 (car org-todo-heads))))
11302 ((car (member arg org-todo-keywords-1)))
11303 ((stringp arg)
11304 (error "State `%s' not valid in this file" arg))
11305 ((nth (1- (prefix-numeric-value arg))
11306 org-todo-keywords-1))))
11307 ((null member) (or head (car org-todo-keywords-1)))
11308 ((equal this final-done-word) nil) ;; -> make empty
11309 ((null tail) nil) ;; -> first entry
11310 ((memq interpret '(type priority))
11311 (if (eq this-command last-command)
11312 (car tail)
11313 (if (> (length tail) 0)
11314 (or done-word (car org-done-keywords))
11315 nil)))
11317 (car tail))))
11318 (state (or
11319 (run-hook-with-args-until-success
11320 'org-todo-get-default-hook state last-state)
11321 state))
11322 (next (if state (concat " " state " ") " "))
11323 (change-plist (list :type 'todo-state-change :from this :to state
11324 :position startpos))
11325 dolog now-done-p)
11326 (when org-blocker-hook
11327 (setq org-last-todo-state-is-todo
11328 (not (member this org-done-keywords)))
11329 (unless (save-excursion
11330 (save-match-data
11331 (org-with-wide-buffer
11332 (run-hook-with-args-until-failure
11333 'org-blocker-hook change-plist))))
11334 (if (org-called-interactively-p 'interactive)
11335 (error "TODO state change from %s to %s blocked" this state)
11336 ;; fail silently
11337 (message "TODO state change from %s to %s blocked" this state)
11338 (throw 'exit nil))))
11339 (store-match-data match-data)
11340 (replace-match next t t)
11341 (unless (pos-visible-in-window-p hl-pos)
11342 (message "TODO state changed to %s" (org-trim next)))
11343 (unless head
11344 (setq head (org-get-todo-sequence-head state)
11345 ass (assoc head org-todo-kwd-alist)
11346 interpret (nth 1 ass)
11347 done-word (nth 3 ass)
11348 final-done-word (nth 4 ass)))
11349 (when (memq arg '(nextset previousset))
11350 (message "Keyword-Set %d/%d: %s"
11351 (- (length org-todo-sets) -1
11352 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11353 (length org-todo-sets)
11354 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11355 (setq org-last-todo-state-is-todo
11356 (not (member state org-done-keywords)))
11357 (setq now-done-p (and (member state org-done-keywords)
11358 (not (member this org-done-keywords))))
11359 (and logging (org-local-logging logging))
11360 (when (and (or org-todo-log-states org-log-done)
11361 (not (eq org-inhibit-logging t))
11362 (not (memq arg '(nextset previousset))))
11363 ;; we need to look at recording a time and note
11364 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11365 (nth 2 (assoc this org-todo-log-states))))
11366 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11367 (setq dolog 'time))
11368 (when (and state
11369 (member state org-not-done-keywords)
11370 (not (member this org-not-done-keywords)))
11371 ;; This is now a todo state and was not one before
11372 ;; If there was a CLOSED time stamp, get rid of it.
11373 (org-add-planning-info nil nil 'closed))
11374 (when (and now-done-p org-log-done)
11375 ;; It is now done, and it was not done before
11376 (org-add-planning-info 'closed (org-current-effective-time))
11377 (if (and (not dolog) (eq 'note org-log-done))
11378 (org-add-log-setup 'done state this 'findpos 'note)))
11379 (when (and state dolog)
11380 ;; This is a non-nil state, and we need to log it
11381 (org-add-log-setup 'state state this 'findpos dolog)))
11382 ;; Fixup tag positioning
11383 (org-todo-trigger-tag-changes state)
11384 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11385 (when org-provide-todo-statistics
11386 (org-update-parent-todo-statistics))
11387 (run-hooks 'org-after-todo-state-change-hook)
11388 (if (and arg (not (member state org-done-keywords)))
11389 (setq head (org-get-todo-sequence-head state)))
11390 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11391 ;; Do we need to trigger a repeat?
11392 (when now-done-p
11393 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11394 ;; This is for the agenda, take a snapshot of the headline.
11395 (save-match-data
11396 (setq org-agenda-headline-snapshot-before-repeat
11397 (org-get-heading))))
11398 (org-auto-repeat-maybe state))
11399 ;; Fixup cursor location if close to the keyword
11400 (if (and (outline-on-heading-p)
11401 (not (bolp))
11402 (save-excursion (beginning-of-line 1)
11403 (looking-at org-todo-line-regexp))
11404 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11405 (progn
11406 (goto-char (or (match-end 2) (match-end 1)))
11407 (and (looking-at " ") (just-one-space))))
11408 (when org-trigger-hook
11409 (save-excursion
11410 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11412 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11413 "Block turning an entry into a TODO, using the hierarchy.
11414 This checks whether the current task should be blocked from state
11415 changes. Such blocking occurs when:
11417 1. The task has children which are not all in a completed state.
11419 2. A task has a parent with the property :ORDERED:, and there
11420 are siblings prior to the current task with incomplete
11421 status.
11423 3. The parent of the task is blocked because it has siblings that should
11424 be done first, or is child of a block grandparent TODO entry."
11426 (if (not org-enforce-todo-dependencies)
11427 t ; if locally turned off don't block
11428 (catch 'dont-block
11429 ;; If this is not a todo state change, or if this entry is already DONE,
11430 ;; do not block
11431 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11432 (member (plist-get change-plist :from)
11433 (cons 'done org-done-keywords))
11434 (member (plist-get change-plist :to)
11435 (cons 'todo org-not-done-keywords))
11436 (not (plist-get change-plist :to)))
11437 (throw 'dont-block t))
11438 ;; If this task has children, and any are undone, it's blocked
11439 (save-excursion
11440 (org-back-to-heading t)
11441 (let ((this-level (funcall outline-level)))
11442 (outline-next-heading)
11443 (let ((child-level (funcall outline-level)))
11444 (while (and (not (eobp))
11445 (> child-level this-level))
11446 ;; this todo has children, check whether they are all
11447 ;; completed
11448 (if (and (not (org-entry-is-done-p))
11449 (org-entry-is-todo-p))
11450 (throw 'dont-block nil))
11451 (outline-next-heading)
11452 (setq child-level (funcall outline-level))))))
11453 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11454 ;; any previous siblings are undone, it's blocked
11455 (save-excursion
11456 (org-back-to-heading t)
11457 (let* ((pos (point))
11458 (parent-pos (and (org-up-heading-safe) (point))))
11459 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11460 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11461 (forward-line 1)
11462 (re-search-forward org-not-done-heading-regexp pos t))
11463 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11464 ;; Search further up the hierarchy, to see if an ancestor is blocked
11465 (while t
11466 (goto-char parent-pos)
11467 (if (not (looking-at org-not-done-heading-regexp))
11468 (throw 'dont-block t)) ; do not block, parent is not a TODO
11469 (setq pos (point))
11470 (setq parent-pos (and (org-up-heading-safe) (point)))
11471 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11472 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11473 (forward-line 1)
11474 (re-search-forward org-not-done-heading-regexp pos t))
11475 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11477 (defcustom org-track-ordered-property-with-tag nil
11478 "Should the ORDERED property also be shown as a tag?
11479 The ORDERED property decides if an entry should require subtasks to be
11480 completed in sequence. Since a property is not very visible, setting
11481 this option means that toggling the ORDERED property with the command
11482 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11483 not relevant for the behavior, but it makes things more visible.
11485 Note that toggling the tag with tags commands will not change the property
11486 and therefore not influence behavior!
11488 This can be t, meaning the tag ORDERED should be used, It can also be a
11489 string to select a different tag for this task."
11490 :group 'org-todo
11491 :type '(choice
11492 (const :tag "No tracking" nil)
11493 (const :tag "Track with ORDERED tag" t)
11494 (string :tag "Use other tag")))
11496 (defun org-toggle-ordered-property ()
11497 "Toggle the ORDERED property of the current entry.
11498 For better visibility, you can track the value of this property with a tag.
11499 See variable `org-track-ordered-property-with-tag'."
11500 (interactive)
11501 (let* ((t1 org-track-ordered-property-with-tag)
11502 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11503 (save-excursion
11504 (org-back-to-heading)
11505 (if (org-entry-get nil "ORDERED")
11506 (progn
11507 (org-delete-property "ORDERED")
11508 (and tag (org-toggle-tag tag 'off))
11509 (message "Subtasks can be completed in arbitrary order"))
11510 (org-entry-put nil "ORDERED" "t")
11511 (and tag (org-toggle-tag tag 'on))
11512 (message "Subtasks must be completed in sequence")))))
11514 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11515 (defun org-block-todo-from-checkboxes (change-plist)
11516 "Block turning an entry into a TODO, using checkboxes.
11517 This checks whether the current task should be blocked from state
11518 changes because there are unchecked boxes in this entry."
11519 (if (not org-enforce-todo-checkbox-dependencies)
11520 t ; if locally turned off don't block
11521 (catch 'dont-block
11522 ;; If this is not a todo state change, or if this entry is already DONE,
11523 ;; do not block
11524 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11525 (member (plist-get change-plist :from)
11526 (cons 'done org-done-keywords))
11527 (member (plist-get change-plist :to)
11528 (cons 'todo org-not-done-keywords))
11529 (not (plist-get change-plist :to)))
11530 (throw 'dont-block t))
11531 ;; If this task has checkboxes that are not checked, it's blocked
11532 (save-excursion
11533 (org-back-to-heading t)
11534 (let ((beg (point)) end)
11535 (outline-next-heading)
11536 (setq end (point))
11537 (goto-char beg)
11538 (if (org-list-search-forward
11539 (concat (org-item-beginning-re)
11540 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11541 "\\[[- ]\\]")
11542 end t)
11543 (progn
11544 (if (boundp 'org-blocked-by-checkboxes)
11545 (setq org-blocked-by-checkboxes t))
11546 (throw 'dont-block nil)))))
11547 t))) ; do not block
11549 (defun org-entry-blocked-p ()
11550 "Is the current entry blocked?"
11551 (if (org-entry-get nil "NOBLOCKING")
11552 nil ;; Never block this entry
11553 (not
11554 (run-hook-with-args-until-failure
11555 'org-blocker-hook
11556 (list :type 'todo-state-change
11557 :position (point)
11558 :from 'todo
11559 :to 'done)))))
11561 (defun org-update-statistics-cookies (all)
11562 "Update the statistics cookie, either from TODO or from checkboxes.
11563 This should be called with the cursor in a line with a statistics cookie."
11564 (interactive "P")
11565 (if all
11566 (progn
11567 (org-update-checkbox-count 'all)
11568 (org-map-entries 'org-update-parent-todo-statistics))
11569 (if (not (org-at-heading-p))
11570 (org-update-checkbox-count)
11571 (let ((pos (move-marker (make-marker) (point)))
11572 end l1 l2)
11573 (ignore-errors (org-back-to-heading t))
11574 (if (not (org-at-heading-p))
11575 (org-update-checkbox-count)
11576 (setq l1 (org-outline-level))
11577 (setq end (save-excursion
11578 (outline-next-heading)
11579 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11580 (point)))
11581 (if (and (save-excursion
11582 (re-search-forward
11583 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11584 (not (save-excursion (re-search-forward
11585 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11586 (org-update-checkbox-count)
11587 (if (and l2 (> l2 l1))
11588 (progn
11589 (goto-char end)
11590 (org-update-parent-todo-statistics))
11591 (goto-char pos)
11592 (beginning-of-line 1)
11593 (while (re-search-forward
11594 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11595 (point-at-eol) t)
11596 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11597 (goto-char pos)
11598 (move-marker pos nil)))))
11600 (defvar org-entry-property-inherited-from) ;; defined below
11601 (defun org-update-parent-todo-statistics ()
11602 "Update any statistics cookie in the parent of the current headline.
11603 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11604 the entire subtree and this will travel up the hierarchy and update
11605 statistics everywhere."
11606 (let* ((prop (save-excursion (org-up-heading-safe)
11607 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11608 (recursive (or (not org-hierarchical-todo-statistics)
11609 (and prop (string-match "\\<recursive\\>" prop))))
11610 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11612 (first t)
11613 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11614 level ltoggle l1 new ndel
11615 (cnt-all 0) (cnt-done 0) is-percent kwd
11616 checkbox-beg ov ovs ove cookie-present)
11617 (catch 'exit
11618 (save-excursion
11619 (beginning-of-line 1)
11620 (setq ltoggle (funcall outline-level))
11621 ;; Three situations are to consider:
11623 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11624 ;; to the top-level ancestor on the headline;
11626 ;; 2. If parent has "recursive" property, repeat up to the
11627 ;; headline setting that property, taking inheritance into
11628 ;; account;
11630 ;; 3. Else, move up to direct parent and proceed only once.
11631 (while (and (setq level (org-up-heading-safe))
11632 (or recursive first)
11633 (>= (point) lim))
11634 (setq first nil cookie-present nil)
11635 (unless (and level
11636 (not (string-match
11637 "\\<checkbox\\>"
11638 (downcase (or (org-entry-get nil "COOKIE_DATA")
11639 "")))))
11640 (throw 'exit nil))
11641 (while (re-search-forward box-re (point-at-eol) t)
11642 (setq cnt-all 0 cnt-done 0 cookie-present t)
11643 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11644 (save-match-data
11645 (unless (outline-next-heading) (throw 'exit nil))
11646 (while (and (looking-at org-complex-heading-regexp)
11647 (> (setq l1 (length (match-string 1))) level))
11648 (setq kwd (and (or recursive (= l1 ltoggle))
11649 (match-string 2)))
11650 (if (or (eq org-provide-todo-statistics 'all-headlines)
11651 (and (listp org-provide-todo-statistics)
11652 (or (member kwd org-provide-todo-statistics)
11653 (member kwd org-done-keywords))))
11654 (setq cnt-all (1+ cnt-all))
11655 (if (eq org-provide-todo-statistics t)
11656 (and kwd (setq cnt-all (1+ cnt-all)))))
11657 (and (member kwd org-done-keywords)
11658 (setq cnt-done (1+ cnt-done)))
11659 (outline-next-heading)))
11660 (setq new
11661 (if is-percent
11662 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11663 (format "[%d/%d]" cnt-done cnt-all))
11664 ndel (- (match-end 0) checkbox-beg))
11665 ;; handle overlays when updating cookie from column view
11666 (when (setq ov (car (overlays-at checkbox-beg)))
11667 (setq ovs (overlay-start ov) ove (overlay-end ov))
11668 (delete-overlay ov))
11669 (goto-char checkbox-beg)
11670 (insert new)
11671 (delete-region (point) (+ (point) ndel))
11672 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11673 (when ov (move-overlay ov ovs ove)))
11674 (when cookie-present
11675 (run-hook-with-args 'org-after-todo-statistics-hook
11676 cnt-done (- cnt-all cnt-done))))))
11677 (run-hooks 'org-todo-statistics-hook)))
11679 (defvar org-after-todo-statistics-hook nil
11680 "Hook that is called after a TODO statistics cookie has been updated.
11681 Each function is called with two arguments: the number of not-done entries
11682 and the number of done entries.
11684 For example, the following function, when added to this hook, will switch
11685 an entry to DONE when all children are done, and back to TODO when new
11686 entries are set to a TODO status. Note that this hook is only called
11687 when there is a statistics cookie in the headline!
11689 (defun org-summary-todo (n-done n-not-done)
11690 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11691 (let (org-log-done org-log-states) ; turn off logging
11692 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11695 (defvar org-todo-statistics-hook nil
11696 "Hook that is run whenever Org thinks TODO statistics should be updated.
11697 This hook runs even if there is no statistics cookie present, in which case
11698 `org-after-todo-statistics-hook' would not run.")
11700 (defun org-todo-trigger-tag-changes (state)
11701 "Apply the changes defined in `org-todo-state-tags-triggers'."
11702 (let ((l org-todo-state-tags-triggers)
11703 changes)
11704 (when (or (not state) (equal state ""))
11705 (setq changes (append changes (cdr (assoc "" l)))))
11706 (when (and (stringp state) (> (length state) 0))
11707 (setq changes (append changes (cdr (assoc state l)))))
11708 (when (member state org-not-done-keywords)
11709 (setq changes (append changes (cdr (assoc 'todo l)))))
11710 (when (member state org-done-keywords)
11711 (setq changes (append changes (cdr (assoc 'done l)))))
11712 (dolist (c changes)
11713 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11715 (defun org-local-logging (value)
11716 "Get logging settings from a property VALUE."
11717 (let* (words w a)
11718 ;; directly set the variables, they are already local.
11719 (setq org-log-done nil
11720 org-log-repeat nil
11721 org-todo-log-states nil)
11722 (setq words (org-split-string value))
11723 (while (setq w (pop words))
11724 (cond
11725 ((setq a (assoc w org-startup-options))
11726 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11727 (set (nth 1 a) (nth 2 a))))
11728 ((setq a (org-extract-log-state-settings w))
11729 (and (member (car a) org-todo-keywords-1)
11730 (push a org-todo-log-states)))))))
11732 (defun org-get-todo-sequence-head (kwd)
11733 "Return the head of the TODO sequence to which KWD belongs.
11734 If KWD is not set, check if there is a text property remembering the
11735 right sequence."
11736 (let (p)
11737 (cond
11738 ((not kwd)
11739 (or (get-text-property (point-at-bol) 'org-todo-head)
11740 (progn
11741 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11742 nil (point-at-eol)))
11743 (get-text-property p 'org-todo-head))))
11744 ((not (member kwd org-todo-keywords-1))
11745 (car org-todo-keywords-1))
11746 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11748 (defun org-fast-todo-selection ()
11749 "Fast TODO keyword selection with single keys.
11750 Returns the new TODO keyword, or nil if no state change should occur."
11751 (let* ((fulltable org-todo-key-alist)
11752 (done-keywords org-done-keywords) ;; needed for the faces.
11753 (maxlen (apply 'max (mapcar
11754 (lambda (x)
11755 (if (stringp (car x)) (string-width (car x)) 0))
11756 fulltable)))
11757 (expert nil)
11758 (fwidth (+ maxlen 3 1 3))
11759 (ncol (/ (- (window-width) 4) fwidth))
11760 tg cnt e c tbl
11761 groups ingroup)
11762 (save-excursion
11763 (save-window-excursion
11764 (if expert
11765 (set-buffer (get-buffer-create " *Org todo*"))
11766 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11767 (erase-buffer)
11768 (org-set-local 'org-done-keywords done-keywords)
11769 (setq tbl fulltable cnt 0)
11770 (while (setq e (pop tbl))
11771 (cond
11772 ((equal e '(:startgroup))
11773 (push '() groups) (setq ingroup t)
11774 (when (not (= cnt 0))
11775 (setq cnt 0)
11776 (insert "\n"))
11777 (insert "{ "))
11778 ((equal e '(:endgroup))
11779 (setq ingroup nil cnt 0)
11780 (insert "}\n"))
11781 ((equal e '(:newline))
11782 (when (not (= cnt 0))
11783 (setq cnt 0)
11784 (insert "\n")
11785 (setq e (car tbl))
11786 (while (equal (car tbl) '(:newline))
11787 (insert "\n")
11788 (setq tbl (cdr tbl)))))
11790 (setq tg (car e) c (cdr e))
11791 (if ingroup (push tg (car groups)))
11792 (setq tg (org-add-props tg nil 'face
11793 (org-get-todo-face tg)))
11794 (if (and (= cnt 0) (not ingroup)) (insert " "))
11795 (insert "[" c "] " tg (make-string
11796 (- fwidth 4 (length tg)) ?\ ))
11797 (when (= (setq cnt (1+ cnt)) ncol)
11798 (insert "\n")
11799 (if ingroup (insert " "))
11800 (setq cnt 0)))))
11801 (insert "\n")
11802 (goto-char (point-min))
11803 (if (not expert) (org-fit-window-to-buffer))
11804 (message "[a-z..]:Set [SPC]:clear")
11805 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11806 (cond
11807 ((or (= c ?\C-g)
11808 (and (= c ?q) (not (rassoc c fulltable))))
11809 (setq quit-flag t))
11810 ((= c ?\ ) nil)
11811 ((setq e (rassoc c fulltable) tg (car e))
11813 (t (setq quit-flag t)))))))
11815 (defun org-entry-is-todo-p ()
11816 (member (org-get-todo-state) org-not-done-keywords))
11818 (defun org-entry-is-done-p ()
11819 (member (org-get-todo-state) org-done-keywords))
11821 (defun org-get-todo-state ()
11822 (save-excursion
11823 (org-back-to-heading t)
11824 (and (looking-at org-todo-line-regexp)
11825 (match-end 2)
11826 (match-string 2))))
11828 (defun org-at-date-range-p (&optional inactive-ok)
11829 "Is the cursor inside a date range?"
11830 (interactive)
11831 (save-excursion
11832 (catch 'exit
11833 (let ((pos (point)))
11834 (skip-chars-backward "^[<\r\n")
11835 (skip-chars-backward "<[")
11836 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11837 (>= (match-end 0) pos)
11838 (throw 'exit t))
11839 (skip-chars-backward "^<[\r\n")
11840 (skip-chars-backward "<[")
11841 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11842 (>= (match-end 0) pos)
11843 (throw 'exit t)))
11844 nil)))
11846 (defun org-get-repeat (&optional tagline)
11847 "Check if there is a deadline/schedule with repeater in this entry."
11848 (save-match-data
11849 (save-excursion
11850 (org-back-to-heading t)
11851 (and (re-search-forward (if tagline
11852 (concat tagline "\\s-*" org-repeat-re)
11853 org-repeat-re)
11854 (org-entry-end-position) t)
11855 (match-string-no-properties 1)))))
11857 (defvar org-last-changed-timestamp)
11858 (defvar org-last-inserted-timestamp)
11859 (defvar org-log-post-message)
11860 (defvar org-log-note-purpose)
11861 (defvar org-log-note-how)
11862 (defvar org-log-note-extra)
11863 (defun org-auto-repeat-maybe (done-word)
11864 "Check if the current headline contains a repeated deadline/schedule.
11865 If yes, set TODO state back to what it was and change the base date
11866 of repeating deadline/scheduled time stamps to new date.
11867 This function is run automatically after each state change to a DONE state."
11868 ;; last-state is dynamically scoped into this function
11869 (let* ((repeat (org-get-repeat))
11870 (aa (assoc last-state org-todo-kwd-alist))
11871 (interpret (nth 1 aa))
11872 (head (nth 2 aa))
11873 (whata '(("d" . day) ("m" . month) ("y" . year)))
11874 (msg "Entry repeats: ")
11875 (org-log-done nil)
11876 (org-todo-log-states nil)
11877 re type n what ts time to-state)
11878 (when repeat
11879 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11880 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11881 org-todo-repeat-to-state))
11882 (unless (and to-state (member to-state org-todo-keywords-1))
11883 (setq to-state (if (eq interpret 'type) last-state head)))
11884 (org-todo to-state)
11885 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11886 (org-entry-put nil "LAST_REPEAT" (format-time-string
11887 (org-time-stamp-format t t))))
11888 (when org-log-repeat
11889 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11890 (memq 'org-add-log-note post-command-hook))
11891 ;; OK, we are already setup for some record
11892 (if (eq org-log-repeat 'note)
11893 ;; make sure we take a note, not only a time stamp
11894 (setq org-log-note-how 'note))
11895 ;; Set up for taking a record
11896 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11897 last-state
11898 'findpos org-log-repeat)))
11899 (org-back-to-heading t)
11900 (org-add-planning-info nil nil 'closed)
11901 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11902 org-deadline-time-regexp "\\)\\|\\("
11903 org-ts-regexp "\\)"))
11904 (while (re-search-forward
11905 re (save-excursion (outline-next-heading) (point)) t)
11906 (setq type (if (match-end 1) org-scheduled-string
11907 (if (match-end 3) org-deadline-string "Plain:"))
11908 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11909 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11910 (setq n (string-to-number (match-string 2 ts))
11911 what (match-string 3 ts))
11912 (if (equal what "w") (setq n (* n 7) what "d"))
11913 ;; Preparation, see if we need to modify the start date for the change
11914 (when (match-end 1)
11915 (setq time (save-match-data (org-time-string-to-time ts)))
11916 (cond
11917 ((equal (match-string 1 ts) ".")
11918 ;; Shift starting date to today
11919 (org-timestamp-change
11920 (- (org-today) (time-to-days time))
11921 'day))
11922 ((equal (match-string 1 ts) "+")
11923 (let ((nshiftmax 10) (nshift 0))
11924 (while (or (= nshift 0)
11925 (<= (time-to-days time)
11926 (time-to-days (current-time))))
11927 (when (= (incf nshift) nshiftmax)
11928 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11929 (error "Abort")))
11930 (org-timestamp-change n (cdr (assoc what whata)))
11931 (org-at-timestamp-p t)
11932 (setq ts (match-string 1))
11933 (setq time (save-match-data (org-time-string-to-time ts)))))
11934 (org-timestamp-change (- n) (cdr (assoc what whata)))
11935 ;; rematch, so that we have everything in place for the real shift
11936 (org-at-timestamp-p t)
11937 (setq ts (match-string 1))
11938 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11939 (org-timestamp-change n (cdr (assoc what whata)))
11940 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11941 (setq org-log-post-message msg)
11942 (message "%s" msg))))
11944 (defun org-show-todo-tree (arg)
11945 "Make a compact tree which shows all headlines marked with TODO.
11946 The tree will show the lines where the regexp matches, and all higher
11947 headlines above the match.
11948 With a \\[universal-argument] prefix, prompt for a regexp to match.
11949 With a numeric prefix N, construct a sparse tree for the Nth element
11950 of `org-todo-keywords-1'."
11951 (interactive "P")
11952 (let ((case-fold-search nil)
11953 (kwd-re
11954 (cond ((null arg) org-not-done-regexp)
11955 ((equal arg '(4))
11956 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11957 (mapcar 'list org-todo-keywords-1))))
11958 (concat "\\("
11959 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11960 "\\)\\>")))
11961 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11962 (regexp-quote (nth (1- (prefix-numeric-value arg))
11963 org-todo-keywords-1)))
11964 (t (error "Invalid prefix argument: %s" arg)))))
11965 (message "%d TODO entries found"
11966 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11968 (defun org-deadline (&optional remove time)
11969 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11970 With argument REMOVE, remove any deadline from the item.
11971 With argument TIME, set the deadline at the corresponding date. TIME
11972 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11973 (interactive "P")
11974 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11975 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11976 'region-start-level 'region))
11977 org-loop-over-headlines-in-active-region)
11978 (org-map-entries
11979 `(org-deadline ',remove ,time)
11980 org-loop-over-headlines-in-active-region
11981 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11982 (let* ((old-date (org-entry-get nil "DEADLINE"))
11983 (repeater (and old-date
11984 (string-match
11985 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11986 old-date)
11987 (match-string 1 old-date))))
11988 (if remove
11989 (progn
11990 (when (and old-date org-log-redeadline)
11991 (org-add-log-setup 'deldeadline nil old-date 'findpos
11992 org-log-redeadline))
11993 (org-remove-timestamp-with-keyword org-deadline-string)
11994 (message "Item no longer has a deadline."))
11995 (org-add-planning-info 'deadline time 'closed)
11996 (when (and old-date org-log-redeadline
11997 (not (equal old-date
11998 (substring org-last-inserted-timestamp 1 -1))))
11999 (org-add-log-setup 'redeadline nil old-date 'findpos
12000 org-log-redeadline))
12001 (when repeater
12002 (save-excursion
12003 (org-back-to-heading t)
12004 (when (re-search-forward (concat org-deadline-string " "
12005 org-last-inserted-timestamp)
12006 (save-excursion
12007 (outline-next-heading) (point)) t)
12008 (goto-char (1- (match-end 0)))
12009 (insert " " repeater)
12010 (setq org-last-inserted-timestamp
12011 (concat (substring org-last-inserted-timestamp 0 -1)
12012 " " repeater
12013 (substring org-last-inserted-timestamp -1))))))
12014 (message "Deadline on %s" org-last-inserted-timestamp)))))
12016 (defun org-schedule (&optional remove time)
12017 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12018 With argument REMOVE, remove any scheduling date from the item.
12019 With argument TIME, scheduled at the corresponding date. TIME can
12020 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12021 (interactive "P")
12022 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12023 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12024 'region-start-level 'region))
12025 org-loop-over-headlines-in-active-region)
12026 (org-map-entries
12027 `(org-schedule ',remove ,time)
12028 org-loop-over-headlines-in-active-region
12029 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12030 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12031 (repeater (and old-date
12032 (string-match
12033 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12034 old-date)
12035 (match-string 1 old-date))))
12036 (if remove
12037 (progn
12038 (when (and old-date org-log-reschedule)
12039 (org-add-log-setup 'delschedule nil old-date 'findpos
12040 org-log-reschedule))
12041 (org-remove-timestamp-with-keyword org-scheduled-string)
12042 (message "Item is no longer scheduled."))
12043 (org-add-planning-info 'scheduled time 'closed)
12044 (when (and old-date org-log-reschedule
12045 (not (equal old-date
12046 (substring org-last-inserted-timestamp 1 -1))))
12047 (org-add-log-setup 'reschedule nil old-date 'findpos
12048 org-log-reschedule))
12049 (when repeater
12050 (save-excursion
12051 (org-back-to-heading t)
12052 (when (re-search-forward (concat org-scheduled-string " "
12053 org-last-inserted-timestamp)
12054 (save-excursion
12055 (outline-next-heading) (point)) t)
12056 (goto-char (1- (match-end 0)))
12057 (insert " " repeater)
12058 (setq org-last-inserted-timestamp
12059 (concat (substring org-last-inserted-timestamp 0 -1)
12060 " " repeater
12061 (substring org-last-inserted-timestamp -1))))))
12062 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12064 (defun org-get-scheduled-time (pom &optional inherit)
12065 "Get the scheduled time as a time tuple, of a format suitable
12066 for calling org-schedule with, or if there is no scheduling,
12067 returns nil."
12068 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12069 (when time
12070 (apply 'encode-time (org-parse-time-string time)))))
12072 (defun org-get-deadline-time (pom &optional inherit)
12073 "Get the deadline as a time tuple, of a format suitable for
12074 calling org-deadline with, or if there is no scheduling, returns
12075 nil."
12076 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12077 (when time
12078 (apply 'encode-time (org-parse-time-string time)))))
12080 (defun org-remove-timestamp-with-keyword (keyword)
12081 "Remove all time stamps with KEYWORD in the current entry."
12082 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12083 beg)
12084 (save-excursion
12085 (org-back-to-heading t)
12086 (setq beg (point))
12087 (outline-next-heading)
12088 (while (re-search-backward re beg t)
12089 (replace-match "")
12090 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12091 (equal (char-before) ?\ ))
12092 (backward-delete-char 1)
12093 (if (string-match "^[ \t]*$" (buffer-substring
12094 (point-at-bol) (point-at-eol)))
12095 (delete-region (point-at-bol)
12096 (min (point-max) (1+ (point-at-eol))))))))))
12098 (defun org-add-planning-info (what &optional time &rest remove)
12099 "Insert new timestamp with keyword in the line directly after the headline.
12100 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12101 If non is given, the user is prompted for a date.
12102 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12103 be removed."
12104 (interactive)
12105 (let (org-time-was-given org-end-time-was-given ts
12106 end default-time default-input)
12108 (catch 'exit
12109 (when (and (memq what '(scheduled deadline))
12110 (or (not time)
12111 (and (stringp time)
12112 (string-match "^[-+]+[0-9]" time))))
12113 ;; Try to get a default date/time from existing timestamp
12114 (save-excursion
12115 (org-back-to-heading t)
12116 (setq end (save-excursion (outline-next-heading) (point)))
12117 (when (re-search-forward (if (eq what 'scheduled)
12118 org-scheduled-time-regexp
12119 org-deadline-time-regexp)
12120 end t)
12121 (setq ts (match-string 1)
12122 default-time
12123 (apply 'encode-time (org-parse-time-string ts))
12124 default-input (and ts (org-get-compact-tod ts))))))
12125 (when what
12126 (setq time
12127 (if (stringp time)
12128 ;; This is a string (relative or absolute), set proper date
12129 (apply 'encode-time
12130 (org-read-date-analyze
12131 time default-time (decode-time default-time)))
12132 ;; If necessary, get the time from the user
12133 (or time (org-read-date nil 'to-time nil nil
12134 default-time default-input)))))
12136 (when (and org-insert-labeled-timestamps-at-point
12137 (member what '(scheduled deadline)))
12138 (insert
12139 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12140 (org-insert-time-stamp time org-time-was-given
12141 nil nil nil (list org-end-time-was-given))
12142 (setq what nil))
12143 (save-excursion
12144 (save-restriction
12145 (let (col list elt ts buffer-invisibility-spec)
12146 (org-back-to-heading t)
12147 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12148 (goto-char (match-end 1))
12149 (setq col (current-column))
12150 (goto-char (match-end 0))
12151 (if (eobp) (insert "\n") (forward-char 1))
12152 (when (and (not what)
12153 (not (looking-at
12154 (concat "[ \t]*"
12155 org-keyword-time-not-clock-regexp))))
12156 ;; Nothing to add, nothing to remove...... :-)
12157 (throw 'exit nil))
12158 (if (and (not (looking-at org-outline-regexp))
12159 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12160 "[^\r\n]*"))
12161 (not (equal (match-string 1) org-clock-string)))
12162 (narrow-to-region (match-beginning 0) (match-end 0))
12163 (insert-before-markers "\n")
12164 (backward-char 1)
12165 (narrow-to-region (point) (point))
12166 (and org-adapt-indentation (org-indent-to-column col)))
12167 ;; Check if we have to remove something.
12168 (setq list (cons what remove))
12169 (while list
12170 (setq elt (pop list))
12171 (when (or (and (eq elt 'scheduled)
12172 (re-search-forward org-scheduled-time-regexp nil t))
12173 (and (eq elt 'deadline)
12174 (re-search-forward org-deadline-time-regexp nil t))
12175 (and (eq elt 'closed)
12176 (re-search-forward org-closed-time-regexp nil t)))
12177 (replace-match "")
12178 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12179 (and (looking-at "[ \t]+") (replace-match ""))
12180 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12181 (when what
12182 (insert
12183 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12184 (cond ((eq what 'scheduled) org-scheduled-string)
12185 ((eq what 'deadline) org-deadline-string)
12186 ((eq what 'closed) org-closed-string))
12187 " ")
12188 (setq ts (org-insert-time-stamp
12189 time
12190 (or org-time-was-given
12191 (and (eq what 'closed) org-log-done-with-time))
12192 (eq what 'closed)
12193 nil nil (list org-end-time-was-given)))
12194 (insert
12195 (if (not (or (bolp) (eq (char-before) ?\ )
12196 (memq (char-after) '(32 10))
12197 (eobp))) " " ""))
12198 (end-of-line 1))
12199 (goto-char (point-min))
12200 (widen)
12201 (if (and (looking-at "[ \t]*\n")
12202 (equal (char-before) ?\n))
12203 (delete-region (1- (point)) (point-at-eol)))
12204 ts))))))
12206 (defvar org-log-note-marker (make-marker))
12207 (defvar org-log-note-purpose nil)
12208 (defvar org-log-note-state nil)
12209 (defvar org-log-note-previous-state nil)
12210 (defvar org-log-note-how nil)
12211 (defvar org-log-note-extra nil)
12212 (defvar org-log-note-window-configuration nil)
12213 (defvar org-log-note-return-to (make-marker))
12214 (defvar org-log-note-effective-time nil
12215 "Remembered current time so that dynamically scoped
12216 `org-extend-today-until' affects tha timestamps in state change
12217 log")
12219 (defvar org-log-post-message nil
12220 "Message to be displayed after a log note has been stored.
12221 The auto-repeater uses this.")
12223 (defun org-add-note ()
12224 "Add a note to the current entry.
12225 This is done in the same way as adding a state change note."
12226 (interactive)
12227 (org-add-log-setup 'note nil nil 'findpos nil))
12229 (defvar org-property-end-re)
12230 (defun org-add-log-setup (&optional purpose state prev-state
12231 findpos how extra)
12232 "Set up the post command hook to take a note.
12233 If this is about to TODO state change, the new state is expected in STATE.
12234 When FINDPOS is non-nil, find the correct position for the note in
12235 the current entry. If not, assume that it can be inserted at point.
12236 HOW is an indicator what kind of note should be created.
12237 EXTRA is additional text that will be inserted into the notes buffer."
12238 (let* ((org-log-into-drawer (org-log-into-drawer))
12239 (drawer (cond ((stringp org-log-into-drawer)
12240 org-log-into-drawer)
12241 (org-log-into-drawer "LOGBOOK")
12242 (t nil))))
12243 (save-restriction
12244 (save-excursion
12245 (when findpos
12246 (org-back-to-heading t)
12247 (narrow-to-region (point) (save-excursion
12248 (outline-next-heading) (point)))
12249 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12250 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12251 "[^\r\n]*\\)?"))
12252 (goto-char (match-end 0))
12253 (cond
12254 (drawer
12255 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12256 nil t)
12257 (progn
12258 (goto-char (match-end 0))
12259 (or org-log-states-order-reversed
12260 (and (re-search-forward org-property-end-re nil t)
12261 (goto-char (1- (match-beginning 0))))))
12262 (insert "\n:" drawer ":\n:END:")
12263 (beginning-of-line 0)
12264 (org-indent-line-function)
12265 (beginning-of-line 2)
12266 (org-indent-line-function)
12267 (end-of-line 0)))
12268 ((and org-log-state-notes-insert-after-drawers
12269 (save-excursion
12270 (forward-line) (looking-at org-drawer-regexp)))
12271 (forward-line)
12272 (while (looking-at org-drawer-regexp)
12273 (goto-char (match-end 0))
12274 (re-search-forward org-property-end-re (point-max) t)
12275 (forward-line))
12276 (forward-line -1)))
12277 (unless org-log-states-order-reversed
12278 (and (= (char-after) ?\n) (forward-char 1))
12279 (org-skip-over-state-notes)
12280 (skip-chars-backward " \t\n\r")))
12281 (move-marker org-log-note-marker (point))
12282 (setq org-log-note-purpose purpose
12283 org-log-note-state state
12284 org-log-note-previous-state prev-state
12285 org-log-note-how how
12286 org-log-note-extra extra
12287 org-log-note-effective-time (org-current-effective-time))
12288 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12290 (defun org-skip-over-state-notes ()
12291 "Skip past the list of State notes in an entry."
12292 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12293 (when (ignore-errors (goto-char (org-in-item-p)))
12294 (let* ((struct (org-list-struct))
12295 (prevs (org-list-prevs-alist struct)))
12296 (while (looking-at "[ \t]*- State")
12297 (goto-char (or (org-list-get-next-item (point) struct prevs)
12298 (org-list-get-item-end (point) struct)))))))
12300 (defun org-add-log-note (&optional purpose)
12301 "Pop up a window for taking a note, and add this note later at point."
12302 (remove-hook 'post-command-hook 'org-add-log-note)
12303 (setq org-log-note-window-configuration (current-window-configuration))
12304 (delete-other-windows)
12305 (move-marker org-log-note-return-to (point))
12306 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12307 (goto-char org-log-note-marker)
12308 (org-switch-to-buffer-other-window "*Org Note*")
12309 (erase-buffer)
12310 (if (memq org-log-note-how '(time state))
12311 (let (current-prefix-arg) (org-store-log-note))
12312 (let ((org-inhibit-startup t)) (org-mode))
12313 (insert (format "# Insert note for %s.
12314 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12315 (cond
12316 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12317 ((eq org-log-note-purpose 'done) "closed todo item")
12318 ((eq org-log-note-purpose 'state)
12319 (format "state change from \"%s\" to \"%s\""
12320 (or org-log-note-previous-state "")
12321 (or org-log-note-state "")))
12322 ((eq org-log-note-purpose 'reschedule)
12323 "rescheduling")
12324 ((eq org-log-note-purpose 'delschedule)
12325 "no longer scheduled")
12326 ((eq org-log-note-purpose 'redeadline)
12327 "changing deadline")
12328 ((eq org-log-note-purpose 'deldeadline)
12329 "removing deadline")
12330 ((eq org-log-note-purpose 'refile)
12331 "refiling")
12332 ((eq org-log-note-purpose 'note)
12333 "this entry")
12334 (t (error "This should not happen")))))
12335 (if org-log-note-extra (insert org-log-note-extra))
12336 (org-set-local 'org-finish-function 'org-store-log-note)
12337 (run-hooks 'org-log-buffer-setup-hook)))
12339 (defvar org-note-abort nil) ; dynamically scoped
12340 (defun org-store-log-note ()
12341 "Finish taking a log note, and insert it to where it belongs."
12342 (let ((txt (buffer-string))
12343 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12344 lines ind bul)
12345 (kill-buffer (current-buffer))
12346 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12347 (setq txt (replace-match "" t t txt)))
12348 (if (string-match "\\s-+\\'" txt)
12349 (setq txt (replace-match "" t t txt)))
12350 (setq lines (org-split-string txt "\n"))
12351 (when (and note (string-match "\\S-" note))
12352 (setq note
12353 (org-replace-escapes
12354 note
12355 (list (cons "%u" (user-login-name))
12356 (cons "%U" user-full-name)
12357 (cons "%t" (format-time-string
12358 (org-time-stamp-format 'long 'inactive)
12359 org-log-note-effective-time))
12360 (cons "%T" (format-time-string
12361 (org-time-stamp-format 'long nil)
12362 org-log-note-effective-time))
12363 (cons "%d" (format-time-string
12364 (org-time-stamp-format nil 'inactive)
12365 org-log-note-effective-time))
12366 (cons "%D" (format-time-string
12367 (org-time-stamp-format nil nil)
12368 org-log-note-effective-time))
12369 (cons "%s" (if org-log-note-state
12370 (concat "\"" org-log-note-state "\"")
12371 ""))
12372 (cons "%S" (if org-log-note-previous-state
12373 (concat "\"" org-log-note-previous-state "\"")
12374 "\"\"")))))
12375 (if lines (setq note (concat note " \\\\")))
12376 (push note lines))
12377 (when (or current-prefix-arg org-note-abort)
12378 (when org-log-into-drawer
12379 (org-remove-empty-drawer-at
12380 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12381 org-log-note-marker))
12382 (setq lines nil))
12383 (when lines
12384 (with-current-buffer (marker-buffer org-log-note-marker)
12385 (save-excursion
12386 (goto-char org-log-note-marker)
12387 (move-marker org-log-note-marker nil)
12388 (end-of-line 1)
12389 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12390 (setq ind (save-excursion
12391 (if (ignore-errors (goto-char (org-in-item-p)))
12392 (let ((struct (org-list-struct)))
12393 (org-list-get-ind
12394 (org-list-get-top-point struct) struct))
12395 (skip-chars-backward " \r\t\n")
12396 (cond
12397 ((and (org-at-heading-p)
12398 org-adapt-indentation)
12399 (1+ (org-current-level)))
12400 ((org-at-heading-p) 0)
12401 (t (org-get-indentation))))))
12402 (setq bul (org-list-bullet-string "-"))
12403 (org-indent-line-to ind)
12404 (insert bul (pop lines))
12405 (let ((ind-body (+ (length bul) ind)))
12406 (while lines
12407 (insert "\n")
12408 (org-indent-line-to ind-body)
12409 (insert (pop lines))))
12410 (message "Note stored")
12411 (org-back-to-heading t)
12412 (org-cycle-hide-drawers 'children)))))
12413 (set-window-configuration org-log-note-window-configuration)
12414 (with-current-buffer (marker-buffer org-log-note-return-to)
12415 (goto-char org-log-note-return-to))
12416 (move-marker org-log-note-return-to nil)
12417 (and org-log-post-message (message "%s" org-log-post-message)))
12419 (defun org-remove-empty-drawer-at (drawer pos)
12420 "Remove an empty drawer DRAWER at position POS.
12421 POS may also be a marker."
12422 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12423 (save-excursion
12424 (save-restriction
12425 (widen)
12426 (goto-char pos)
12427 (if (org-in-regexp
12428 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12429 (replace-match ""))))))
12431 (defun org-sparse-tree (&optional arg)
12432 "Create a sparse tree, prompt for the details.
12433 This command can create sparse trees. You first need to select the type
12434 of match used to create the tree:
12436 t Show all TODO entries.
12437 T Show entries with a specific TODO keyword.
12438 m Show entries selected by a tags/property match.
12439 p Enter a property name and its value (both with completion on existing
12440 names/values) and show entries with that property.
12441 r Show entries matching a regular expression (`/' can be used as well)
12442 d Show deadlines due within `org-deadline-warning-days'.
12443 b Show deadlines and scheduled items before a date.
12444 a Show deadlines and scheduled items after a date."
12445 (interactive "P")
12446 (let (ans kwd value)
12447 (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")
12448 (setq ans (read-char-exclusive))
12449 (cond
12450 ((equal ans ?d)
12451 (call-interactively 'org-check-deadlines))
12452 ((equal ans ?b)
12453 (call-interactively 'org-check-before-date))
12454 ((equal ans ?a)
12455 (call-interactively 'org-check-after-date))
12456 ((equal ans ?D)
12457 (call-interactively 'org-check-dates-range))
12458 ((equal ans ?t)
12459 (org-show-todo-tree nil))
12460 ((equal ans ?T)
12461 (org-show-todo-tree '(4)))
12462 ((member ans '(?T ?m))
12463 (call-interactively 'org-match-sparse-tree))
12464 ((member ans '(?p ?P))
12465 (setq kwd (org-icompleting-read "Property: "
12466 (mapcar 'list (org-buffer-property-keys))))
12467 (setq value (org-icompleting-read "Value: "
12468 (mapcar 'list (org-property-values kwd))))
12469 (unless (string-match "\\`{.*}\\'" value)
12470 (setq value (concat "\"" value "\"")))
12471 (org-match-sparse-tree arg (concat kwd "=" value)))
12472 ((member ans '(?r ?R ?/))
12473 (call-interactively 'org-occur))
12474 (t (error "No such sparse tree command \"%c\"" ans)))))
12476 (defvar org-occur-highlights nil
12477 "List of overlays used for occur matches.")
12478 (make-variable-buffer-local 'org-occur-highlights)
12479 (defvar org-occur-parameters nil
12480 "Parameters of the active org-occur calls.
12481 This is a list, each call to org-occur pushes as cons cell,
12482 containing the regular expression and the callback, onto the list.
12483 The list can contain several entries if `org-occur' has been called
12484 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12485 will only contain one set of parameters. When the highlights are
12486 removed (for example with `C-c C-c', or with the next edit (depending
12487 on `org-remove-highlights-with-change'), this variable is emptied
12488 as well.")
12489 (make-variable-buffer-local 'org-occur-parameters)
12491 (defun org-occur (regexp &optional keep-previous callback)
12492 "Make a compact tree which shows all matches of REGEXP.
12493 The tree will show the lines where the regexp matches, and all higher
12494 headlines above the match. It will also show the heading after the match,
12495 to make sure editing the matching entry is easy.
12496 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12497 call to `org-occur' will be kept, to allow stacking of calls to this
12498 command.
12499 If CALLBACK is non-nil, it is a function which is called to confirm
12500 that the match should indeed be shown."
12501 (interactive "sRegexp: \nP")
12502 (when (equal regexp "")
12503 (error "Regexp cannot be empty"))
12504 (unless keep-previous
12505 (org-remove-occur-highlights nil nil t))
12506 (push (cons regexp callback) org-occur-parameters)
12507 (let ((cnt 0))
12508 (save-excursion
12509 (goto-char (point-min))
12510 (if (or (not keep-previous) ; do not want to keep
12511 (not org-occur-highlights)) ; no previous matches
12512 ;; hide everything
12513 (org-overview))
12514 (while (re-search-forward regexp nil t)
12515 (when (or (not callback)
12516 (save-match-data (funcall callback)))
12517 (setq cnt (1+ cnt))
12518 (when org-highlight-sparse-tree-matches
12519 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12520 (org-show-context 'occur-tree))))
12521 (when org-remove-highlights-with-change
12522 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12523 nil 'local))
12524 (unless org-sparse-tree-open-archived-trees
12525 (org-hide-archived-subtrees (point-min) (point-max)))
12526 (run-hooks 'org-occur-hook)
12527 (if (org-called-interactively-p 'interactive)
12528 (message "%d match(es) for regexp %s" cnt regexp))
12529 cnt))
12531 (defun org-occur-next-match (&optional n reset)
12532 "Function for `next-error-function' to find sparse tree matches.
12533 N is the number of matches to move, when negative move backwards.
12534 RESET is entirely ignored - this function always goes back to the
12535 starting point when no match is found."
12536 (let* ((limit (if (< n 0) (point-min) (point-max)))
12537 (search-func (if (< n 0)
12538 'previous-single-char-property-change
12539 'next-single-char-property-change))
12540 (n (abs n))
12541 (pos (point))
12543 (catch 'exit
12544 (while (setq p1 (funcall search-func (point) 'org-type))
12545 (when (equal p1 limit)
12546 (goto-char pos)
12547 (error "No more matches"))
12548 (when (equal (get-char-property p1 'org-type) 'org-occur)
12549 (setq n (1- n))
12550 (when (= n 0)
12551 (goto-char p1)
12552 (throw 'exit (point))))
12553 (goto-char p1))
12554 (goto-char p1)
12555 (error "No more matches"))))
12557 (defun org-show-context (&optional key)
12558 "Make sure point and context are visible.
12559 How much context is shown depends upon the variables
12560 `org-show-hierarchy-above', `org-show-following-heading',
12561 `org-show-entry-below' and `org-show-siblings'."
12562 (let ((heading-p (org-at-heading-p t))
12563 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12564 (following-p (org-get-alist-option org-show-following-heading key))
12565 (entry-p (org-get-alist-option org-show-entry-below key))
12566 (siblings-p (org-get-alist-option org-show-siblings key)))
12567 (catch 'exit
12568 ;; Show heading or entry text
12569 (if (and heading-p (not entry-p))
12570 (org-flag-heading nil) ; only show the heading
12571 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12572 (org-show-hidden-entry))) ; show entire entry
12573 (when following-p
12574 ;; Show next sibling, or heading below text
12575 (save-excursion
12576 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12577 (org-flag-heading nil))))
12578 (when siblings-p (org-show-siblings))
12579 (when hierarchy-p
12580 ;; show all higher headings, possibly with siblings
12581 (save-excursion
12582 (while (and (condition-case nil
12583 (progn (org-up-heading-all 1) t)
12584 (error nil))
12585 (not (bobp)))
12586 (org-flag-heading nil)
12587 (when siblings-p (org-show-siblings))))))))
12589 (defvar org-reveal-start-hook nil
12590 "Hook run before revealing a location.")
12592 (defun org-reveal (&optional siblings)
12593 "Show current entry, hierarchy above it, and the following headline.
12594 This can be used to show a consistent set of context around locations
12595 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12596 not t for the search context.
12598 With optional argument SIBLINGS, on each level of the hierarchy all
12599 siblings are shown. This repairs the tree structure to what it would
12600 look like when opened with hierarchical calls to `org-cycle'.
12601 With double optional argument \\[universal-argument] \\[universal-argument], \
12602 go to the parent and show the
12603 entire tree."
12604 (interactive "P")
12605 (run-hooks 'org-reveal-start-hook)
12606 (let ((org-show-hierarchy-above t)
12607 (org-show-following-heading t)
12608 (org-show-siblings (if siblings t org-show-siblings)))
12609 (org-show-context nil))
12610 (when (equal siblings '(16))
12611 (save-excursion
12612 (when (org-up-heading-safe)
12613 (org-show-subtree)
12614 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12616 (defun org-highlight-new-match (beg end)
12617 "Highlight from BEG to END and mark the highlight is an occur headline."
12618 (let ((ov (make-overlay beg end)))
12619 (overlay-put ov 'face 'secondary-selection)
12620 (overlay-put ov 'org-type 'org-occur)
12621 (push ov org-occur-highlights)))
12623 (defun org-remove-occur-highlights (&optional beg end noremove)
12624 "Remove the occur highlights from the buffer.
12625 BEG and END are ignored. If NOREMOVE is nil, remove this function
12626 from the `before-change-functions' in the current buffer."
12627 (interactive)
12628 (unless org-inhibit-highlight-removal
12629 (mapc 'delete-overlay org-occur-highlights)
12630 (setq org-occur-highlights nil)
12631 (setq org-occur-parameters nil)
12632 (unless noremove
12633 (remove-hook 'before-change-functions
12634 'org-remove-occur-highlights 'local))))
12636 ;;;; Priorities
12638 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12639 "Regular expression matching the priority indicator.")
12641 (defvar org-remove-priority-next-time nil)
12643 (defun org-priority-up ()
12644 "Increase the priority of the current item."
12645 (interactive)
12646 (org-priority 'up))
12648 (defun org-priority-down ()
12649 "Decrease the priority of the current item."
12650 (interactive)
12651 (org-priority 'down))
12653 (defun org-priority (&optional action)
12654 "Change the priority of an item by ARG.
12655 ACTION can be `set', `up', `down', or a character."
12656 (interactive)
12657 (unless org-enable-priority-commands
12658 (error "Priority commands are disabled"))
12659 (setq action (or action 'set))
12660 (let (current new news have remove)
12661 (save-excursion
12662 (org-back-to-heading t)
12663 (if (looking-at org-priority-regexp)
12664 (setq current (string-to-char (match-string 2))
12665 have t))
12666 (cond
12667 ((eq action 'remove)
12668 (setq remove t new ?\ ))
12669 ((or (eq action 'set)
12670 (if (featurep 'xemacs) (characterp action) (integerp action)))
12671 (if (not (eq action 'set))
12672 (setq new action)
12673 (message "Priority %c-%c, SPC to remove: "
12674 org-highest-priority org-lowest-priority)
12675 (save-match-data
12676 (setq new (read-char-exclusive))))
12677 (if (and (= (upcase org-highest-priority) org-highest-priority)
12678 (= (upcase org-lowest-priority) org-lowest-priority))
12679 (setq new (upcase new)))
12680 (cond ((equal new ?\ ) (setq remove t))
12681 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12682 (error "Priority must be between `%c' and `%c'"
12683 org-highest-priority org-lowest-priority))))
12684 ((eq action 'up)
12685 (setq new (if have
12686 (1- current) ; normal cycling
12687 ;; last priority was empty
12688 (if (eq last-command this-command)
12689 org-lowest-priority ; wrap around empty to lowest
12690 ;; default
12691 (if org-priority-start-cycle-with-default
12692 org-default-priority
12693 (1- org-default-priority))))))
12694 ((eq action 'down)
12695 (setq new (if have
12696 (1+ current) ; normal cycling
12697 ;; last priority was empty
12698 (if (eq last-command this-command)
12699 org-highest-priority ; wrap around empty to highest
12700 ;; default
12701 (if org-priority-start-cycle-with-default
12702 org-default-priority
12703 (1+ org-default-priority))))))
12704 (t (error "Invalid action")))
12705 (if (or (< (upcase new) org-highest-priority)
12706 (> (upcase new) org-lowest-priority))
12707 (if (and (memq action '(up down))
12708 (not have) (not (eq last-command this-command)))
12709 ;; `new' is from default priority
12710 (error
12711 "The default can not be set, see `org-default-priority' why")
12712 ;; normal cycling: `new' is beyond highest/lowest priority
12713 ;; and is wrapped around to the empty priority
12714 (setq remove t)))
12715 (setq news (format "%c" new))
12716 (if have
12717 (if remove
12718 (replace-match "" t t nil 1)
12719 (replace-match news t t nil 2))
12720 (if remove
12721 (error "No priority cookie found in line")
12722 (let ((case-fold-search nil))
12723 (looking-at org-todo-line-regexp))
12724 (if (match-end 2)
12725 (progn
12726 (goto-char (match-end 2))
12727 (insert " [#" news "]"))
12728 (goto-char (match-beginning 3))
12729 (insert "[#" news "] "))))
12730 (org-preserve-lc (org-set-tags nil 'align)))
12731 (if remove
12732 (message "Priority removed")
12733 (message "Priority of current item set to %s" news))))
12735 (defun org-get-priority (s)
12736 "Find priority cookie and return priority."
12737 (if (functionp org-get-priority-function)
12738 (funcall org-get-priority-function)
12739 (save-match-data
12740 (if (not (string-match org-priority-regexp s))
12741 (* 1000 (- org-lowest-priority org-default-priority))
12742 (* 1000 (- org-lowest-priority
12743 (string-to-char (match-string 2 s))))))))
12745 ;;;; Tags
12747 (defvar org-agenda-archives-mode)
12748 (defvar org-map-continue-from nil
12749 "Position from where mapping should continue.
12750 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12752 (defvar org-scanner-tags nil
12753 "The current tag list while the tags scanner is running.")
12754 (defvar org-trust-scanner-tags nil
12755 "Should `org-get-tags-at' use the tags for the scanner.
12756 This is for internal dynamical scoping only.
12757 When this is non-nil, the function `org-get-tags-at' will return the value
12758 of `org-scanner-tags' instead of building the list by itself. This
12759 can lead to large speed-ups when the tags scanner is used in a file with
12760 many entries, and when the list of tags is retrieved, for example to
12761 obtain a list of properties. Building the tags list for each entry in such
12762 a file becomes an N^2 operation - but with this variable set, it scales
12763 as N.")
12765 (defun org-scan-tags (action matcher &optional todo-only start-level)
12766 "Scan headline tags with inheritance and produce output ACTION.
12768 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12769 or `agenda' to produce an entry list for an agenda view. It can also be
12770 a Lisp form or a function that should be called at each matched headline, in
12771 this case the return value is a list of all return values from these calls.
12773 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12774 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12775 only lines with a TODO keyword are included in the output.
12777 START-LEVEL can be a string with asterisks, reducing the scope to
12778 headlines matching this string."
12779 (require 'org-agenda)
12780 (let* ((re (concat "^"
12781 (if start-level
12782 ;; Get the correct level to match
12783 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12784 org-outline-regexp)
12785 " *\\(\\<\\("
12786 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12787 (org-re
12788 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12789 (props (list 'face 'default
12790 'done-face 'org-agenda-done
12791 'undone-face 'default
12792 'mouse-face 'highlight
12793 'org-not-done-regexp org-not-done-regexp
12794 'org-todo-regexp org-todo-regexp
12795 'org-complex-heading-regexp org-complex-heading-regexp
12796 'help-echo
12797 (format "mouse-2 or RET jump to org file %s"
12798 (abbreviate-file-name
12799 (or (buffer-file-name (buffer-base-buffer))
12800 (buffer-name (buffer-base-buffer)))))))
12801 (case-fold-search nil)
12802 (org-map-continue-from nil)
12803 lspos tags tags-list
12804 (tags-alist (list (cons 0 org-file-tags)))
12805 (llast 0) rtn rtn1 level category i txt
12806 todo marker entry priority)
12807 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12808 (setq action (list 'lambda nil action)))
12809 (save-excursion
12810 (goto-char (point-min))
12811 (when (eq action 'sparse-tree)
12812 (org-overview)
12813 (org-remove-occur-highlights))
12814 (while (re-search-forward re nil t)
12815 (setq org-map-continue-from nil)
12816 (catch :skip
12817 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12818 tags (if (match-end 4) (org-match-string-no-properties 4)))
12819 (goto-char (setq lspos (match-beginning 0)))
12820 (setq level (org-reduced-level (funcall outline-level))
12821 category (org-get-category))
12822 (setq i llast llast level)
12823 ;; remove tag lists from same and sublevels
12824 (while (>= i level)
12825 (when (setq entry (assoc i tags-alist))
12826 (setq tags-alist (delete entry tags-alist)))
12827 (setq i (1- i)))
12828 ;; add the next tags
12829 (when tags
12830 (setq tags (org-split-string tags ":")
12831 tags-alist
12832 (cons (cons level tags) tags-alist)))
12833 ;; compile tags for current headline
12834 (setq tags-list
12835 (if org-use-tag-inheritance
12836 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12837 tags)
12838 org-scanner-tags tags-list)
12839 (when org-use-tag-inheritance
12840 (setcdr (car tags-alist)
12841 (mapcar (lambda (x)
12842 (setq x (copy-sequence x))
12843 (org-add-prop-inherited x))
12844 (cdar tags-alist))))
12845 (when (and tags org-use-tag-inheritance
12846 (or (not (eq t org-use-tag-inheritance))
12847 org-tags-exclude-from-inheritance))
12848 ;; selective inheritance, remove uninherited ones
12849 (setcdr (car tags-alist)
12850 (org-remove-uninherited-tags (cdar tags-alist))))
12851 (when (and
12853 ;; eval matcher only when the todo condition is OK
12854 (and (or (not todo-only) (member todo org-not-done-keywords))
12855 (let ((case-fold-search t)) (eval matcher)))
12857 ;; Call the skipper, but return t if it does not skip,
12858 ;; so that the `and' form continues evaluating
12859 (progn
12860 (unless (eq action 'sparse-tree) (org-agenda-skip))
12863 ;; Check if timestamps are deselecting this entry
12864 (or (not todo-only)
12865 (and (member todo org-not-done-keywords)
12866 (or (not org-agenda-tags-todo-honor-ignore-options)
12867 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12869 ;; Extra check for the archive tag
12870 ;; FIXME: Does the skipper already do this????
12872 (not (member org-archive-tag tags-list))
12873 ;; we have an archive tag, should we use this anyway?
12874 (or (not org-agenda-skip-archived-trees)
12875 (and (eq action 'agenda) org-agenda-archives-mode))))
12877 ;; select this headline
12879 (cond
12880 ((eq action 'sparse-tree)
12881 (and org-highlight-sparse-tree-matches
12882 (org-get-heading) (match-end 0)
12883 (org-highlight-new-match
12884 (match-beginning 1) (match-end 1)))
12885 (org-show-context 'tags-tree))
12886 ((eq action 'agenda)
12887 (setq txt (org-agenda-format-item
12889 (concat
12890 (if (eq org-tags-match-list-sublevels 'indented)
12891 (make-string (1- level) ?.) "")
12892 (org-get-heading))
12893 category
12894 tags-list
12896 priority (org-get-priority txt))
12897 (goto-char lspos)
12898 (setq marker (org-agenda-new-marker))
12899 (org-add-props txt props
12900 'org-marker marker 'org-hd-marker marker 'org-category category
12901 'todo-state todo
12902 'priority priority 'type "tagsmatch")
12903 (push txt rtn))
12904 ((functionp action)
12905 (setq org-map-continue-from nil)
12906 (save-excursion
12907 (setq rtn1 (funcall action))
12908 (push rtn1 rtn)))
12909 (t (error "Invalid action")))
12911 ;; if we are to skip sublevels, jump to end of subtree
12912 (unless org-tags-match-list-sublevels
12913 (org-end-of-subtree t)
12914 (backward-char 1))))
12915 ;; Get the correct position from where to continue
12916 (if org-map-continue-from
12917 (goto-char org-map-continue-from)
12918 (and (= (point) lspos) (end-of-line 1)))))
12919 (when (and (eq action 'sparse-tree)
12920 (not org-sparse-tree-open-archived-trees))
12921 (org-hide-archived-subtrees (point-min) (point-max)))
12922 (nreverse rtn)))
12924 (defun org-remove-uninherited-tags (tags)
12925 "Remove all tags that are not inherited from the list TAGS."
12926 (cond
12927 ((eq org-use-tag-inheritance t)
12928 (if org-tags-exclude-from-inheritance
12929 (org-delete-all org-tags-exclude-from-inheritance tags)
12930 tags))
12931 ((not org-use-tag-inheritance) nil)
12932 ((stringp org-use-tag-inheritance)
12933 (delq nil (mapcar
12934 (lambda (x)
12935 (if (and (string-match org-use-tag-inheritance x)
12936 (not (member x org-tags-exclude-from-inheritance)))
12937 x nil))
12938 tags)))
12939 ((listp org-use-tag-inheritance)
12940 (delq nil (mapcar
12941 (lambda (x)
12942 (if (member x org-use-tag-inheritance) x nil))
12943 tags)))))
12945 (defvar todo-only) ;; dynamically scoped
12947 (defun org-match-sparse-tree (&optional todo-only match)
12948 "Create a sparse tree according to tags string MATCH.
12949 MATCH can contain positive and negative selection of tags, like
12950 \"+WORK+URGENT-WITHBOSS\".
12951 If optional argument TODO-ONLY is non-nil, only select lines that are
12952 also TODO lines."
12953 (interactive "P")
12954 (org-prepare-agenda-buffers (list (current-buffer)))
12955 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12957 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12959 (defvar org-cached-props nil)
12960 (defun org-cached-entry-get (pom property)
12961 (if (or (eq t org-use-property-inheritance)
12962 (and (stringp org-use-property-inheritance)
12963 (string-match org-use-property-inheritance property))
12964 (and (listp org-use-property-inheritance)
12965 (member property org-use-property-inheritance)))
12966 ;; Caching is not possible, check it directly
12967 (org-entry-get pom property 'inherit)
12968 ;; Get all properties, so that we can do complicated checks easily
12969 (cdr (assoc property (or org-cached-props
12970 (setq org-cached-props
12971 (org-entry-properties pom)))))))
12973 (defun org-global-tags-completion-table (&optional files)
12974 "Return the list of all tags in all agenda buffer/files.
12975 Optional FILES argument is a list of files to which can be used
12976 instead of the agenda files."
12977 (save-excursion
12978 (org-uniquify
12979 (delq nil
12980 (apply 'append
12981 (mapcar
12982 (lambda (file)
12983 (set-buffer (find-file-noselect file))
12984 (append (org-get-buffer-tags)
12985 (mapcar (lambda (x) (if (stringp (car-safe x))
12986 (list (car-safe x)) nil))
12987 org-tag-alist)))
12988 (if (and files (car files))
12989 files
12990 (org-agenda-files))))))))
12992 (defun org-make-tags-matcher (match)
12993 "Create the TAGS/TODO matcher form for the selection string MATCH."
12994 ;; todo-only is scoped dynamically into this function, and the function
12995 ;; may change it if the matcher asks for it.
12996 (unless match
12997 ;; Get a new match request, with completion
12998 (let ((org-last-tags-completion-table
12999 (org-global-tags-completion-table)))
13000 (setq match (org-completing-read-no-i
13001 "Match: " 'org-tags-completion-function nil nil nil
13002 'org-tags-history))))
13004 ;; Parse the string and create a lisp form
13005 (let ((match0 match)
13006 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13007 minus tag mm
13008 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13009 orterms term orlist re-p str-p level-p level-op time-p
13010 prop-p pn pv po gv rest)
13011 (if (string-match "/+" match)
13012 ;; match contains also a todo-matching request
13013 (progn
13014 (setq tagsmatch (substring match 0 (match-beginning 0))
13015 todomatch (substring match (match-end 0)))
13016 (if (string-match "^!" todomatch)
13017 (setq todo-only t todomatch (substring todomatch 1)))
13018 (if (string-match "^\\s-*$" todomatch)
13019 (setq todomatch nil)))
13020 ;; only matching tags
13021 (setq tagsmatch match todomatch nil))
13023 ;; Make the tags matcher
13024 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13025 (setq tagsmatcher t)
13026 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13027 (while (setq term (pop orterms))
13028 (while (and (equal (substring term -1) "\\") orterms)
13029 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13030 (while (string-match re term)
13031 (setq rest (substring term (match-end 0))
13032 minus (and (match-end 1)
13033 (equal (match-string 1 term) "-"))
13034 tag (save-match-data (replace-regexp-in-string
13035 "\\\\-" "-"
13036 (match-string 2 term)))
13037 re-p (equal (string-to-char tag) ?{)
13038 level-p (match-end 4)
13039 prop-p (match-end 5)
13040 mm (cond
13041 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13042 (level-p
13043 (setq level-op (org-op-to-function (match-string 3 term)))
13044 `(,level-op level ,(string-to-number
13045 (match-string 4 term))))
13046 (prop-p
13047 (setq pn (match-string 5 term)
13048 po (match-string 6 term)
13049 pv (match-string 7 term)
13050 re-p (equal (string-to-char pv) ?{)
13051 str-p (equal (string-to-char pv) ?\")
13052 time-p (save-match-data
13053 (string-match "^\"[[<].*[]>]\"$" pv))
13054 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13055 (if time-p (setq pv (org-matcher-time pv)))
13056 (setq po (org-op-to-function po (if time-p 'time str-p)))
13057 (cond
13058 ((equal pn "CATEGORY")
13059 (setq gv '(get-text-property (point) 'org-category)))
13060 ((equal pn "TODO")
13061 (setq gv 'todo))
13063 (setq gv `(org-cached-entry-get nil ,pn))))
13064 (if re-p
13065 (if (eq po 'org<>)
13066 `(not (string-match ,pv (or ,gv "")))
13067 `(string-match ,pv (or ,gv "")))
13068 (if str-p
13069 `(,po (or ,gv "") ,pv)
13070 `(,po (string-to-number (or ,gv ""))
13071 ,(string-to-number pv) ))))
13072 (t `(member ,tag tags-list)))
13073 mm (if minus (list 'not mm) mm)
13074 term rest)
13075 (push mm tagsmatcher))
13076 (push (if (> (length tagsmatcher) 1)
13077 (cons 'and tagsmatcher)
13078 (car tagsmatcher))
13079 orlist)
13080 (setq tagsmatcher nil))
13081 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13082 (setq tagsmatcher
13083 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13084 ;; Make the todo matcher
13085 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13086 (setq todomatcher t)
13087 (setq orterms (org-split-string todomatch "|") orlist nil)
13088 (while (setq term (pop orterms))
13089 (while (string-match re term)
13090 (setq minus (and (match-end 1)
13091 (equal (match-string 1 term) "-"))
13092 kwd (match-string 2 term)
13093 re-p (equal (string-to-char kwd) ?{)
13094 term (substring term (match-end 0))
13095 mm (if re-p
13096 `(string-match ,(substring kwd 1 -1) todo)
13097 (list 'equal 'todo kwd))
13098 mm (if minus (list 'not mm) mm))
13099 (push mm todomatcher))
13100 (push (if (> (length todomatcher) 1)
13101 (cons 'and todomatcher)
13102 (car todomatcher))
13103 orlist)
13104 (setq todomatcher nil))
13105 (setq todomatcher (if (> (length orlist) 1)
13106 (cons 'or orlist) (car orlist))))
13108 ;; Return the string and lisp forms of the matcher
13109 (setq matcher (if todomatcher
13110 (list 'and tagsmatcher todomatcher)
13111 tagsmatcher))
13112 (cons match0 matcher)))
13114 (defun org-op-to-function (op &optional stringp)
13115 "Turn an operator into the appropriate function."
13116 (setq op
13117 (cond
13118 ((equal op "<" ) '(< string< org-time<))
13119 ((equal op ">" ) '(> org-string> org-time>))
13120 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13121 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13122 ((member op '("=" "==")) '(= string= org-time=))
13123 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13124 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13126 (defun org<> (a b) (not (= a b)))
13127 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13128 (defun org-string>= (a b) (not (string< a b)))
13129 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13130 (defun org-string<> (a b) (not (string= a b)))
13131 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13132 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13133 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13134 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13135 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13136 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13137 (defun org-2ft (s)
13138 "Convert S to a floating point time.
13139 If S is already a number, just return it. If it is a string, parse
13140 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13141 (cond
13142 ((numberp s) s)
13143 ((stringp s)
13144 (condition-case nil
13145 (float-time (apply 'encode-time (org-parse-time-string s)))
13146 (error 0.)))
13147 (t 0.)))
13149 (defun org-time-today ()
13150 "Time in seconds today at 0:00.
13151 Returns the float number of seconds since the beginning of the
13152 epoch to the beginning of today (00:00)."
13153 (float-time (apply 'encode-time
13154 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13156 (defun org-matcher-time (s)
13157 "Interpret a time comparison value."
13158 (save-match-data
13159 (cond
13160 ((string= s "<now>") (float-time))
13161 ((string= s "<today>") (org-time-today))
13162 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13163 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13164 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13165 (+ (org-time-today)
13166 (* (string-to-number (match-string 1 s))
13167 (cdr (assoc (match-string 2 s)
13168 '(("d" . 86400.0) ("w" . 604800.0)
13169 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13170 (t (org-2ft s)))))
13172 (defun org-match-any-p (re list)
13173 "Does re match any element of list?"
13174 (setq list (mapcar (lambda (x) (string-match re x)) list))
13175 (delq nil list))
13177 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13178 (defvar org-tags-overlay (make-overlay 1 1))
13179 (org-detach-overlay org-tags-overlay)
13181 (defun org-get-local-tags-at (&optional pos)
13182 "Get a list of tags defined in the current headline."
13183 (org-get-tags-at pos 'local))
13185 (defun org-get-local-tags ()
13186 "Get a list of tags defined in the current headline."
13187 (org-get-tags-at nil 'local))
13189 (defun org-get-tags-at (&optional pos local)
13190 "Get a list of all headline tags applicable at POS.
13191 POS defaults to point. If tags are inherited, the list contains
13192 the targets in the same sequence as the headlines appear, i.e.
13193 the tags of the current headline come last.
13194 When LOCAL is non-nil, only return tags from the current headline,
13195 ignore inherited ones."
13196 (interactive)
13197 (if (and org-trust-scanner-tags
13198 (or (not pos) (equal pos (point)))
13199 (not local))
13200 org-scanner-tags
13201 (let (tags ltags lastpos parent)
13202 (save-excursion
13203 (save-restriction
13204 (widen)
13205 (goto-char (or pos (point)))
13206 (save-match-data
13207 (catch 'done
13208 (condition-case nil
13209 (progn
13210 (org-back-to-heading t)
13211 (while (not (equal lastpos (point)))
13212 (setq lastpos (point))
13213 (when (looking-at
13214 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13215 (setq ltags (org-split-string
13216 (org-match-string-no-properties 1) ":"))
13217 (when parent
13218 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13219 (setq tags (append
13220 (if parent
13221 (org-remove-uninherited-tags ltags)
13222 ltags)
13223 tags)))
13224 (or org-use-tag-inheritance (throw 'done t))
13225 (if local (throw 'done t))
13226 (or (org-up-heading-safe) (error nil))
13227 (setq parent t)))
13228 (error nil)))))
13229 (if local
13230 tags
13231 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13233 (defun org-add-prop-inherited (s)
13234 (add-text-properties 0 (length s) '(inherited t) s)
13237 (defun org-toggle-tag (tag &optional onoff)
13238 "Toggle the tag TAG for the current line.
13239 If ONOFF is `on' or `off', don't toggle but set to this state."
13240 (let (res current)
13241 (save-excursion
13242 (org-back-to-heading t)
13243 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13244 (point-at-eol) t)
13245 (progn
13246 (setq current (match-string 1))
13247 (replace-match ""))
13248 (setq current ""))
13249 (setq current (nreverse (org-split-string current ":")))
13250 (cond
13251 ((eq onoff 'on)
13252 (setq res t)
13253 (or (member tag current) (push tag current)))
13254 ((eq onoff 'off)
13255 (or (not (member tag current)) (setq current (delete tag current))))
13256 (t (if (member tag current)
13257 (setq current (delete tag current))
13258 (setq res t)
13259 (push tag current))))
13260 (end-of-line 1)
13261 (if current
13262 (progn
13263 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13264 (org-set-tags nil t))
13265 (delete-horizontal-space))
13266 (run-hooks 'org-after-tags-change-hook))
13267 res))
13269 (defun org-align-tags-here (to-col)
13270 ;; Assumes that this is a headline
13271 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13272 (beginning-of-line 1)
13273 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13274 (< pos (match-beginning 2)))
13275 (progn
13276 (setq tags-l (- (match-end 2) (match-beginning 2)))
13277 (goto-char (match-beginning 1))
13278 (insert " ")
13279 (delete-region (point) (1+ (match-beginning 2)))
13280 (setq ncol (max (current-column)
13281 (1+ col)
13282 (if (> to-col 0)
13283 to-col
13284 (- (abs to-col) tags-l))))
13285 (setq p (point))
13286 (insert (make-string (- ncol (current-column)) ?\ ))
13287 (setq ncol (current-column))
13288 (when indent-tabs-mode (tabify p (point-at-eol)))
13289 (org-move-to-column (min ncol col) t))
13290 (goto-char pos))))
13292 (defun org-set-tags-command (&optional arg just-align)
13293 "Call the set-tags command for the current entry."
13294 (interactive "P")
13295 (if (org-at-heading-p)
13296 (org-set-tags arg just-align)
13297 (save-excursion
13298 (org-back-to-heading t)
13299 (org-set-tags arg just-align))))
13301 (defun org-set-tags-to (data)
13302 "Set the tags of the current entry to DATA, replacing the current tags.
13303 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13304 If DATA is nil or the empty string, any tags will be removed."
13305 (interactive "sTags: ")
13306 (setq data
13307 (cond
13308 ((eq data nil) "")
13309 ((equal data "") "")
13310 ((stringp data)
13311 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13312 ":"))
13313 ((listp data)
13314 (concat ":" (mapconcat 'identity data ":") ":"))
13315 (t nil)))
13316 (when data
13317 (save-excursion
13318 (org-back-to-heading t)
13319 (when (looking-at org-complex-heading-regexp)
13320 (if (match-end 5)
13321 (progn
13322 (goto-char (match-beginning 5))
13323 (insert data)
13324 (delete-region (point) (point-at-eol))
13325 (org-set-tags nil 'align))
13326 (goto-char (point-at-eol))
13327 (insert " " data)
13328 (org-set-tags nil 'align)))
13329 (beginning-of-line 1)
13330 (if (looking-at ".*?\\([ \t]+\\)$")
13331 (delete-region (match-beginning 1) (match-end 1))))))
13333 (defun org-align-all-tags ()
13334 "Align the tags i all headings."
13335 (interactive)
13336 (save-excursion
13337 (or (ignore-errors (org-back-to-heading t))
13338 (outline-next-heading))
13339 (if (org-at-heading-p)
13340 (org-set-tags t)
13341 (message "No headings"))))
13343 (defvar org-indent-indentation-per-level)
13344 (defun org-set-tags (&optional arg just-align)
13345 "Set the tags for the current headline.
13346 With prefix ARG, realign all tags in headings in the current buffer."
13347 (interactive "P")
13348 (let* ((re org-outline-regexp-bol)
13349 (current (org-get-tags-string))
13350 (col (current-column))
13351 (org-setting-tags t)
13352 table current-tags inherited-tags ; computed below when needed
13353 tags p0 c0 c1 rpl di tc level)
13354 (if arg
13355 (save-excursion
13356 (goto-char (point-min))
13357 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13358 (while (re-search-forward re nil t)
13359 (org-set-tags nil t)
13360 (end-of-line 1)))
13361 (message "All tags realigned to column %d" org-tags-column))
13362 (if just-align
13363 (setq tags current)
13364 ;; Get a new set of tags from the user
13365 (save-excursion
13366 (setq table (append org-tag-persistent-alist
13367 (or org-tag-alist (org-get-buffer-tags))
13368 (and
13369 org-complete-tags-always-offer-all-agenda-tags
13370 (org-global-tags-completion-table
13371 (org-agenda-files))))
13372 org-last-tags-completion-table table
13373 current-tags (org-split-string current ":")
13374 inherited-tags (nreverse
13375 (nthcdr (length current-tags)
13376 (nreverse (org-get-tags-at))))
13377 tags
13378 (if (or (eq t org-use-fast-tag-selection)
13379 (and org-use-fast-tag-selection
13380 (delq nil (mapcar 'cdr table))))
13381 (org-fast-tag-selection
13382 current-tags inherited-tags table
13383 (if org-fast-tag-selection-include-todo
13384 org-todo-key-alist))
13385 (let ((org-add-colon-after-tag-completion t))
13386 (org-trim
13387 (org-icompleting-read "Tags: "
13388 'org-tags-completion-function
13389 nil nil current 'org-tags-history))))))
13390 (while (string-match "[-+&]+" tags)
13391 ;; No boolean logic, just a list
13392 (setq tags (replace-match ":" t t tags))))
13394 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13396 (if org-tags-sort-function
13397 (setq tags (mapconcat 'identity
13398 (sort (org-split-string
13399 tags (org-re "[^[:alnum:]_@#%]+"))
13400 org-tags-sort-function) ":")))
13402 (if (string-match "\\`[\t ]*\\'" tags)
13403 (setq tags "")
13404 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13405 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13407 ;; Insert new tags at the correct column
13408 (beginning-of-line 1)
13409 (setq level (or (and (looking-at org-outline-regexp)
13410 (- (match-end 0) (point) 1))
13412 (cond
13413 ((and (equal current "") (equal tags "")))
13414 ((re-search-forward
13415 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13416 (point-at-eol) t)
13417 (if (equal tags "")
13418 (setq rpl "")
13419 (goto-char (match-beginning 0))
13420 (setq c0 (current-column)
13421 ;; compute offset for the case of org-indent-mode active
13422 di (if org-indent-mode
13423 (* (1- org-indent-indentation-per-level) (1- level))
13425 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13426 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13427 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13428 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13429 (replace-match rpl t t)
13430 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13431 tags)
13432 (t (error "Tags alignment failed")))
13433 (org-move-to-column col)
13434 (unless just-align
13435 (run-hooks 'org-after-tags-change-hook)))))
13437 (defun org-change-tag-in-region (beg end tag off)
13438 "Add or remove TAG for each entry in the region.
13439 This works in the agenda, and also in an org-mode buffer."
13440 (interactive
13441 (list (region-beginning) (region-end)
13442 (let ((org-last-tags-completion-table
13443 (if (eq major-mode 'org-mode)
13444 (org-get-buffer-tags)
13445 (org-global-tags-completion-table))))
13446 (org-icompleting-read
13447 "Tag: " 'org-tags-completion-function nil nil nil
13448 'org-tags-history))
13449 (progn
13450 (message "[s]et or [r]emove? ")
13451 (equal (read-char-exclusive) ?r))))
13452 (if (fboundp 'deactivate-mark) (deactivate-mark))
13453 (let ((agendap (equal major-mode 'org-agenda-mode))
13454 l1 l2 m buf pos newhead (cnt 0))
13455 (goto-char end)
13456 (setq l2 (1- (org-current-line)))
13457 (goto-char beg)
13458 (setq l1 (org-current-line))
13459 (loop for l from l1 to l2 do
13460 (org-goto-line l)
13461 (setq m (get-text-property (point) 'org-hd-marker))
13462 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13463 (and agendap m))
13464 (setq buf (if agendap (marker-buffer m) (current-buffer))
13465 pos (if agendap m (point)))
13466 (with-current-buffer buf
13467 (save-excursion
13468 (save-restriction
13469 (goto-char pos)
13470 (setq cnt (1+ cnt))
13471 (org-toggle-tag tag (if off 'off 'on))
13472 (setq newhead (org-get-heading)))))
13473 (and agendap (org-agenda-change-all-lines newhead m))))
13474 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13476 (defun org-tags-completion-function (string predicate &optional flag)
13477 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13478 (confirm (lambda (x) (stringp (car x)))))
13479 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13480 (setq s1 (match-string 1 string)
13481 s2 (match-string 2 string))
13482 (setq s1 "" s2 string))
13483 (cond
13484 ((eq flag nil)
13485 ;; try completion
13486 (setq rtn (try-completion s2 ctable confirm))
13487 (if (stringp rtn)
13488 (setq rtn
13489 (concat s1 s2 (substring rtn (length s2))
13490 (if (and org-add-colon-after-tag-completion
13491 (assoc rtn ctable))
13492 ":" ""))))
13493 rtn)
13494 ((eq flag t)
13495 ;; all-completions
13496 (all-completions s2 ctable confirm)
13498 ((eq flag 'lambda)
13499 ;; exact match?
13500 (assoc s2 ctable)))
13503 (defun org-fast-tag-insert (kwd tags face &optional end)
13504 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13505 (insert (format "%-12s" (concat kwd ":"))
13506 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13507 (or end "")))
13509 (defun org-fast-tag-show-exit (flag)
13510 (save-excursion
13511 (org-goto-line 3)
13512 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13513 (replace-match ""))
13514 (when flag
13515 (end-of-line 1)
13516 (org-move-to-column (- (window-width) 19) t)
13517 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13519 (defun org-set-current-tags-overlay (current prefix)
13520 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13521 (if (featurep 'xemacs)
13522 (org-overlay-display org-tags-overlay (concat prefix s)
13523 'secondary-selection)
13524 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13525 (org-overlay-display org-tags-overlay (concat prefix s)))))
13527 (defvar org-last-tag-selection-key nil)
13528 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13529 "Fast tag selection with single keys.
13530 CURRENT is the current list of tags in the headline, INHERITED is the
13531 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13532 possibly with grouping information. TODO-TABLE is a similar table with
13533 TODO keywords, should these have keys assigned to them.
13534 If the keys are nil, a-z are automatically assigned.
13535 Returns the new tags string, or nil to not change the current settings."
13536 (let* ((fulltable (append table todo-table))
13537 (maxlen (apply 'max (mapcar
13538 (lambda (x)
13539 (if (stringp (car x)) (string-width (car x)) 0))
13540 fulltable)))
13541 (buf (current-buffer))
13542 (expert (eq org-fast-tag-selection-single-key 'expert))
13543 (buffer-tags nil)
13544 (fwidth (+ maxlen 3 1 3))
13545 (ncol (/ (- (window-width) 4) fwidth))
13546 (i-face 'org-done)
13547 (c-face 'org-todo)
13548 tg cnt e c char c1 c2 ntable tbl rtn
13549 ov-start ov-end ov-prefix
13550 (exit-after-next org-fast-tag-selection-single-key)
13551 (done-keywords org-done-keywords)
13552 groups ingroup)
13553 (save-excursion
13554 (beginning-of-line 1)
13555 (if (looking-at
13556 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13557 (setq ov-start (match-beginning 1)
13558 ov-end (match-end 1)
13559 ov-prefix "")
13560 (setq ov-start (1- (point-at-eol))
13561 ov-end (1+ ov-start))
13562 (skip-chars-forward "^\n\r")
13563 (setq ov-prefix
13564 (concat
13565 (buffer-substring (1- (point)) (point))
13566 (if (> (current-column) org-tags-column)
13568 (make-string (- org-tags-column (current-column)) ?\ ))))))
13569 (move-overlay org-tags-overlay ov-start ov-end)
13570 (save-window-excursion
13571 (if expert
13572 (set-buffer (get-buffer-create " *Org tags*"))
13573 (delete-other-windows)
13574 (split-window-vertically)
13575 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13576 (erase-buffer)
13577 (org-set-local 'org-done-keywords done-keywords)
13578 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13579 (org-fast-tag-insert "Current" current c-face "\n\n")
13580 (org-fast-tag-show-exit exit-after-next)
13581 (org-set-current-tags-overlay current ov-prefix)
13582 (setq tbl fulltable char ?a cnt 0)
13583 (while (setq e (pop tbl))
13584 (cond
13585 ((equal (car e) :startgroup)
13586 (push '() groups) (setq ingroup t)
13587 (when (not (= cnt 0))
13588 (setq cnt 0)
13589 (insert "\n"))
13590 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13591 ((equal (car e) :endgroup)
13592 (setq ingroup nil cnt 0)
13593 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13594 ((equal e '(:newline))
13595 (when (not (= cnt 0))
13596 (setq cnt 0)
13597 (insert "\n")
13598 (setq e (car tbl))
13599 (while (equal (car tbl) '(:newline))
13600 (insert "\n")
13601 (setq tbl (cdr tbl)))))
13603 (setq tg (copy-sequence (car e)) c2 nil)
13604 (if (cdr e)
13605 (setq c (cdr e))
13606 ;; automatically assign a character.
13607 (setq c1 (string-to-char
13608 (downcase (substring
13609 tg (if (= (string-to-char tg) ?@) 1 0)))))
13610 (if (or (rassoc c1 ntable) (rassoc c1 table))
13611 (while (or (rassoc char ntable) (rassoc char table))
13612 (setq char (1+ char)))
13613 (setq c2 c1))
13614 (setq c (or c2 char)))
13615 (if ingroup (push tg (car groups)))
13616 (setq tg (org-add-props tg nil 'face
13617 (cond
13618 ((not (assoc tg table))
13619 (org-get-todo-face tg))
13620 ((member tg current) c-face)
13621 ((member tg inherited) i-face)
13622 (t nil))))
13623 (if (and (= cnt 0) (not ingroup)) (insert " "))
13624 (insert "[" c "] " tg (make-string
13625 (- fwidth 4 (length tg)) ?\ ))
13626 (push (cons tg c) ntable)
13627 (when (= (setq cnt (1+ cnt)) ncol)
13628 (insert "\n")
13629 (if ingroup (insert " "))
13630 (setq cnt 0)))))
13631 (setq ntable (nreverse ntable))
13632 (insert "\n")
13633 (goto-char (point-min))
13634 (if (not expert) (org-fit-window-to-buffer))
13635 (setq rtn
13636 (catch 'exit
13637 (while t
13638 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13639 (if (not groups) "no " "")
13640 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13641 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13642 (setq org-last-tag-selection-key c)
13643 (cond
13644 ((= c ?\r) (throw 'exit t))
13645 ((= c ?!)
13646 (setq groups (not groups))
13647 (goto-char (point-min))
13648 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13649 ((= c ?\C-c)
13650 (if (not expert)
13651 (org-fast-tag-show-exit
13652 (setq exit-after-next (not exit-after-next)))
13653 (setq expert nil)
13654 (delete-other-windows)
13655 (set-window-buffer (split-window-vertically) " *Org tags*")
13656 (org-switch-to-buffer-other-window " *Org tags*")
13657 (org-fit-window-to-buffer)))
13658 ((or (= c ?\C-g)
13659 (and (= c ?q) (not (rassoc c ntable))))
13660 (org-detach-overlay org-tags-overlay)
13661 (setq quit-flag t))
13662 ((= c ?\ )
13663 (setq current nil)
13664 (if exit-after-next (setq exit-after-next 'now)))
13665 ((= c ?\t)
13666 (condition-case nil
13667 (setq tg (org-icompleting-read
13668 "Tag: "
13669 (or buffer-tags
13670 (with-current-buffer buf
13671 (org-get-buffer-tags)))))
13672 (quit (setq tg "")))
13673 (when (string-match "\\S-" tg)
13674 (add-to-list 'buffer-tags (list tg))
13675 (if (member tg current)
13676 (setq current (delete tg current))
13677 (push tg current)))
13678 (if exit-after-next (setq exit-after-next 'now)))
13679 ((setq e (rassoc c todo-table) tg (car e))
13680 (with-current-buffer buf
13681 (save-excursion (org-todo tg)))
13682 (if exit-after-next (setq exit-after-next 'now)))
13683 ((setq e (rassoc c ntable) tg (car e))
13684 (if (member tg current)
13685 (setq current (delete tg current))
13686 (loop for g in groups do
13687 (if (member tg g)
13688 (mapc (lambda (x)
13689 (setq current (delete x current)))
13690 g)))
13691 (push tg current))
13692 (if exit-after-next (setq exit-after-next 'now))))
13694 ;; Create a sorted list
13695 (setq current
13696 (sort current
13697 (lambda (a b)
13698 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13699 (if (eq exit-after-next 'now) (throw 'exit t))
13700 (goto-char (point-min))
13701 (beginning-of-line 2)
13702 (delete-region (point) (point-at-eol))
13703 (org-fast-tag-insert "Current" current c-face)
13704 (org-set-current-tags-overlay current ov-prefix)
13705 (while (re-search-forward
13706 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13707 (setq tg (match-string 1))
13708 (add-text-properties
13709 (match-beginning 1) (match-end 1)
13710 (list 'face
13711 (cond
13712 ((member tg current) c-face)
13713 ((member tg inherited) i-face)
13714 (t (get-text-property (match-beginning 1) 'face))))))
13715 (goto-char (point-min)))))
13716 (org-detach-overlay org-tags-overlay)
13717 (if rtn
13718 (mapconcat 'identity current ":")
13719 nil))))
13721 (defun org-get-tags-string ()
13722 "Get the TAGS string in the current headline."
13723 (unless (org-at-heading-p t)
13724 (error "Not on a heading"))
13725 (save-excursion
13726 (beginning-of-line 1)
13727 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13728 (org-match-string-no-properties 1)
13729 "")))
13731 (defun org-get-tags ()
13732 "Get the list of tags specified in the current headline."
13733 (org-split-string (org-get-tags-string) ":"))
13735 (defun org-get-buffer-tags ()
13736 "Get a table of all tags used in the buffer, for completion."
13737 (let (tags)
13738 (save-excursion
13739 (goto-char (point-min))
13740 (while (re-search-forward
13741 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13742 (when (equal (char-after (point-at-bol 0)) ?*)
13743 (mapc (lambda (x) (add-to-list 'tags x))
13744 (org-split-string (org-match-string-no-properties 1) ":")))))
13745 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13746 (mapcar 'list tags)))
13748 ;;;; The mapping API
13750 ;;;###autoload
13751 (defun org-map-entries (func &optional match scope &rest skip)
13752 "Call FUNC at each headline selected by MATCH in SCOPE.
13754 FUNC is a function or a lisp form. The function will be called without
13755 arguments, with the cursor positioned at the beginning of the headline.
13756 The return values of all calls to the function will be collected and
13757 returned as a list.
13759 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13760 does not need to preserve point. After evaluation, the cursor will be
13761 moved to the end of the line (presumably of the headline of the
13762 processed entry) and search continues from there. Under some
13763 circumstances, this may not produce the wanted results. For example,
13764 if you have removed (e.g. archived) the current (sub)tree it could
13765 mean that the next entry will be skipped entirely. In such cases, you
13766 can specify the position from where search should continue by making
13767 FUNC set the variable `org-map-continue-from' to the desired buffer
13768 position.
13770 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13771 Only headlines that are matched by this query will be considered during
13772 the iteration. When MATCH is nil or t, all headlines will be
13773 visited by the iteration.
13775 SCOPE determines the scope of this command. It can be any of:
13777 nil The current buffer, respecting the restriction if any
13778 tree The subtree started with the entry at point
13779 region The entries within the active region, if any
13780 region-start-level
13781 The entries within the active region, but only those at
13782 the same level than the first one.
13783 file The current buffer, without restriction
13784 file-with-archives
13785 The current buffer, and any archives associated with it
13786 agenda All agenda files
13787 agenda-with-archives
13788 All agenda files with any archive files associated with them
13789 \(file1 file2 ...)
13790 If this is a list, all files in the list will be scanned
13792 The remaining args are treated as settings for the skipping facilities of
13793 the scanner. The following items can be given here:
13795 archive skip trees with the archive tag.
13796 comment skip trees with the COMMENT keyword
13797 function or Emacs Lisp form:
13798 will be used as value for `org-agenda-skip-function', so whenever
13799 the function returns t, FUNC will not be called for that
13800 entry and search will continue from the point where the
13801 function leaves it.
13803 If your function needs to retrieve the tags including inherited tags
13804 at the *current* entry, you can use the value of the variable
13805 `org-scanner-tags' which will be much faster than getting the value
13806 with `org-get-tags-at'. If your function gets properties with
13807 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13808 to t around the call to `org-entry-properties' to get the same speedup.
13809 Note that if your function moves around to retrieve tags and properties at
13810 a *different* entry, you cannot use these techniques."
13811 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13812 (not (org-region-active-p)))
13813 (let* ((org-agenda-archives-mode nil) ; just to make sure
13814 (org-agenda-skip-archived-trees (memq 'archive skip))
13815 (org-agenda-skip-comment-trees (memq 'comment skip))
13816 (org-agenda-skip-function
13817 (car (org-delete-all '(comment archive) skip)))
13818 (org-tags-match-list-sublevels t)
13819 (start-level (eq scope 'region-start-level))
13820 matcher file res
13821 org-todo-keywords-for-agenda
13822 org-done-keywords-for-agenda
13823 org-todo-keyword-alist-for-agenda
13824 org-drawers-for-agenda
13825 org-tag-alist-for-agenda)
13827 (cond
13828 ((eq match t) (setq matcher t))
13829 ((eq match nil) (setq matcher t))
13830 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13832 (save-excursion
13833 (save-restriction
13834 (cond ((eq scope 'tree)
13835 (org-back-to-heading t)
13836 (org-narrow-to-subtree)
13837 (setq scope nil))
13838 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13839 (org-region-active-p))
13840 ;; If needed, set start-level to a string like "2"
13841 (when start-level
13842 (save-excursion
13843 (goto-char (region-beginning))
13844 (unless (org-at-heading-p) (outline-next-heading))
13845 (setq start-level (org-current-level))))
13846 (narrow-to-region (region-beginning)
13847 (save-excursion
13848 (goto-char (region-end))
13849 (unless (and (bolp) (org-at-heading-p))
13850 (outline-next-heading))
13851 (point)))
13852 (setq scope nil)))
13854 (if (not scope)
13855 (progn
13856 (org-prepare-agenda-buffers
13857 (list (buffer-file-name (current-buffer))))
13858 (setq res (org-scan-tags func matcher nil start-level)))
13859 ;; Get the right scope
13860 (cond
13861 ((and scope (listp scope) (symbolp (car scope)))
13862 (setq scope (eval scope)))
13863 ((eq scope 'agenda)
13864 (setq scope (org-agenda-files t)))
13865 ((eq scope 'agenda-with-archives)
13866 (setq scope (org-agenda-files t))
13867 (setq scope (org-add-archive-files scope)))
13868 ((eq scope 'file)
13869 (setq scope (list (buffer-file-name))))
13870 ((eq scope 'file-with-archives)
13871 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13872 (org-prepare-agenda-buffers scope)
13873 (while (setq file (pop scope))
13874 (with-current-buffer (org-find-base-buffer-visiting file)
13875 (save-excursion
13876 (save-restriction
13877 (widen)
13878 (goto-char (point-min))
13879 (setq res (append res (org-scan-tags func matcher))))))))))
13880 res)))
13882 ;;;; Properties
13884 ;;; Setting and retrieving properties
13886 (defconst org-special-properties
13887 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13888 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13889 "The special properties valid in Org-mode.
13891 These are properties that are not defined in the property drawer,
13892 but in some other way.")
13894 (defconst org-default-properties
13895 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13896 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13897 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13898 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13899 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13900 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13901 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13902 "Some properties that are used by Org-mode for various purposes.
13903 Being in this list makes sure that they are offered for completion.")
13905 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13906 "Regular expression matching the first line of a property drawer.")
13908 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13909 "Regular expression matching the last line of a property drawer.")
13911 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13912 "Regular expression matching the first line of a property drawer.")
13914 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13915 "Regular expression matching the first line of a property drawer.")
13917 (defconst org-property-drawer-re
13918 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13919 org-property-end-re "\\)\n?")
13920 "Matches an entire property drawer.")
13922 (defconst org-clock-drawer-re
13923 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13924 org-property-end-re "\\)\n?")
13925 "Matches an entire clock drawer.")
13927 (defsubst org-re-property (property)
13928 "Return a regexp matching PROPERTY.
13929 Match group 1 will be set to the value "
13930 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13932 (defun org-property-action ()
13933 "Do an action on properties."
13934 (interactive)
13935 (let (c)
13936 (org-at-property-p)
13937 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13938 (setq c (read-char-exclusive))
13939 (cond
13940 ((equal c ?s)
13941 (call-interactively 'org-set-property))
13942 ((equal c ?d)
13943 (call-interactively 'org-delete-property))
13944 ((equal c ?D)
13945 (call-interactively 'org-delete-property-globally))
13946 ((equal c ?c)
13947 (call-interactively 'org-compute-property-at-point))
13948 (t (error "No such property action %c" c)))))
13950 (defun org-set-effort (&optional value)
13951 "Set the effort property of the current entry.
13952 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13953 allowed value."
13954 (interactive "P")
13955 (if (equal value 0) (setq value 10))
13956 (let* ((completion-ignore-case t)
13957 (prop org-effort-property)
13958 (cur (org-entry-get nil prop))
13959 (allowed (org-property-get-allowed-values nil prop 'table))
13960 (existing (mapcar 'list (org-property-values prop)))
13962 (val (cond
13963 ((stringp value) value)
13964 ((and allowed (integerp value))
13965 (or (car (nth (1- value) allowed))
13966 (car (org-last allowed))))
13967 (allowed
13968 (message "Select 1-9,0, [RET%s]: %s"
13969 (if cur (concat "=" cur) "")
13970 (mapconcat 'car allowed " "))
13971 (setq rpl (read-char-exclusive))
13972 (if (equal rpl ?\r)
13974 (setq rpl (- rpl ?0))
13975 (if (equal rpl 0) (setq rpl 10))
13976 (if (and (> rpl 0) (<= rpl (length allowed)))
13977 (car (nth (1- rpl) allowed))
13978 (org-completing-read "Effort: " allowed nil))))
13980 (let (org-completion-use-ido org-completion-use-iswitchb)
13981 (org-completing-read
13982 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13983 (concat "[" cur "]") "")
13984 ": ")
13985 existing nil nil "" nil cur))))))
13986 (unless (equal (org-entry-get nil prop) val)
13987 (org-entry-put nil prop val))
13988 (message "%s is now %s" prop val)))
13990 (defun org-at-property-p ()
13991 "Is cursor inside a property drawer?"
13992 (save-excursion
13993 (beginning-of-line 1)
13994 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13995 (save-match-data ;; Used by calling procedures
13996 (let ((p (point))
13997 (range (unless (org-before-first-heading-p)
13998 (org-get-property-block))))
13999 (and range (<= (car range) p) (< p (cdr range))))))))
14001 (defun org-get-property-block (&optional beg end force)
14002 "Return the (beg . end) range of the body of the property drawer.
14003 BEG and END can be beginning and end of subtree, if not given
14004 they will be found.
14005 If the drawer does not exist and FORCE is non-nil, create the drawer."
14006 (catch 'exit
14007 (save-excursion
14008 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14009 (end (or end (progn (outline-next-heading) (point)))))
14010 (goto-char beg)
14011 (if (re-search-forward org-property-start-re end t)
14012 (setq beg (1+ (match-end 0)))
14013 (if force
14014 (save-excursion
14015 (org-insert-property-drawer)
14016 (setq end (progn (outline-next-heading) (point))))
14017 (throw 'exit nil))
14018 (goto-char beg)
14019 (if (re-search-forward org-property-start-re end t)
14020 (setq beg (1+ (match-end 0)))))
14021 (if (re-search-forward org-property-end-re end t)
14022 (setq end (match-beginning 0))
14023 (or force (throw 'exit nil))
14024 (goto-char beg)
14025 (setq end beg)
14026 (org-indent-line-function)
14027 (insert ":END:\n"))
14028 (cons beg end)))))
14030 (defun org-entry-properties (&optional pom which specific)
14031 "Get all properties of the entry at point-or-marker POM.
14032 This includes the TODO keyword, the tags, time strings for deadline,
14033 scheduled, and clocking, and any additional properties defined in the
14034 entry. The return value is an alist, keys may occur multiple times
14035 if the property key was used several times.
14036 POM may also be nil, in which case the current entry is used.
14037 If WHICH is nil or `all', get all properties. If WHICH is
14038 `special' or `standard', only get that subclass. If WHICH
14039 is a string only get exactly this property. SPECIFIC can be a string, the
14040 specific property we are interested in. Specifying it can speed
14041 things up because then unnecessary parsing is avoided."
14042 (setq which (or which 'all))
14043 (org-with-point-at pom
14044 (let ((clockstr (substring org-clock-string 0 -1))
14045 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14046 (case-fold-search nil)
14047 beg end range props sum-props key key1 value string clocksum)
14048 (save-excursion
14049 (when (condition-case nil
14050 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14051 (error nil))
14052 (setq beg (point))
14053 (setq sum-props (get-text-property (point) 'org-summaries))
14054 (setq clocksum (get-text-property (point) :org-clock-minutes))
14055 (outline-next-heading)
14056 (setq end (point))
14057 (when (memq which '(all special))
14058 ;; Get the special properties, like TODO and tags
14059 (goto-char beg)
14060 (when (and (or (not specific) (string= specific "TODO"))
14061 (looking-at org-todo-line-regexp) (match-end 2))
14062 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14063 (when (and (or (not specific) (string= specific "PRIORITY"))
14064 (looking-at org-priority-regexp))
14065 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14066 (when (or (not specific) (string= specific "FILE"))
14067 (push (cons "FILE" buffer-file-name) props))
14068 (when (and (or (not specific) (string= specific "TAGS"))
14069 (setq value (org-get-tags-string))
14070 (string-match "\\S-" value))
14071 (push (cons "TAGS" value) props))
14072 (when (and (or (not specific) (string= specific "ALLTAGS"))
14073 (setq value (org-get-tags-at)))
14074 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14075 ":"))
14076 props))
14077 (when (or (not specific) (string= specific "BLOCKED"))
14078 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14079 (when (or (not specific)
14080 (member specific
14081 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14082 "TIMESTAMP" "TIMESTAMP_IA")))
14083 (catch 'match
14084 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14085 (setq key (if (match-end 1)
14086 (substring (org-match-string-no-properties 1)
14087 0 -1))
14088 string (if (equal key clockstr)
14089 (org-no-properties
14090 (org-trim
14091 (buffer-substring
14092 (match-beginning 3) (goto-char
14093 (point-at-eol)))))
14094 (substring (org-match-string-no-properties 3)
14095 1 -1)))
14096 ;; Get the correct property name from the key. This is
14097 ;; necessary if the user has configured time keywords.
14098 (setq key1 (concat key ":"))
14099 (cond
14100 ((not key)
14101 (setq key
14102 (if (= (char-after (match-beginning 3)) ?\[)
14103 "TIMESTAMP_IA" "TIMESTAMP")))
14104 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14105 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14106 ((equal key1 org-closed-string) (setq key "CLOSED"))
14107 ((equal key1 org-clock-string) (setq key "CLOCK")))
14108 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14109 (progn
14110 (push (cons key string) props)
14111 ;; no need to search further if match is found
14112 (throw 'match t))
14113 (when (or (equal key "CLOCK") (not (assoc key props)))
14114 (push (cons key string) props))))))
14117 (when (memq which '(all standard))
14118 ;; Get the standard properties, like :PROP: ...
14119 (setq range (org-get-property-block beg end))
14120 (when range
14121 (goto-char (car range))
14122 (while (re-search-forward
14123 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14124 (cdr range) t)
14125 (setq key (org-match-string-no-properties 1)
14126 value (org-trim (or (org-match-string-no-properties 2) "")))
14127 (unless (member key excluded)
14128 (push (cons key (or value "")) props)))))
14129 (if clocksum
14130 (push (cons "CLOCKSUM"
14131 (org-columns-number-to-string (/ (float clocksum) 60.)
14132 'add_times))
14133 props))
14134 (unless (assoc "CATEGORY" props)
14135 (push (cons "CATEGORY" (org-get-category)) props))
14136 (append sum-props (nreverse props)))))))
14138 (defun org-entry-get (pom property &optional inherit literal-nil)
14139 "Get value of PROPERTY for entry at point-or-marker POM.
14140 If INHERIT is non-nil and the entry does not have the property,
14141 then also check higher levels of the hierarchy.
14142 If INHERIT is the symbol `selective', use inheritance only if the setting
14143 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14144 If the property is present but empty, the return value is the empty string.
14145 If the property is not present at all, nil is returned.
14147 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14148 do not interpret it as the list atom nil. This is used for inheritance
14149 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14150 (org-with-point-at pom
14151 (if (and inherit (if (eq inherit 'selective)
14152 (org-property-inherit-p property)
14154 (org-entry-get-with-inheritance property literal-nil)
14155 (if (member property org-special-properties)
14156 ;; We need a special property. Use `org-entry-properties' to
14157 ;; retrieve it, but specify the wanted property
14158 (cdr (assoc property (org-entry-properties nil 'special property)))
14159 (let ((range (unless (org-before-first-heading-p)
14160 (org-get-property-block)))
14161 (props (list (or (assoc property org-file-properties)
14162 (assoc property org-global-properties)
14163 (assoc property org-global-properties-fixed))))
14164 val)
14165 (flet ((ap (key)
14166 (when (re-search-forward
14167 (org-re-property key) (cdr range) t)
14168 (setq props
14169 (org-update-property-plist
14171 (if (match-end 1)
14172 (org-match-string-no-properties 1) "")
14173 props)))))
14174 (when (and range (goto-char (car range)))
14175 (ap property)
14176 (goto-char (car range))
14177 (while (ap (concat property "+")))
14178 (setq val (cdr (assoc property props)))
14179 (when val (if literal-nil val (org-not-nil val))))))))))
14181 (defun org-property-or-variable-value (var &optional inherit)
14182 "Check if there is a property fixing the value of VAR.
14183 If yes, return this value. If not, return the current value of the variable."
14184 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14185 (if (and prop (stringp prop) (string-match "\\S-" prop))
14186 (read prop)
14187 (symbol-value var))))
14189 (defun org-entry-delete (pom property)
14190 "Delete the property PROPERTY from entry at point-or-marker POM."
14191 (org-with-point-at pom
14192 (if (member property org-special-properties)
14193 nil ; cannot delete these properties.
14194 (let ((range (org-get-property-block)))
14195 (if (and range
14196 (goto-char (car range))
14197 (re-search-forward
14198 (org-re-property property)
14199 (cdr range) t))
14200 (progn
14201 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14203 nil)))))
14205 ;; Multi-values properties are properties that contain multiple values
14206 ;; These values are assumed to be single words, separated by whitespace.
14207 (defun org-entry-add-to-multivalued-property (pom property value)
14208 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14209 (let* ((old (org-entry-get pom property))
14210 (values (and old (org-split-string old "[ \t]"))))
14211 (setq value (org-entry-protect-space value))
14212 (unless (member value values)
14213 (setq values (cons value values))
14214 (org-entry-put pom property
14215 (mapconcat 'identity values " ")))))
14217 (defun org-entry-remove-from-multivalued-property (pom property value)
14218 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14219 (let* ((old (org-entry-get pom property))
14220 (values (and old (org-split-string old "[ \t]"))))
14221 (setq value (org-entry-protect-space value))
14222 (when (member value values)
14223 (setq values (delete value values))
14224 (org-entry-put pom property
14225 (mapconcat 'identity values " ")))))
14227 (defun org-entry-member-in-multivalued-property (pom property value)
14228 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14229 (let* ((old (org-entry-get pom property))
14230 (values (and old (org-split-string old "[ \t]"))))
14231 (setq value (org-entry-protect-space value))
14232 (member value values)))
14234 (defun org-entry-get-multivalued-property (pom property)
14235 "Return a list of values in a multivalued property."
14236 (let* ((value (org-entry-get pom property))
14237 (values (and value (org-split-string value "[ \t]"))))
14238 (mapcar 'org-entry-restore-space values)))
14240 (defun org-entry-put-multivalued-property (pom property &rest values)
14241 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14242 VALUES should be a list of strings. Spaces will be protected."
14243 (org-entry-put pom property
14244 (mapconcat 'org-entry-protect-space values " "))
14245 (let* ((value (org-entry-get pom property))
14246 (values (and value (org-split-string value "[ \t]"))))
14247 (mapcar 'org-entry-restore-space values)))
14249 (defun org-entry-protect-space (s)
14250 "Protect spaces and newline in string S."
14251 (while (string-match " " s)
14252 (setq s (replace-match "%20" t t s)))
14253 (while (string-match "\n" s)
14254 (setq s (replace-match "%0A" t t s)))
14257 (defun org-entry-restore-space (s)
14258 "Restore spaces and newline in string S."
14259 (while (string-match "%20" s)
14260 (setq s (replace-match " " t t s)))
14261 (while (string-match "%0A" s)
14262 (setq s (replace-match "\n" t t s)))
14265 (defvar org-entry-property-inherited-from (make-marker)
14266 "Marker pointing to the entry from where a property was inherited.
14267 Each call to `org-entry-get-with-inheritance' will set this marker to the
14268 location of the entry where the inheritance search matched. If there was
14269 no match, the marker will point nowhere.
14270 Note that also `org-entry-get' calls this function, if the INHERIT flag
14271 is set.")
14273 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14274 "Get entry property, and search higher levels if not present.
14275 The search will stop at the first ancestor which has the property defined.
14276 If the value found is \"nil\", return nil to show that the property
14277 should be considered as undefined (this is the meaning of nil here).
14278 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14279 (move-marker org-entry-property-inherited-from nil)
14280 (let (tmp)
14281 (unless (org-before-first-heading-p)
14282 (save-excursion
14283 (save-restriction
14284 (widen)
14285 (catch 'ex
14286 (while t
14287 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14288 (org-back-to-heading t)
14289 (move-marker org-entry-property-inherited-from (point))
14290 (throw 'ex tmp))
14291 (or (org-up-heading-safe) (throw 'ex nil)))))))
14292 (setq tmp (or tmp
14293 (cdr (assoc property org-file-properties))
14294 (cdr (assoc property org-global-properties))
14295 (cdr (assoc property org-global-properties-fixed))))
14296 (if literal-nil tmp (org-not-nil tmp))))
14298 (defvar org-property-changed-functions nil
14299 "Hook called when the value of a property has changed.
14300 Each hook function should accept two arguments, the name of the property
14301 and the new value.")
14303 (defun org-entry-put (pom property value)
14304 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14305 (org-with-point-at pom
14306 (org-back-to-heading t)
14307 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14308 range)
14309 (cond
14310 ((equal property "TODO")
14311 (when (and (stringp value) (string-match "\\S-" value)
14312 (not (member value org-todo-keywords-1)))
14313 (error "\"%s\" is not a valid TODO state" value))
14314 (if (or (not value)
14315 (not (string-match "\\S-" value)))
14316 (setq value 'none))
14317 (org-todo value)
14318 (org-set-tags nil 'align))
14319 ((equal property "PRIORITY")
14320 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14321 (string-to-char value) ?\ ))
14322 (org-set-tags nil 'align))
14323 ((equal property "SCHEDULED")
14324 (if (re-search-forward org-scheduled-time-regexp end t)
14325 (cond
14326 ((eq value 'earlier) (org-timestamp-change -1 'day))
14327 ((eq value 'later) (org-timestamp-change 1 'day))
14328 (t (call-interactively 'org-schedule)))
14329 (call-interactively 'org-schedule)))
14330 ((equal property "DEADLINE")
14331 (if (re-search-forward org-deadline-time-regexp end t)
14332 (cond
14333 ((eq value 'earlier) (org-timestamp-change -1 'day))
14334 ((eq value 'later) (org-timestamp-change 1 'day))
14335 (t (call-interactively 'org-deadline)))
14336 (call-interactively 'org-deadline)))
14337 ((member property org-special-properties)
14338 (error "The %s property can not yet be set with `org-entry-put'"
14339 property))
14340 (t ; a non-special property
14341 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14342 (setq range (org-get-property-block beg end 'force))
14343 (goto-char (car range))
14344 (if (re-search-forward
14345 (org-re-property property) (cdr range) t)
14346 (progn
14347 (delete-region (match-beginning 0) (match-end 0))
14348 (goto-char (match-beginning 0)))
14349 (goto-char (cdr range))
14350 (insert "\n")
14351 (backward-char 1)
14352 (org-indent-line-function))
14353 (insert ":" property ":")
14354 (and value (insert " " value))
14355 (org-indent-line-function)))))
14356 (run-hook-with-args 'org-property-changed-functions property value)))
14358 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14359 "Get all property keys in the current buffer.
14360 With INCLUDE-SPECIALS, also list the special properties that reflect things
14361 like tags and TODO state.
14362 With INCLUDE-DEFAULTS, also include properties that has special meaning
14363 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14364 and others.
14365 With INCLUDE-COLUMNS, also include property names given in COLUMN
14366 formats in the current buffer."
14367 (let (rtn range cfmt s p)
14368 (save-excursion
14369 (save-restriction
14370 (widen)
14371 (goto-char (point-min))
14372 (while (re-search-forward org-property-start-re nil t)
14373 (setq range (org-get-property-block))
14374 (goto-char (car range))
14375 (while (re-search-forward
14376 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14377 (cdr range) t)
14378 (add-to-list 'rtn (org-match-string-no-properties 1)))
14379 (outline-next-heading))))
14381 (when include-specials
14382 (setq rtn (append org-special-properties rtn)))
14384 (when include-defaults
14385 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14386 (add-to-list 'rtn org-effort-property))
14388 (when include-columns
14389 (save-excursion
14390 (save-restriction
14391 (widen)
14392 (goto-char (point-min))
14393 (while (re-search-forward
14394 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14395 nil t)
14396 (setq cfmt (match-string 2) s 0)
14397 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14398 cfmt s)
14399 (setq s (match-end 0)
14400 p (match-string 1 cfmt))
14401 (unless (or (equal p "ITEM")
14402 (member p org-special-properties))
14403 (add-to-list 'rtn (match-string 1 cfmt))))))))
14405 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14407 (defun org-property-values (key)
14408 "Return a list of all values of property KEY in the current buffer."
14409 (save-excursion
14410 (save-restriction
14411 (widen)
14412 (goto-char (point-min))
14413 (let ((re (org-re-property key))
14414 values)
14415 (while (re-search-forward re nil t)
14416 (add-to-list 'values (org-trim (match-string 1))))
14417 (delete "" values)))))
14419 (defun org-insert-property-drawer ()
14420 "Insert a property drawer into the current entry."
14421 (interactive)
14422 (org-back-to-heading t)
14423 (looking-at org-outline-regexp)
14424 (let ((indent (if org-adapt-indentation
14425 (- (match-end 0)(match-beginning 0))
14427 (beg (point))
14428 (re (concat "^[ \t]*" org-keyword-time-regexp))
14429 end hiddenp)
14430 (outline-next-heading)
14431 (setq end (point))
14432 (goto-char beg)
14433 (while (re-search-forward re end t))
14434 (setq hiddenp (outline-invisible-p))
14435 (end-of-line 1)
14436 (and (equal (char-after) ?\n) (forward-char 1))
14437 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14438 (if (member (match-string 1) '("CLOCK:" ":END:"))
14439 ;; just skip this line
14440 (beginning-of-line 2)
14441 ;; Drawer start, find the end
14442 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14443 (beginning-of-line 1)))
14444 (org-skip-over-state-notes)
14445 (skip-chars-backward " \t\n\r")
14446 (if (eq (char-before) ?*) (forward-char 1))
14447 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14448 (beginning-of-line 0)
14449 (org-indent-to-column indent)
14450 (beginning-of-line 2)
14451 (org-indent-to-column indent)
14452 (beginning-of-line 0)
14453 (if hiddenp
14454 (save-excursion
14455 (org-back-to-heading t)
14456 (hide-entry))
14457 (org-flag-drawer t))))
14459 (defvar org-property-set-functions-alist nil
14460 "Property set function alist.
14461 Each entry should have the following format:
14463 (PROPERTY . READ-FUNCTION)
14465 The read function will be called with the same argument as
14466 `org-completing-read'.")
14468 (defun org-set-property-function (property)
14469 "Get the function that should be used to set PROPERTY.
14470 This is computed according to `org-property-set-functions-alist'."
14471 (or (cdr (assoc property org-property-set-functions-alist))
14472 'org-completing-read))
14474 (defun org-read-property-value (property)
14475 "Read PROPERTY value from user."
14476 (let* ((completion-ignore-case t)
14477 (allowed (org-property-get-allowed-values nil property 'table))
14478 (cur (org-entry-get nil property))
14479 (prompt (concat property " value"
14480 (if (and cur (string-match "\\S-" cur))
14481 (concat " [" cur "]") "") ": "))
14482 (set-function (org-set-property-function property))
14483 (val (if allowed
14484 (funcall set-function prompt allowed nil
14485 (not (get-text-property 0 'org-unrestricted
14486 (caar allowed))))
14487 (let (org-completion-use-ido org-completion-use-iswitchb)
14488 (funcall set-function prompt
14489 (mapcar 'list (org-property-values property))
14490 nil nil "" nil cur)))))
14491 (if (equal val "")
14493 val)))
14495 (defvar org-last-set-property nil)
14496 (defun org-read-property-name ()
14497 "Read a property name."
14498 (let* ((completion-ignore-case t)
14499 (keys (org-buffer-property-keys nil t t))
14500 (default-prop (or (save-excursion
14501 (save-match-data
14502 (beginning-of-line)
14503 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14504 (null (string= (match-string 1) "END"))
14505 (match-string 1))))
14506 org-last-set-property))
14507 (property (org-icompleting-read
14508 (concat "Property"
14509 (if default-prop (concat " [" default-prop "]") "")
14510 ": ")
14511 (mapcar 'list keys)
14512 nil nil nil nil
14513 default-prop
14515 (if (member property keys)
14516 property
14517 (or (cdr (assoc (downcase property)
14518 (mapcar (lambda (x) (cons (downcase x) x))
14519 keys)))
14520 property))))
14522 (defun org-set-property (property value)
14523 "In the current entry, set PROPERTY to VALUE.
14524 When called interactively, this will prompt for a property name, offering
14525 completion on existing and default properties. And then it will prompt
14526 for a value, offering completion either on allowed values (via an inherited
14527 xxx_ALL property) or on existing values in other instances of this property
14528 in the current file."
14529 (interactive (list nil nil))
14530 (let* ((property (or property (org-read-property-name)))
14531 (value (or value (org-read-property-value property)))
14532 (fn (assoc property org-properties-postprocess-alist)))
14533 (setq org-last-set-property property)
14534 ;; Possibly postprocess the inserted value:
14535 (when fn (setq value (funcall (cadr fn) value)))
14536 (unless (equal (org-entry-get nil property) value)
14537 (org-entry-put nil property value))))
14539 (defun org-delete-property (property)
14540 "In the current entry, delete PROPERTY."
14541 (interactive
14542 (let* ((completion-ignore-case t)
14543 (prop (org-icompleting-read "Property: "
14544 (org-entry-properties nil 'standard))))
14545 (list prop)))
14546 (message "Property %s %s" property
14547 (if (org-entry-delete nil property)
14548 "deleted"
14549 "was not present in the entry")))
14551 (defun org-delete-property-globally (property)
14552 "Remove PROPERTY globally, from all entries."
14553 (interactive
14554 (let* ((completion-ignore-case t)
14555 (prop (org-icompleting-read
14556 "Globally remove property: "
14557 (mapcar 'list (org-buffer-property-keys)))))
14558 (list prop)))
14559 (save-excursion
14560 (save-restriction
14561 (widen)
14562 (goto-char (point-min))
14563 (let ((cnt 0))
14564 (while (re-search-forward
14565 (org-re-property property)
14566 nil t)
14567 (setq cnt (1+ cnt))
14568 (replace-match ""))
14569 (message "Property \"%s\" removed from %d entries" property cnt)))))
14571 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14573 (defun org-compute-property-at-point ()
14574 "Compute the property at point.
14575 This looks for an enclosing column format, extracts the operator and
14576 then applies it to the property in the column format's scope."
14577 (interactive)
14578 (unless (org-at-property-p)
14579 (error "Not at a property"))
14580 (let ((prop (org-match-string-no-properties 2)))
14581 (org-columns-get-format-and-top-level)
14582 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14583 (error "No operator defined for property %s" prop))
14584 (org-columns-compute prop)))
14586 (defvar org-property-allowed-value-functions nil
14587 "Hook for functions supplying allowed values for a specific property.
14588 The functions must take a single argument, the name of the property, and
14589 return a flat list of allowed values. If \":ETC\" is one of
14590 the values, this means that these values are intended as defaults for
14591 completion, but that other values should be allowed too.
14592 The functions must return nil if they are not responsible for this
14593 property.")
14595 (defun org-property-get-allowed-values (pom property &optional table)
14596 "Get allowed values for the property PROPERTY.
14597 When TABLE is non-nil, return an alist that can directly be used for
14598 completion."
14599 (let (vals)
14600 (cond
14601 ((equal property "TODO")
14602 (setq vals (org-with-point-at pom
14603 (append org-todo-keywords-1 '("")))))
14604 ((equal property "PRIORITY")
14605 (let ((n org-lowest-priority))
14606 (while (>= n org-highest-priority)
14607 (push (char-to-string n) vals)
14608 (setq n (1- n)))))
14609 ((member property org-special-properties))
14610 ((setq vals (run-hook-with-args-until-success
14611 'org-property-allowed-value-functions property)))
14613 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14614 (when (and vals (string-match "\\S-" vals))
14615 (setq vals (car (read-from-string (concat "(" vals ")"))))
14616 (setq vals (mapcar (lambda (x)
14617 (cond ((stringp x) x)
14618 ((numberp x) (number-to-string x))
14619 ((symbolp x) (symbol-name x))
14620 (t "???")))
14621 vals)))))
14622 (when (member ":ETC" vals)
14623 (setq vals (remove ":ETC" vals))
14624 (org-add-props (car vals) '(org-unrestricted t)))
14625 (if table (mapcar 'list vals) vals)))
14627 (defun org-property-previous-allowed-value (&optional previous)
14628 "Switch to the next allowed value for this property."
14629 (interactive)
14630 (org-property-next-allowed-value t))
14632 (defun org-property-next-allowed-value (&optional previous)
14633 "Switch to the next allowed value for this property."
14634 (interactive)
14635 (unless (org-at-property-p)
14636 (error "Not at a property"))
14637 (let* ((key (match-string 2))
14638 (value (match-string 3))
14639 (allowed (or (org-property-get-allowed-values (point) key)
14640 (and (member value '("[ ]" "[-]" "[X]"))
14641 '("[ ]" "[X]"))))
14642 nval)
14643 (unless allowed
14644 (error "Allowed values for this property have not been defined"))
14645 (if previous (setq allowed (reverse allowed)))
14646 (if (member value allowed)
14647 (setq nval (car (cdr (member value allowed)))))
14648 (setq nval (or nval (car allowed)))
14649 (if (equal nval value)
14650 (error "Only one allowed value for this property"))
14651 (org-at-property-p)
14652 (replace-match (concat " :" key ": " nval) t t)
14653 (org-indent-line-function)
14654 (beginning-of-line 1)
14655 (skip-chars-forward " \t")
14656 (run-hook-with-args 'org-property-changed-functions key nval)))
14658 (defun org-find-olp (path &optional this-buffer)
14659 "Return a marker pointing to the entry at outline path OLP.
14660 If anything goes wrong, throw an error.
14661 You can wrap this call to catch the error like this:
14663 (condition-case msg
14664 (org-mobile-locate-entry (match-string 4))
14665 (error (nth 1 msg)))
14667 The return value will then be either a string with the error message,
14668 or a marker if everything is OK.
14670 If THIS-BUFFER is set, the outline path does not contain a file,
14671 only headings."
14672 (let* ((file (if this-buffer buffer-file-name (pop path)))
14673 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14674 (level 1)
14675 (lmin 1)
14676 (lmax 1)
14677 limit re end found pos heading cnt flevel)
14678 (unless buffer (error "File not found :%s" file))
14679 (with-current-buffer buffer
14680 (save-excursion
14681 (save-restriction
14682 (widen)
14683 (setq limit (point-max))
14684 (goto-char (point-min))
14685 (while (setq heading (pop path))
14686 (setq re (format org-complex-heading-regexp-format
14687 (regexp-quote heading)))
14688 (setq cnt 0 pos (point))
14689 (while (re-search-forward re end t)
14690 (setq level (- (match-end 1) (match-beginning 1)))
14691 (if (and (>= level lmin) (<= level lmax))
14692 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14693 (when (= cnt 0) (error "Heading not found on level %d: %s"
14694 lmax heading))
14695 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14696 lmax heading))
14697 (goto-char found)
14698 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14699 (setq end (save-excursion (org-end-of-subtree t t))))
14700 (when (org-at-heading-p)
14701 (move-marker (make-marker) (point))))))))
14703 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14704 "Find node HEADING in BUFFER.
14705 Return a marker to the heading if it was found, or nil if not.
14706 If POS-ONLY is set, return just the position instead of a marker.
14708 The heading text must match exact, but it may have a TODO keyword,
14709 a priority cookie and tags in the standard locations."
14710 (with-current-buffer (or buffer (current-buffer))
14711 (save-excursion
14712 (save-restriction
14713 (widen)
14714 (goto-char (point-min))
14715 (let (case-fold-search)
14716 (if (re-search-forward
14717 (format org-complex-heading-regexp-format
14718 (regexp-quote heading)) nil t)
14719 (if pos-only
14720 (match-beginning 0)
14721 (move-marker (make-marker) (match-beginning 0)))))))))
14723 (defun org-find-exact-heading-in-directory (heading &optional dir)
14724 "Find Org node headline HEADING in all .org files in directory DIR.
14725 When the target headline is found, return a marker to this location."
14726 (let ((files (directory-files (or dir default-directory)
14727 nil "\\`[^.#].*\\.org\\'"))
14728 file visiting m buffer)
14729 (catch 'found
14730 (while (setq file (pop files))
14731 (message "trying %s" file)
14732 (setq visiting (org-find-base-buffer-visiting file))
14733 (setq buffer (or visiting (find-file-noselect file)))
14734 (setq m (org-find-exact-headline-in-buffer
14735 heading buffer))
14736 (when (and (not m) (not visiting)) (kill-buffer buffer))
14737 (and m (throw 'found m))))))
14739 (defun org-find-entry-with-id (ident)
14740 "Locate the entry that contains the ID property with exact value IDENT.
14741 IDENT can be a string, a symbol or a number, this function will search for
14742 the string representation of it.
14743 Return the position where this entry starts, or nil if there is no such entry."
14744 (interactive "sID: ")
14745 (let ((id (cond
14746 ((stringp ident) ident)
14747 ((symbol-name ident) (symbol-name ident))
14748 ((numberp ident) (number-to-string ident))
14749 (t (error "IDENT %s must be a string, symbol or number" ident))))
14750 (case-fold-search nil))
14751 (save-excursion
14752 (save-restriction
14753 (widen)
14754 (goto-char (point-min))
14755 (when (re-search-forward
14756 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14757 nil t)
14758 (org-back-to-heading t)
14759 (point))))))
14761 ;;;; Timestamps
14763 (defvar org-last-changed-timestamp nil)
14764 (defvar org-last-inserted-timestamp nil
14765 "The last time stamp inserted with `org-insert-time-stamp'.")
14766 (defvar org-time-was-given) ; dynamically scoped parameter
14767 (defvar org-end-time-was-given) ; dynamically scoped parameter
14768 (defvar org-ts-what) ; dynamically scoped parameter
14770 (defun org-time-stamp (arg &optional inactive)
14771 "Prompt for a date/time and insert a time stamp.
14772 If the user specifies a time like HH:MM, or if this command is called
14773 with a prefix argument, the time stamp will contain date and time.
14774 Otherwise, only the date will be included. All parts of a date not
14775 specified by the user will be filled in from the current date/time.
14776 So if you press just return without typing anything, the time stamp
14777 will represent the current date/time. If there is already a timestamp
14778 at the cursor, it will be modified."
14779 (interactive "P")
14780 (let* ((ts nil)
14781 (default-time
14782 ;; Default time is either today, or, when entering a range,
14783 ;; the range start.
14784 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14785 (save-excursion
14786 (re-search-backward
14787 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14788 (- (point) 20) t)))
14789 (apply 'encode-time (org-parse-time-string (match-string 1)))
14790 (current-time)))
14791 (default-input (and ts (org-get-compact-tod ts)))
14792 (repeater (save-excursion
14793 (save-match-data
14794 (beginning-of-line)
14795 (when (re-search-forward
14796 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14797 (save-excursion (progn (end-of-line) (point))) t)
14798 (match-string 0)))))
14799 org-time-was-given org-end-time-was-given time)
14800 (cond
14801 ((and (org-at-timestamp-p t)
14802 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14803 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14804 (insert "--")
14805 (setq time (let ((this-command this-command))
14806 (org-read-date arg 'totime nil nil
14807 default-time default-input)))
14808 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14809 ((org-at-timestamp-p t)
14810 (setq time (let ((this-command this-command))
14811 (org-read-date arg 'totime nil nil default-time default-input)))
14812 (when (org-at-timestamp-p t) ; just to get the match data
14813 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14814 (replace-match "")
14815 (setq org-last-changed-timestamp
14816 (org-insert-time-stamp
14817 time (or org-time-was-given arg)
14818 inactive nil nil (list org-end-time-was-given)))
14819 (when repeater (goto-char (1- (point))) (insert " " repeater)
14820 (setq org-last-changed-timestamp
14821 (concat (substring org-last-inserted-timestamp 0 -1)
14822 " " repeater ">"))))
14823 (message "Timestamp updated"))
14825 (setq time (let ((this-command this-command))
14826 (org-read-date arg 'totime nil nil default-time default-input)))
14827 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14828 nil nil (list org-end-time-was-given))))))
14830 ;; FIXME: can we use this for something else, like computing time differences?
14831 (defun org-get-compact-tod (s)
14832 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14833 (let* ((t1 (match-string 1 s))
14834 (h1 (string-to-number (match-string 2 s)))
14835 (m1 (string-to-number (match-string 3 s)))
14836 (t2 (and (match-end 4) (match-string 5 s)))
14837 (h2 (and t2 (string-to-number (match-string 6 s))))
14838 (m2 (and t2 (string-to-number (match-string 7 s))))
14839 dh dm)
14840 (if (not t2)
14842 (setq dh (- h2 h1) dm (- m2 m1))
14843 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14844 (concat t1 "+" (number-to-string dh)
14845 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14847 (defun org-time-stamp-inactive (&optional arg)
14848 "Insert an inactive time stamp.
14849 An inactive time stamp is enclosed in square brackets instead of angle
14850 brackets. It is inactive in the sense that it does not trigger agenda entries,
14851 does not link to the calendar and cannot be changed with the S-cursor keys.
14852 So these are more for recording a certain time/date."
14853 (interactive "P")
14854 (org-time-stamp arg 'inactive))
14856 (defvar org-date-ovl (make-overlay 1 1))
14857 (overlay-put org-date-ovl 'face 'org-warning)
14858 (org-detach-overlay org-date-ovl)
14860 (defvar org-ans1) ; dynamically scoped parameter
14861 (defvar org-ans2) ; dynamically scoped parameter
14863 (defvar org-plain-time-of-day-regexp) ; defined below
14865 (defvar org-overriding-default-time nil) ; dynamically scoped
14866 (defvar org-read-date-overlay nil)
14867 (defvar org-dcst nil) ; dynamically scoped
14868 (defvar org-read-date-history nil)
14869 (defvar org-read-date-final-answer nil)
14870 (defvar org-read-date-analyze-futurep nil)
14871 (defvar org-read-date-analyze-forced-year nil)
14873 (defun org-read-date (&optional with-time to-time from-string prompt
14874 default-time default-input)
14875 "Read a date, possibly a time, and make things smooth for the user.
14876 The prompt will suggest to enter an ISO date, but you can also enter anything
14877 which will at least partially be understood by `parse-time-string'.
14878 Unrecognized parts of the date will default to the current day, month, year,
14879 hour and minute. If this command is called to replace a timestamp at point,
14880 or to enter the second timestamp of a range, the default time is taken
14881 from the existing stamp. Furthermore, the command prefers the future,
14882 so if you are giving a date where the year is not given, and the day-month
14883 combination is already past in the current year, it will assume you
14884 mean next year. For details, see the manual. A few examples:
14886 3-2-5 --> 2003-02-05
14887 feb 15 --> currentyear-02-15
14888 2/15 --> currentyear-02-15
14889 sep 12 9 --> 2009-09-12
14890 12:45 --> today 12:45
14891 22 sept 0:34 --> currentyear-09-22 0:34
14892 12 --> currentyear-currentmonth-12
14893 Fri --> nearest Friday (today or later)
14894 etc.
14896 Furthermore you can specify a relative date by giving, as the *first* thing
14897 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14898 change in days weeks, months, years.
14899 With a single plus or minus, the date is relative to today. With a double
14900 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14901 +4d --> four days from today
14902 +4 --> same as above
14903 +2w --> two weeks from today
14904 ++5 --> five days from default date
14906 The function understands only English month and weekday abbreviations,
14907 but this can be configured with the variables `parse-time-months' and
14908 `parse-time-weekdays'.
14910 While prompting, a calendar is popped up - you can also select the
14911 date with the mouse (button 1). The calendar shows a period of three
14912 months. To scroll it to other months, use the keys `>' and `<'.
14913 If you don't like the calendar, turn it off with
14914 \(setq org-read-date-popup-calendar nil)
14916 With optional argument TO-TIME, the date will immediately be converted
14917 to an internal time.
14918 With an optional argument WITH-TIME, the prompt will suggest to also
14919 insert a time. Note that when WITH-TIME is not set, you can still
14920 enter a time, and this function will inform the calling routine about
14921 this change. The calling routine may then choose to change the format
14922 used to insert the time stamp into the buffer to include the time.
14923 With optional argument FROM-STRING, read from this string instead from
14924 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14925 the time/date that is used for everything that is not specified by the
14926 user."
14927 (require 'parse-time)
14928 (let* ((org-time-stamp-rounding-minutes
14929 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14930 (org-dcst org-display-custom-times)
14931 (ct (org-current-time))
14932 (def (or org-overriding-default-time default-time ct))
14933 (defdecode (decode-time def))
14934 (dummy (progn
14935 (when (< (nth 2 defdecode) org-extend-today-until)
14936 (setcar (nthcdr 2 defdecode) -1)
14937 (setcar (nthcdr 1 defdecode) 59)
14938 (setq def (apply 'encode-time defdecode)
14939 defdecode (decode-time def)))))
14940 (calendar-frame-setup nil)
14941 (calendar-setup nil)
14942 (calendar-move-hook nil)
14943 (calendar-view-diary-initially-flag nil)
14944 (calendar-view-holidays-initially-flag nil)
14945 (timestr (format-time-string
14946 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14947 (prompt (concat (if prompt (concat prompt " ") "")
14948 (format "Date+time [%s]: " timestr)))
14949 ans (org-ans0 "") org-ans1 org-ans2 final)
14951 (cond
14952 (from-string (setq ans from-string))
14953 (org-read-date-popup-calendar
14954 (save-excursion
14955 (save-window-excursion
14956 (calendar)
14957 (unwind-protect
14958 (progn
14959 (calendar-forward-day (- (time-to-days def)
14960 (calendar-absolute-from-gregorian
14961 (calendar-current-date))))
14962 (org-eval-in-calendar nil t)
14963 (let* ((old-map (current-local-map))
14964 (map (copy-keymap calendar-mode-map))
14965 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14966 (org-defkey map (kbd "RET") 'org-calendar-select)
14967 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14968 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14969 (org-defkey minibuffer-local-map [(meta shift left)]
14970 (lambda () (interactive)
14971 (org-eval-in-calendar '(calendar-backward-month 1))))
14972 (org-defkey minibuffer-local-map [(meta shift right)]
14973 (lambda () (interactive)
14974 (org-eval-in-calendar '(calendar-forward-month 1))))
14975 (org-defkey minibuffer-local-map [(meta shift up)]
14976 (lambda () (interactive)
14977 (org-eval-in-calendar '(calendar-backward-year 1))))
14978 (org-defkey minibuffer-local-map [(meta shift down)]
14979 (lambda () (interactive)
14980 (org-eval-in-calendar '(calendar-forward-year 1))))
14981 (org-defkey minibuffer-local-map [?\e (shift left)]
14982 (lambda () (interactive)
14983 (org-eval-in-calendar '(calendar-backward-month 1))))
14984 (org-defkey minibuffer-local-map [?\e (shift right)]
14985 (lambda () (interactive)
14986 (org-eval-in-calendar '(calendar-forward-month 1))))
14987 (org-defkey minibuffer-local-map [?\e (shift up)]
14988 (lambda () (interactive)
14989 (org-eval-in-calendar '(calendar-backward-year 1))))
14990 (org-defkey minibuffer-local-map [?\e (shift down)]
14991 (lambda () (interactive)
14992 (org-eval-in-calendar '(calendar-forward-year 1))))
14993 (org-defkey minibuffer-local-map [(shift up)]
14994 (lambda () (interactive)
14995 (org-eval-in-calendar '(calendar-backward-week 1))))
14996 (org-defkey minibuffer-local-map [(shift down)]
14997 (lambda () (interactive)
14998 (org-eval-in-calendar '(calendar-forward-week 1))))
14999 (org-defkey minibuffer-local-map [(shift left)]
15000 (lambda () (interactive)
15001 (org-eval-in-calendar '(calendar-backward-day 1))))
15002 (org-defkey minibuffer-local-map [(shift right)]
15003 (lambda () (interactive)
15004 (org-eval-in-calendar '(calendar-forward-day 1))))
15005 (org-defkey minibuffer-local-map ">"
15006 (lambda () (interactive)
15007 (org-eval-in-calendar '(scroll-calendar-left 1))))
15008 (org-defkey minibuffer-local-map "<"
15009 (lambda () (interactive)
15010 (org-eval-in-calendar '(scroll-calendar-right 1))))
15011 (org-defkey minibuffer-local-map "\C-v"
15012 (lambda () (interactive)
15013 (org-eval-in-calendar
15014 '(calendar-scroll-left-three-months 1))))
15015 (org-defkey minibuffer-local-map "\M-v"
15016 (lambda () (interactive)
15017 (org-eval-in-calendar
15018 '(calendar-scroll-right-three-months 1))))
15019 (run-hooks 'org-read-date-minibuffer-setup-hook)
15020 (unwind-protect
15021 (progn
15022 (use-local-map map)
15023 (add-hook 'post-command-hook 'org-read-date-display)
15024 (setq org-ans0 (read-string prompt default-input
15025 'org-read-date-history nil))
15026 ;; org-ans0: from prompt
15027 ;; org-ans1: from mouse click
15028 ;; org-ans2: from calendar motion
15029 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15030 (remove-hook 'post-command-hook 'org-read-date-display)
15031 (use-local-map old-map)
15032 (when org-read-date-overlay
15033 (delete-overlay org-read-date-overlay)
15034 (setq org-read-date-overlay nil)))))
15035 (bury-buffer "*Calendar*")))))
15037 (t ; Naked prompt only
15038 (unwind-protect
15039 (setq ans (read-string prompt default-input
15040 'org-read-date-history timestr))
15041 (when org-read-date-overlay
15042 (delete-overlay org-read-date-overlay)
15043 (setq org-read-date-overlay nil)))))
15045 (setq final (org-read-date-analyze ans def defdecode))
15047 (when org-read-date-analyze-forced-year
15048 (message "Year was forced into %s"
15049 (if org-read-date-force-compatible-dates
15050 "compatible range (1970-2037)"
15051 "range representable on this machine"))
15052 (ding))
15054 ;; One round trip to get rid of 34th of August and stuff like that....
15055 (setq final (decode-time (apply 'encode-time final)))
15057 (setq org-read-date-final-answer ans)
15059 (if to-time
15060 (apply 'encode-time final)
15061 (if (and (boundp 'org-time-was-given) org-time-was-given)
15062 (format "%04d-%02d-%02d %02d:%02d"
15063 (nth 5 final) (nth 4 final) (nth 3 final)
15064 (nth 2 final) (nth 1 final))
15065 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15067 (defvar def)
15068 (defvar defdecode)
15069 (defvar with-time)
15070 (defun org-read-date-display ()
15071 "Display the current date prompt interpretation in the minibuffer."
15072 (when org-read-date-display-live
15073 (when org-read-date-overlay
15074 (delete-overlay org-read-date-overlay))
15075 (let ((p (point)))
15076 (end-of-line 1)
15077 (while (not (equal (buffer-substring
15078 (max (point-min) (- (point) 4)) (point))
15079 " "))
15080 (insert " "))
15081 (goto-char p))
15082 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15083 " " (or org-ans1 org-ans2)))
15084 (org-end-time-was-given nil)
15085 (f (org-read-date-analyze ans def defdecode))
15086 (fmts (if org-dcst
15087 org-time-stamp-custom-formats
15088 org-time-stamp-formats))
15089 (fmt (if (or with-time
15090 (and (boundp 'org-time-was-given) org-time-was-given))
15091 (cdr fmts)
15092 (car fmts)))
15093 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15094 (when (and org-end-time-was-given
15095 (string-match org-plain-time-of-day-regexp txt))
15096 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15097 org-end-time-was-given
15098 (substring txt (match-end 0)))))
15099 (when org-read-date-analyze-futurep
15100 (setq txt (concat txt " (=>F)")))
15101 (setq org-read-date-overlay
15102 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15103 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15105 (defun org-read-date-analyze (ans def defdecode)
15106 "Analyze the combined answer of the date prompt."
15107 ;; FIXME: cleanup and comment
15108 (let ((nowdecode (decode-time (current-time)))
15109 delta deltan deltaw deltadef year month day
15110 hour minute second wday pm h2 m2 tl wday1
15111 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15112 (setq org-read-date-analyze-futurep nil
15113 org-read-date-analyze-forced-year nil)
15114 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15115 (setq ans "+0"))
15117 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15118 (setq ans (replace-match "" t t ans)
15119 deltan (car delta)
15120 deltaw (nth 1 delta)
15121 deltadef (nth 2 delta)))
15123 ;; Check if there is an iso week date in there
15124 ;; If yes, store the info and postpone interpreting it until the rest
15125 ;; of the parsing is done
15126 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15127 (setq iso-year (if (match-end 1)
15128 (org-small-year-to-year
15129 (string-to-number (match-string 1 ans))))
15130 iso-weekday (if (match-end 3)
15131 (string-to-number (match-string 3 ans)))
15132 iso-week (string-to-number (match-string 2 ans)))
15133 (setq ans (replace-match "" t t ans)))
15135 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15136 (when (string-match
15137 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15138 (setq year (if (match-end 2)
15139 (string-to-number (match-string 2 ans))
15140 (progn (setq kill-year t)
15141 (string-to-number (format-time-string "%Y"))))
15142 month (string-to-number (match-string 3 ans))
15143 day (string-to-number (match-string 4 ans)))
15144 (if (< year 100) (setq year (+ 2000 year)))
15145 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15146 t nil ans)))
15148 ;; Help matching dotted european dates
15149 (when (string-match
15150 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15151 (setq year (if (match-end 3)
15152 (string-to-number (match-string 3 ans))
15153 (progn (setq kill-year t)
15154 (string-to-number (format-time-string "%Y"))))
15155 day (string-to-number (match-string 1 ans))
15156 month (string-to-number (match-string 2 ans))
15157 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15158 t nil ans)))
15160 ;; Help matching american dates, like 5/30 or 5/30/7
15161 (when (string-match
15162 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15163 (setq year (if (match-end 4)
15164 (string-to-number (match-string 4 ans))
15165 (progn (setq kill-year t)
15166 (string-to-number (format-time-string "%Y"))))
15167 month (string-to-number (match-string 1 ans))
15168 day (string-to-number (match-string 2 ans)))
15169 (if (< year 100) (setq year (+ 2000 year)))
15170 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15171 t nil ans)))
15172 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15173 ;; If there is a time with am/pm, and *no* time without it, we convert
15174 ;; so that matching will be successful.
15175 (loop for i from 1 to 2 do ; twice, for end time as well
15176 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15177 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15178 (setq hour (string-to-number (match-string 1 ans))
15179 minute (if (match-end 3)
15180 (string-to-number (match-string 3 ans))
15182 pm (equal ?p
15183 (string-to-char (downcase (match-string 4 ans)))))
15184 (if (and (= hour 12) (not pm))
15185 (setq hour 0)
15186 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15187 (setq ans (replace-match (format "%02d:%02d" hour minute)
15188 t t ans))))
15190 ;; Check if a time range is given as a duration
15191 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15192 (setq hour (string-to-number (match-string 1 ans))
15193 h2 (+ hour (string-to-number (match-string 3 ans)))
15194 minute (string-to-number (match-string 2 ans))
15195 m2 (+ minute (if (match-end 5) (string-to-number
15196 (match-string 5 ans))0)))
15197 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15198 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15199 t t ans)))
15201 ;; Check if there is a time range
15202 (when (boundp 'org-end-time-was-given)
15203 (setq org-time-was-given nil)
15204 (when (and (string-match org-plain-time-of-day-regexp ans)
15205 (match-end 8))
15206 (setq org-end-time-was-given (match-string 8 ans))
15207 (setq ans (concat (substring ans 0 (match-beginning 7))
15208 (substring ans (match-end 7))))))
15210 (setq tl (parse-time-string ans)
15211 day (or (nth 3 tl) (nth 3 defdecode))
15212 month (or (nth 4 tl)
15213 (if (and org-read-date-prefer-future
15214 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15215 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15216 (nth 4 defdecode)))
15217 year (or (and (not kill-year) (nth 5 tl))
15218 (if (and org-read-date-prefer-future
15219 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15220 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15221 (nth 5 defdecode)))
15222 hour (or (nth 2 tl) (nth 2 defdecode))
15223 minute (or (nth 1 tl) (nth 1 defdecode))
15224 second (or (nth 0 tl) 0)
15225 wday (nth 6 tl))
15227 (when (and (eq org-read-date-prefer-future 'time)
15228 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15229 (equal day (nth 3 nowdecode))
15230 (equal month (nth 4 nowdecode))
15231 (equal year (nth 5 nowdecode))
15232 (nth 2 tl)
15233 (or (< (nth 2 tl) (nth 2 nowdecode))
15234 (and (= (nth 2 tl) (nth 2 nowdecode))
15235 (nth 1 tl)
15236 (< (nth 1 tl) (nth 1 nowdecode)))))
15237 (setq day (1+ day)
15238 futurep t))
15240 ;; Special date definitions below
15241 (cond
15242 (iso-week
15243 ;; There was an iso week
15244 (require 'cal-iso)
15245 (setq futurep nil)
15246 (setq year (or iso-year year)
15247 day (or iso-weekday wday 1)
15248 wday nil ; to make sure that the trigger below does not match
15249 iso-date (calendar-gregorian-from-absolute
15250 (calendar-absolute-from-iso
15251 (list iso-week day year))))
15252 ; FIXME: Should we also push ISO weeks into the future?
15253 ; (when (and org-read-date-prefer-future
15254 ; (not iso-year)
15255 ; (< (calendar-absolute-from-gregorian iso-date)
15256 ; (time-to-days (current-time))))
15257 ; (setq year (1+ year)
15258 ; iso-date (calendar-gregorian-from-absolute
15259 ; (calendar-absolute-from-iso
15260 ; (list iso-week day year)))))
15261 (setq month (car iso-date)
15262 year (nth 2 iso-date)
15263 day (nth 1 iso-date)))
15264 (deltan
15265 (setq futurep nil)
15266 (unless deltadef
15267 (let ((now (decode-time (current-time))))
15268 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15269 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15270 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15271 ((equal deltaw "m") (setq month (+ month deltan)))
15272 ((equal deltaw "y") (setq year (+ year deltan)))))
15273 ((and wday (not (nth 3 tl)))
15274 (setq futurep nil)
15275 ;; Weekday was given, but no day, so pick that day in the week
15276 ;; on or after the derived date.
15277 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15278 (unless (equal wday wday1)
15279 (setq day (+ day (% (- wday wday1 -7) 7))))))
15280 (if (and (boundp 'org-time-was-given)
15281 (nth 2 tl))
15282 (setq org-time-was-given t))
15283 (if (< year 100) (setq year (+ 2000 year)))
15284 ;; Check of the date is representable
15285 (if org-read-date-force-compatible-dates
15286 (progn
15287 (if (< year 1970)
15288 (setq year 1970 org-read-date-analyze-forced-year t))
15289 (if (> year 2037)
15290 (setq year 2037 org-read-date-analyze-forced-year t)))
15291 (condition-case nil
15292 (ignore (encode-time second minute hour day month year))
15293 (error
15294 (setq year (nth 5 defdecode))
15295 (setq org-read-date-analyze-forced-year t))))
15296 (setq org-read-date-analyze-futurep futurep)
15297 (list second minute hour day month year)))
15299 (defvar parse-time-weekdays)
15301 (defun org-read-date-get-relative (s today default)
15302 "Check string S for special relative date string.
15303 TODAY and DEFAULT are internal times, for today and for a default.
15304 Return shift list (N what def-flag)
15305 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15306 N is the number of WHATs to shift.
15307 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15308 the DEFAULT date rather than TODAY."
15309 (require 'parse-time)
15310 (when (and
15311 (string-match
15312 (concat
15313 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15314 "\\([0-9]+\\)?"
15315 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15316 "\\([ \t]\\|$\\)") s)
15317 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15318 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15319 (string-to-char (substring (match-string 1 s) -1))
15320 ?+))
15321 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15322 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15323 (what (if (match-end 3) (match-string 3 s) "d"))
15324 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15325 (date (if rel default today))
15326 (wday (nth 6 (decode-time date)))
15327 delta)
15328 (if wday1
15329 (progn
15330 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15331 (if (= dir ?-) (setq delta (- delta 7)))
15332 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15333 (list delta "d" rel))
15334 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15336 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15337 "Turn a user-specified date into the internal representation.
15338 The internal representation needed by the calendar is (month day year).
15339 This is a wrapper to handle the brain-dead convention in calendar that
15340 user function argument order change dependent on argument order."
15341 (if (boundp 'calendar-date-style)
15342 (cond
15343 ((eq calendar-date-style 'american)
15344 (list arg1 arg2 arg3))
15345 ((eq calendar-date-style 'european)
15346 (list arg2 arg1 arg3))
15347 ((eq calendar-date-style 'iso)
15348 (list arg2 arg3 arg1)))
15349 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15350 (if (org-bound-and-true-p european-calendar-style)
15351 (list arg2 arg1 arg3)
15352 (list arg1 arg2 arg3)))))
15354 (defun org-eval-in-calendar (form &optional keepdate)
15355 "Eval FORM in the calendar window and return to current window.
15356 Also, store the cursor date in variable org-ans2."
15357 (let ((sf (selected-frame))
15358 (sw (selected-window)))
15359 (select-window (get-buffer-window "*Calendar*" t))
15360 (eval form)
15361 (when (and (not keepdate) (calendar-cursor-to-date))
15362 (let* ((date (calendar-cursor-to-date))
15363 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15364 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15365 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15366 (select-window sw)
15367 (org-select-frame-set-input-focus sf)))
15369 (defun org-calendar-select ()
15370 "Return to `org-read-date' with the date currently selected.
15371 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15372 (interactive)
15373 (when (calendar-cursor-to-date)
15374 (let* ((date (calendar-cursor-to-date))
15375 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15376 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15377 (if (active-minibuffer-window) (exit-minibuffer))))
15379 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15380 "Insert a date stamp for the date given by the internal TIME.
15381 WITH-HM means use the stamp format that includes the time of the day.
15382 INACTIVE means use square brackets instead of angular ones, so that the
15383 stamp will not contribute to the agenda.
15384 PRE and POST are optional strings to be inserted before and after the
15385 stamp.
15386 The command returns the inserted time stamp."
15387 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15388 stamp)
15389 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15390 (insert-before-markers (or pre ""))
15391 (when (listp extra)
15392 (setq extra (car extra))
15393 (if (and (stringp extra)
15394 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15395 (setq extra (format "-%02d:%02d"
15396 (string-to-number (match-string 1 extra))
15397 (string-to-number (match-string 2 extra))))
15398 (setq extra nil)))
15399 (when extra
15400 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15401 (insert-before-markers (setq stamp (format-time-string fmt time)))
15402 (insert-before-markers (or post ""))
15403 (setq org-last-inserted-timestamp stamp)))
15405 (defun org-toggle-time-stamp-overlays ()
15406 "Toggle the use of custom time stamp formats."
15407 (interactive)
15408 (setq org-display-custom-times (not org-display-custom-times))
15409 (unless org-display-custom-times
15410 (let ((p (point-min)) (bmp (buffer-modified-p)))
15411 (while (setq p (next-single-property-change p 'display))
15412 (if (and (get-text-property p 'display)
15413 (eq (get-text-property p 'face) 'org-date))
15414 (remove-text-properties
15415 p (setq p (next-single-property-change p 'display))
15416 '(display t))))
15417 (set-buffer-modified-p bmp)))
15418 (if (featurep 'xemacs)
15419 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15420 (org-restart-font-lock)
15421 (setq org-table-may-need-update t)
15422 (if org-display-custom-times
15423 (message "Time stamps are overlaid with custom format")
15424 (message "Time stamp overlays removed")))
15426 (defun org-display-custom-time (beg end)
15427 "Overlay modified time stamp format over timestamp between BEG and END."
15428 (let* ((ts (buffer-substring beg end))
15429 t1 w1 with-hm tf time str w2 (off 0))
15430 (save-match-data
15431 (setq t1 (org-parse-time-string ts t))
15432 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15433 (setq off (- (match-end 0) (match-beginning 0)))))
15434 (setq end (- end off))
15435 (setq w1 (- end beg)
15436 with-hm (and (nth 1 t1) (nth 2 t1))
15437 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15438 time (org-fix-decoded-time t1)
15439 str (org-add-props
15440 (format-time-string
15441 (substring tf 1 -1) (apply 'encode-time time))
15442 nil 'mouse-face 'highlight)
15443 w2 (length str))
15444 (if (not (= w2 w1))
15445 (add-text-properties (1+ beg) (+ 2 beg)
15446 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15447 (if (featurep 'xemacs)
15448 (progn
15449 (put-text-property beg end 'invisible t)
15450 (put-text-property beg end 'end-glyph (make-glyph str)))
15451 (put-text-property beg end 'display str))))
15453 (defun org-translate-time (string)
15454 "Translate all timestamps in STRING to custom format.
15455 But do this only if the variable `org-display-custom-times' is set."
15456 (when org-display-custom-times
15457 (save-match-data
15458 (let* ((start 0)
15459 (re org-ts-regexp-both)
15460 t1 with-hm inactive tf time str beg end)
15461 (while (setq start (string-match re string start))
15462 (setq beg (match-beginning 0)
15463 end (match-end 0)
15464 t1 (save-match-data
15465 (org-parse-time-string (substring string beg end) t))
15466 with-hm (and (nth 1 t1) (nth 2 t1))
15467 inactive (equal (substring string beg (1+ beg)) "[")
15468 tf (funcall (if with-hm 'cdr 'car)
15469 org-time-stamp-custom-formats)
15470 time (org-fix-decoded-time t1)
15471 str (format-time-string
15472 (concat
15473 (if inactive "[" "<") (substring tf 1 -1)
15474 (if inactive "]" ">"))
15475 (apply 'encode-time time))
15476 string (replace-match str t t string)
15477 start (+ start (length str)))))))
15478 string)
15480 (defun org-fix-decoded-time (time)
15481 "Set 0 instead of nil for the first 6 elements of time.
15482 Don't touch the rest."
15483 (let ((n 0))
15484 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15486 (defun org-days-to-time (timestamp-string)
15487 "Difference between TIMESTAMP-STRING and now in days."
15488 (- (time-to-days (org-time-string-to-time timestamp-string))
15489 (time-to-days (current-time))))
15491 (defun org-deadline-close (timestamp-string &optional ndays)
15492 "Is the time in TIMESTAMP-STRING close to the current date?"
15493 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15494 (and (< (org-days-to-time timestamp-string) ndays)
15495 (not (org-entry-is-done-p))))
15497 (defun org-get-wdays (ts)
15498 "Get the deadline lead time appropriate for timestring TS."
15499 (cond
15500 ((<= org-deadline-warning-days 0)
15501 ;; 0 or negative, enforce this value no matter what
15502 (- org-deadline-warning-days))
15503 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15504 ;; lead time is specified.
15505 (floor (* (string-to-number (match-string 1 ts))
15506 (cdr (assoc (match-string 2 ts)
15507 '(("d" . 1) ("w" . 7)
15508 ("m" . 30.4) ("y" . 365.25)))))))
15509 ;; go for the default.
15510 (t org-deadline-warning-days)))
15512 (defun org-calendar-select-mouse (ev)
15513 "Return to `org-read-date' with the date currently selected.
15514 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15515 (interactive "e")
15516 (mouse-set-point ev)
15517 (when (calendar-cursor-to-date)
15518 (let* ((date (calendar-cursor-to-date))
15519 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15520 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15521 (if (active-minibuffer-window) (exit-minibuffer))))
15523 (defun org-check-deadlines (ndays)
15524 "Check if there are any deadlines due or past due.
15525 A deadline is considered due if it happens within `org-deadline-warning-days'
15526 days from today's date. If the deadline appears in an entry marked DONE,
15527 it is not shown. The prefix arg NDAYS can be used to test that many
15528 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15529 (interactive "P")
15530 (let* ((org-warn-days
15531 (cond
15532 ((equal ndays '(4)) 100000)
15533 (ndays (prefix-numeric-value ndays))
15534 (t (abs org-deadline-warning-days))))
15535 (case-fold-search nil)
15536 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15537 (callback
15538 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15540 (message "%d deadlines past-due or due within %d days"
15541 (org-occur regexp nil callback)
15542 org-warn-days)))
15544 (defun org-check-before-date (date)
15545 "Check if there are deadlines or scheduled entries before DATE."
15546 (interactive (list (org-read-date)))
15547 (let ((case-fold-search nil)
15548 (regexp (concat "\\<\\(" org-deadline-string
15549 "\\|" org-scheduled-string
15550 "\\) *<\\([^>]+\\)>"))
15551 (callback
15552 (lambda () (time-less-p
15553 (org-time-string-to-time (match-string 2))
15554 (org-time-string-to-time date)))))
15555 (message "%d entries before %s"
15556 (org-occur regexp nil callback) date)))
15558 (defun org-check-after-date (date)
15559 "Check if there are deadlines or scheduled entries after DATE."
15560 (interactive (list (org-read-date)))
15561 (let ((case-fold-search nil)
15562 (regexp (concat "\\<\\(" org-deadline-string
15563 "\\|" org-scheduled-string
15564 "\\) *<\\([^>]+\\)>"))
15565 (callback
15566 (lambda () (not
15567 (time-less-p
15568 (org-time-string-to-time (match-string 2))
15569 (org-time-string-to-time date))))))
15570 (message "%d entries after %s"
15571 (org-occur regexp nil callback) date)))
15573 (defun org-check-dates-range (start-date end-date)
15574 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15575 (interactive (list (org-read-date nil nil nil "Range starts")
15576 (org-read-date nil nil nil "Range end")))
15577 (let ((case-fold-search nil)
15578 (regexp (concat "\\<\\(" org-deadline-string
15579 "\\|" org-scheduled-string
15580 "\\) *<\\([^>]+\\)>"))
15581 (callback
15582 (lambda ()
15583 (let ((match (match-string 2)))
15584 (and
15585 (not (time-less-p
15586 (org-time-string-to-time match)
15587 (org-time-string-to-time start-date)))
15588 (time-less-p
15589 (org-time-string-to-time match)
15590 (org-time-string-to-time end-date)))))))
15591 (message "%d entries between %s and %s"
15592 (org-occur regexp nil callback) start-date end-date)))
15594 (defun org-evaluate-time-range (&optional to-buffer)
15595 "Evaluate a time range by computing the difference between start and end.
15596 Normally the result is just printed in the echo area, but with prefix arg
15597 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15598 If the time range is actually in a table, the result is inserted into the
15599 next column.
15600 For time difference computation, a year is assumed to be exactly 365
15601 days in order to avoid rounding problems."
15602 (interactive "P")
15604 (org-clock-update-time-maybe)
15605 (save-excursion
15606 (unless (org-at-date-range-p t)
15607 (goto-char (point-at-bol))
15608 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15609 (if (not (org-at-date-range-p t))
15610 (error "Not at a time-stamp range, and none found in current line")))
15611 (let* ((ts1 (match-string 1))
15612 (ts2 (match-string 2))
15613 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15614 (match-end (match-end 0))
15615 (time1 (org-time-string-to-time ts1))
15616 (time2 (org-time-string-to-time ts2))
15617 (t1 (org-float-time time1))
15618 (t2 (org-float-time time2))
15619 (diff (abs (- t2 t1)))
15620 (negative (< (- t2 t1) 0))
15621 ;; (ys (floor (* 365 24 60 60)))
15622 (ds (* 24 60 60))
15623 (hs (* 60 60))
15624 (fy "%dy %dd %02d:%02d")
15625 (fy1 "%dy %dd")
15626 (fd "%dd %02d:%02d")
15627 (fd1 "%dd")
15628 (fh "%02d:%02d")
15629 y d h m align)
15630 (if havetime
15631 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15633 d (floor (/ diff ds)) diff (mod diff ds)
15634 h (floor (/ diff hs)) diff (mod diff hs)
15635 m (floor (/ diff 60)))
15636 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15638 d (floor (+ (/ diff ds) 0.5))
15639 h 0 m 0))
15640 (if (not to-buffer)
15641 (message "%s" (org-make-tdiff-string y d h m))
15642 (if (org-at-table-p)
15643 (progn
15644 (goto-char match-end)
15645 (setq align t)
15646 (and (looking-at " *|") (goto-char (match-end 0))))
15647 (goto-char match-end))
15648 (if (looking-at
15649 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15650 (replace-match ""))
15651 (if negative (insert " -"))
15652 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15653 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15654 (insert " " (format fh h m))))
15655 (if align (org-table-align))
15656 (message "Time difference inserted")))))
15658 (defun org-make-tdiff-string (y d h m)
15659 (let ((fmt "")
15660 (l nil))
15661 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15662 l (push y l)))
15663 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15664 l (push d l)))
15665 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15666 l (push h l)))
15667 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15668 l (push m l)))
15669 (apply 'format fmt (nreverse l))))
15671 (defun org-time-string-to-time (s &optional buffer pos)
15672 (condition-case errdata
15673 (apply 'encode-time (org-parse-time-string s))
15674 (error (error "Bad timestamp `%s'%s\nError was: %s"
15675 s (if (not (and buffer pos))
15677 (format " at %d in buffer `%s'" pos buffer))
15678 (cdr errdata)))))
15680 (defun org-time-string-to-seconds (s)
15681 (org-float-time (org-time-string-to-time s)))
15683 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15684 "Convert a time stamp to an absolute day number.
15685 If there is a specifier for a cyclic time stamp, get the closest date to
15686 DAYNR.
15687 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15688 The variable date is bound by the calendar when this is called."
15689 (cond
15690 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15691 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15692 daynr
15693 (+ daynr 1000)))
15694 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15695 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15696 (time-to-days (current-time))) (match-string 0 s)
15697 prefer show-all))
15698 (t (time-to-days
15699 (condition-case errdata
15700 (apply 'encode-time (org-parse-time-string s))
15701 (error (error "Bad timestamp `%s'%s\nError was: %s"
15702 s (if (not (and buffer pos))
15704 (format " at %d in buffer `%s'" pos buffer))
15705 (cdr errdata))))))))
15707 (defun org-days-to-iso-week (days)
15708 "Return the iso week number."
15709 (require 'cal-iso)
15710 (car (calendar-iso-from-absolute days)))
15712 (defun org-small-year-to-year (year)
15713 "Convert 2-digit years into 4-digit years.
15714 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15715 The year 2000 cannot be abbreviated. Any year larger than 99
15716 is returned unchanged."
15717 (if (< year 38)
15718 (setq year (+ 2000 year))
15719 (if (< year 100)
15720 (setq year (+ 1900 year))))
15721 year)
15723 (defun org-time-from-absolute (d)
15724 "Return the time corresponding to date D.
15725 D may be an absolute day number, or a calendar-type list (month day year)."
15726 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15727 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15729 (defun org-calendar-holiday ()
15730 "List of holidays, for Diary display in Org-mode."
15731 (require 'holidays)
15732 (let ((hl (funcall
15733 (if (fboundp 'calendar-check-holidays)
15734 'calendar-check-holidays 'check-calendar-holidays) date)))
15735 (if hl (mapconcat 'identity hl "; "))))
15737 (defun org-diary-sexp-entry (sexp entry date)
15738 "Process a SEXP diary ENTRY for DATE."
15739 (require 'diary-lib)
15740 (let ((result (if calendar-debug-sexp
15741 (let ((stack-trace-on-error t))
15742 (eval (car (read-from-string sexp))))
15743 (condition-case nil
15744 (eval (car (read-from-string sexp)))
15745 (error
15746 (beep)
15747 (message "Bad sexp at line %d in %s: %s"
15748 (org-current-line)
15749 (buffer-file-name) sexp)
15750 (sleep-for 2))))))
15751 (cond ((stringp result) (split-string result "; "))
15752 ((and (consp result)
15753 (not (consp (cdr result)))
15754 (stringp (cdr result))) (cdr result))
15755 ((and (consp result)
15756 (stringp (car result))) result)
15757 (result entry)
15758 (t nil))))
15760 (defun org-diary-to-ical-string (frombuf)
15761 "Get iCalendar entries from diary entries in buffer FROMBUF.
15762 This uses the icalendar.el library."
15763 (let* ((tmpdir (if (featurep 'xemacs)
15764 (temp-directory)
15765 temporary-file-directory))
15766 (tmpfile (make-temp-name
15767 (expand-file-name "orgics" tmpdir)))
15768 buf rtn b e)
15769 (with-current-buffer frombuf
15770 (icalendar-export-region (point-min) (point-max) tmpfile)
15771 (setq buf (find-buffer-visiting tmpfile))
15772 (set-buffer buf)
15773 (goto-char (point-min))
15774 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15775 (setq b (match-beginning 0)))
15776 (goto-char (point-max))
15777 (if (re-search-backward "^END:VEVENT" nil t)
15778 (setq e (match-end 0)))
15779 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15780 (kill-buffer buf)
15781 (delete-file tmpfile)
15782 rtn))
15784 (defun org-closest-date (start current change prefer show-all)
15785 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15786 When PREFER is `past', return a date that is either CURRENT or past.
15787 When PREFER is `future', return a date that is either CURRENT or future.
15788 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15789 ;; Make the proper lists from the dates
15790 (catch 'exit
15791 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15792 dn dw sday cday n1 n2 n0
15793 d m y y1 y2 date1 date2 nmonths nm ny m2)
15795 (setq start (org-date-to-gregorian start)
15796 current (org-date-to-gregorian
15797 (if show-all
15798 current
15799 (time-to-days (current-time))))
15800 sday (calendar-absolute-from-gregorian start)
15801 cday (calendar-absolute-from-gregorian current))
15803 (if (<= cday sday) (throw 'exit sday))
15805 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15806 (setq dn (string-to-number (match-string 1 change))
15807 dw (cdr (assoc (match-string 2 change) a1)))
15808 (error "Invalid change specifier: %s" change))
15809 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15810 (cond
15811 ((eq dw 'day)
15812 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15813 n2 (+ n1 dn)))
15814 ((eq dw 'year)
15815 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15816 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15817 (setq date1 (list m d y1)
15818 n1 (calendar-absolute-from-gregorian date1)
15819 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15820 n2 (calendar-absolute-from-gregorian date2)))
15821 ((eq dw 'month)
15822 ;; approx number of month between the two dates
15823 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15824 ;; How often does dn fit in there?
15825 (setq d (nth 1 start) m (car start) y (nth 2 start)
15826 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15827 m (+ m nm)
15828 ny (floor (/ m 12))
15829 y (+ y ny)
15830 m (- m (* ny 12)))
15831 (while (> m 12) (setq m (- m 12) y (1+ y)))
15832 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15833 (setq m2 (+ m dn) y2 y)
15834 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15835 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15836 (while (<= n2 cday)
15837 (setq n1 n2 m m2 y y2)
15838 (setq m2 (+ m dn) y2 y)
15839 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15840 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15841 ;; Make sure n1 is the earlier date
15842 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15843 (if show-all
15844 (cond
15845 ((eq prefer 'past) (if (= cday n2) n2 n1))
15846 ((eq prefer 'future) (if (= cday n1) n1 n2))
15847 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15848 (cond
15849 ((eq prefer 'past) (if (= cday n2) n2 n1))
15850 ((eq prefer 'future) (if (= cday n1) n1 n2))
15851 (t (if (= cday n1) n1 n2)))))))
15853 (defun org-date-to-gregorian (date)
15854 "Turn any specification of DATE into a Gregorian date for the calendar."
15855 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15856 ((and (listp date) (= (length date) 3)) date)
15857 ((stringp date)
15858 (setq date (org-parse-time-string date))
15859 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15860 ((listp date)
15861 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15863 (defun org-parse-time-string (s &optional nodefault)
15864 "Parse the standard Org-mode time string.
15865 This should be a lot faster than the normal `parse-time-string'.
15866 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15867 hour and minute fields will be nil if not given."
15868 (if (string-match org-ts-regexp0 s)
15869 (list 0
15870 (if (or (match-beginning 8) (not nodefault))
15871 (string-to-number (or (match-string 8 s) "0")))
15872 (if (or (match-beginning 7) (not nodefault))
15873 (string-to-number (or (match-string 7 s) "0")))
15874 (string-to-number (match-string 4 s))
15875 (string-to-number (match-string 3 s))
15876 (string-to-number (match-string 2 s))
15877 nil nil nil)
15878 (error "Not a standard Org-mode time string: %s" s)))
15880 (defun org-timestamp-up (&optional arg)
15881 "Increase the date item at the cursor by one.
15882 If the cursor is on the year, change the year. If it is on the month,
15883 the day or the time, change that.
15884 With prefix ARG, change by that many units."
15885 (interactive "p")
15886 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15888 (defun org-timestamp-down (&optional arg)
15889 "Decrease the date item at the cursor by one.
15890 If the cursor is on the year, change the year. If it is on the month,
15891 the day or the time, change that.
15892 With prefix ARG, change by that many units."
15893 (interactive "p")
15894 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15896 (defun org-timestamp-up-day (&optional arg)
15897 "Increase the date in the time stamp by one day.
15898 With prefix ARG, change that many days."
15899 (interactive "p")
15900 (if (and (not (org-at-timestamp-p t))
15901 (org-at-heading-p))
15902 (org-todo 'up)
15903 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15905 (defun org-timestamp-down-day (&optional arg)
15906 "Decrease the date in the time stamp by one day.
15907 With prefix ARG, change that many days."
15908 (interactive "p")
15909 (if (and (not (org-at-timestamp-p t))
15910 (org-at-heading-p))
15911 (org-todo 'down)
15912 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15914 (defun org-at-timestamp-p (&optional inactive-ok)
15915 "Determine if the cursor is in or at a timestamp."
15916 (interactive)
15917 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15918 (pos (point))
15919 (ans (or (looking-at tsr)
15920 (save-excursion
15921 (skip-chars-backward "^[<\n\r\t")
15922 (if (> (point) (point-min)) (backward-char 1))
15923 (and (looking-at tsr)
15924 (> (- (match-end 0) pos) -1))))))
15925 (and ans
15926 (boundp 'org-ts-what)
15927 (setq org-ts-what
15928 (cond
15929 ((= pos (match-beginning 0)) 'bracket)
15930 ;; Point is considered to be "on the bracket" whether
15931 ;; it's really on it or right after it.
15932 ((or (= pos (1- (match-end 0)))
15933 (= pos (match-end 0))) 'bracket)
15934 ((org-pos-in-match-range pos 2) 'year)
15935 ((org-pos-in-match-range pos 3) 'month)
15936 ((org-pos-in-match-range pos 7) 'hour)
15937 ((org-pos-in-match-range pos 8) 'minute)
15938 ((or (org-pos-in-match-range pos 4)
15939 (org-pos-in-match-range pos 5)) 'day)
15940 ((and (> pos (or (match-end 8) (match-end 5)))
15941 (< pos (match-end 0)))
15942 (- pos (or (match-end 8) (match-end 5))))
15943 (t 'day))))
15944 ans))
15946 (defun org-toggle-timestamp-type ()
15947 "Toggle the type (<active> or [inactive]) of a time stamp."
15948 (interactive)
15949 (when (org-at-timestamp-p t)
15950 (let ((beg (match-beginning 0)) (end (match-end 0))
15951 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15952 (save-excursion
15953 (goto-char beg)
15954 (while (re-search-forward "[][<>]" end t)
15955 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15956 t t)))
15957 (message "Timestamp is now %sactive"
15958 (if (equal (char-after beg) ?<) "" "in")))))
15960 (defun org-timestamp-change (n &optional what updown)
15961 "Change the date in the time stamp at point.
15962 The date will be changed by N times WHAT. WHAT can be `day', `month',
15963 `year', `minute', `second'. If WHAT is not given, the cursor position
15964 in the timestamp determines what will be changed."
15965 (let ((origin (point)) origin-cat
15966 with-hm inactive
15967 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15968 org-ts-what
15969 extra rem
15970 ts time time0)
15971 (if (not (org-at-timestamp-p t))
15972 (error "Not at a timestamp"))
15973 (if (and (not what) (eq org-ts-what 'bracket))
15974 (org-toggle-timestamp-type)
15975 ;; Point isn't on brackets. Remember the part of the time-stamp
15976 ;; the point was in. Indeed, size of time-stamps may change,
15977 ;; but point must be kept in the same category nonetheless.
15978 (setq origin-cat org-ts-what)
15979 (if (and (not what) (not (eq org-ts-what 'day))
15980 org-display-custom-times
15981 (get-text-property (point) 'display)
15982 (not (get-text-property (1- (point)) 'display)))
15983 (setq org-ts-what 'day))
15984 (setq org-ts-what (or what org-ts-what)
15985 inactive (= (char-after (match-beginning 0)) ?\[)
15986 ts (match-string 0))
15987 (replace-match "")
15988 (if (string-match
15989 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15991 (setq extra (match-string 1 ts)))
15992 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15993 (setq with-hm t))
15994 (setq time0 (org-parse-time-string ts))
15995 (when (and updown
15996 (eq org-ts-what 'minute)
15997 (not current-prefix-arg))
15998 ;; This looks like s-up and s-down. Change by one rounding step.
15999 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16000 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16001 (setcar (cdr time0) (+ (nth 1 time0)
16002 (if (> n 0) (- rem) (- dm rem))))))
16003 (setq time
16004 (encode-time (or (car time0) 0)
16005 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16006 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16007 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16008 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16009 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16010 (nthcdr 6 time0)))
16011 (when (and (member org-ts-what '(hour minute))
16012 extra
16013 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16014 (setq extra (org-modify-ts-extra
16015 extra
16016 (if (eq org-ts-what 'hour) 2 5)
16017 n dm)))
16018 (when (integerp org-ts-what)
16019 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16020 (if (eq what 'calendar)
16021 (let ((cal-date (org-get-date-from-calendar)))
16022 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16023 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16024 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16025 (setcar time0 (or (car time0) 0))
16026 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16027 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16028 (setq time (apply 'encode-time time0))))
16029 ;; Insert the new time-stamp, and ensure point stays in the same
16030 ;; category as before (i.e. not after the last position in that
16031 ;; category).
16032 (let ((pos (point)))
16033 ;; Stay before inserted string. `save-excursion' is of no use.
16034 (setq org-last-changed-timestamp
16035 (org-insert-time-stamp time with-hm inactive nil nil extra))
16036 (goto-char pos))
16037 (save-match-data
16038 (looking-at org-ts-regexp3)
16039 (goto-char (cond
16040 ;; `day' category ends before `hour' if any, or at
16041 ;; the end of the day name.
16042 ((eq origin-cat 'day)
16043 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16044 ((eq origin-cat 'hour) (min (match-end 7) origin))
16045 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16046 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16047 ;; `year' and `month' have both fixed size: point
16048 ;; couldn't have moved into another part.
16049 (t origin))))
16050 ;; Update clock if on a CLOCK line.
16051 (org-clock-update-time-maybe)
16052 ;; Try to recenter the calendar window, if any.
16053 (if (and org-calendar-follow-timestamp-change
16054 (get-buffer-window "*Calendar*" t)
16055 (memq org-ts-what '(day month year)))
16056 (org-recenter-calendar (time-to-days time))))))
16058 (defun org-modify-ts-extra (s pos n dm)
16059 "Change the different parts of the lead-time and repeat fields in timestamp."
16060 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16061 ng h m new rem)
16062 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16063 (cond
16064 ((or (org-pos-in-match-range pos 2)
16065 (org-pos-in-match-range pos 3))
16066 (setq m (string-to-number (match-string 3 s))
16067 h (string-to-number (match-string 2 s)))
16068 (if (org-pos-in-match-range pos 2)
16069 (setq h (+ h n))
16070 (setq n (* dm (org-no-warnings (signum n))))
16071 (when (not (= 0 (setq rem (% m dm))))
16072 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16073 (setq m (+ m n)))
16074 (if (< m 0) (setq m (+ m 60) h (1- h)))
16075 (if (> m 59) (setq m (- m 60) h (1+ h)))
16076 (setq h (min 24 (max 0 h)))
16077 (setq ng 1 new (format "-%02d:%02d" h m)))
16078 ((org-pos-in-match-range pos 6)
16079 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16080 ((org-pos-in-match-range pos 5)
16081 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16083 ((org-pos-in-match-range pos 9)
16084 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16085 ((org-pos-in-match-range pos 8)
16086 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16088 (when ng
16089 (setq s (concat
16090 (substring s 0 (match-beginning ng))
16092 (substring s (match-end ng))))))
16095 (defun org-recenter-calendar (date)
16096 "If the calendar is visible, recenter it to DATE."
16097 (let ((cwin (get-buffer-window "*Calendar*" t)))
16098 (when cwin
16099 (let ((calendar-move-hook nil))
16100 (with-selected-window cwin
16101 (calendar-goto-date (if (listp date) date
16102 (calendar-gregorian-from-absolute date))))))))
16104 (defun org-goto-calendar (&optional arg)
16105 "Go to the Emacs calendar at the current date.
16106 If there is a time stamp in the current line, go to that date.
16107 A prefix ARG can be used to force the current date."
16108 (interactive "P")
16109 (let ((tsr org-ts-regexp) diff
16110 (calendar-move-hook nil)
16111 (calendar-view-holidays-initially-flag nil)
16112 (calendar-view-diary-initially-flag nil))
16113 (if (or (org-at-timestamp-p)
16114 (save-excursion
16115 (beginning-of-line 1)
16116 (looking-at (concat ".*" tsr))))
16117 (let ((d1 (time-to-days (current-time)))
16118 (d2 (time-to-days
16119 (org-time-string-to-time (match-string 1)))))
16120 (setq diff (- d2 d1))))
16121 (calendar)
16122 (calendar-goto-today)
16123 (if (and diff (not arg)) (calendar-forward-day diff))))
16125 (defun org-get-date-from-calendar ()
16126 "Return a list (month day year) of date at point in calendar."
16127 (with-current-buffer "*Calendar*"
16128 (save-match-data
16129 (calendar-cursor-to-date))))
16131 (defun org-date-from-calendar ()
16132 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16133 If there is already a time stamp at the cursor position, update it."
16134 (interactive)
16135 (if (org-at-timestamp-p t)
16136 (org-timestamp-change 0 'calendar)
16137 (let ((cal-date (org-get-date-from-calendar)))
16138 (org-insert-time-stamp
16139 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16141 (defun org-minutes-to-hh:mm-string (m)
16142 "Compute H:MM from a number of minutes."
16143 (let ((h (/ m 60)))
16144 (setq m (- m (* 60 h)))
16145 (format org-time-clocksum-format h m)))
16147 (defun org-hh:mm-string-to-minutes (s)
16148 "Convert a string H:MM to a number of minutes.
16149 If the string is just a number, interpret it as minutes.
16150 In fact, the first hh:mm or number in the string will be taken,
16151 there can be extra stuff in the string.
16152 If no number is found, the return value is 0."
16153 (cond
16154 ((integerp s) s)
16155 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16156 (+ (* (string-to-number (match-string 1 s)) 60)
16157 (string-to-number (match-string 2 s))))
16158 ((string-match "\\([0-9]+\\)" s)
16159 (string-to-number (match-string 1 s)))
16160 (t 0)))
16162 (defcustom org-effort-durations
16163 `(("h" . 60)
16164 ("d" . ,(* 60 8))
16165 ("w" . ,(* 60 8 5))
16166 ("m" . ,(* 60 8 5 4))
16167 ("y" . ,(* 60 8 5 40)))
16168 "Conversion factor to minutes for an effort modifier.
16170 Each entry has the form (MODIFIER . MINUTES).
16172 In an effort string, a number followed by MODIFIER is multiplied
16173 by the specified number of MINUTES to obtain an effort in
16174 minutes.
16176 For example, if the value of this variable is ((\"hours\" . 60)), then an
16177 effort string \"2hours\" is equivalent to 120 minutes."
16178 :group 'org-agenda
16179 :type '(alist :key-type (string :tag "Modifier")
16180 :value-type (number :tag "Minutes")))
16182 (defun org-duration-string-to-minutes (s)
16183 "Convert a duration string S to minutes.
16185 A bare number is interpreted as minutes, modifiers can be set by
16186 customizing `org-effort-durations' (which see).
16188 Entries containing a colon are interpreted as H:MM by
16189 `org-hh:mm-string-to-minutes'."
16190 (let ((result 0)
16191 (re (concat "\\([0-9]+\\) *\\("
16192 (regexp-opt (mapcar 'car org-effort-durations))
16193 "\\)")))
16194 (while (string-match re s)
16195 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16196 (string-to-number (match-string 1 s))))
16197 (setq s (replace-match "" nil t s)))
16198 (incf result (org-hh:mm-string-to-minutes s))
16199 result))
16201 ;;;; Files
16203 (defun org-save-all-org-buffers ()
16204 "Save all Org-mode buffers without user confirmation."
16205 (interactive)
16206 (message "Saving all Org-mode buffers...")
16207 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16208 (when (featurep 'org-id) (org-id-locations-save))
16209 (message "Saving all Org-mode buffers... done"))
16211 (defun org-revert-all-org-buffers ()
16212 "Revert all Org-mode buffers.
16213 Prompt for confirmation when there are unsaved changes.
16214 Be sure you know what you are doing before letting this function
16215 overwrite your changes.
16217 This function is useful in a setup where one tracks org files
16218 with a version control system, to revert on one machine after pulling
16219 changes from another. I believe the procedure must be like this:
16221 1. M-x org-save-all-org-buffers
16222 2. Pull changes from the other machine, resolve conflicts
16223 3. M-x org-revert-all-org-buffers"
16224 (interactive)
16225 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16226 (error "Abort"))
16227 (save-excursion
16228 (save-window-excursion
16229 (mapc
16230 (lambda (b)
16231 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16232 (with-current-buffer b buffer-file-name))
16233 (org-pop-to-buffer-same-window b)
16234 (revert-buffer t 'no-confirm)))
16235 (buffer-list))
16236 (when (and (featurep 'org-id) org-id-track-globally)
16237 (org-id-locations-load)))))
16239 ;;;; Agenda files
16241 ;;;###autoload
16242 (defun org-switchb (&optional arg)
16243 "Switch between Org buffers.
16244 With one prefix argument, restrict available buffers to files.
16245 With two prefix arguments, restrict available buffers to agenda files.
16247 Defaults to `iswitchb' for buffer name completion.
16248 Set `org-completion-use-ido' to make it use ido instead."
16249 (interactive "P")
16250 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16251 ((equal arg '(16)) (org-buffer-list 'agenda))
16252 (t (org-buffer-list))))
16253 (org-completion-use-iswitchb org-completion-use-iswitchb)
16254 (org-completion-use-ido org-completion-use-ido))
16255 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16256 (setq org-completion-use-iswitchb t))
16257 (org-pop-to-buffer-same-window
16258 (org-icompleting-read "Org buffer: "
16259 (mapcar 'list (mapcar 'buffer-name blist))
16260 nil t))))
16262 ;;; Define some older names previously used for this functionality
16263 ;;;###autoload
16264 (defalias 'org-ido-switchb 'org-switchb)
16265 ;;;###autoload
16266 (defalias 'org-iswitchb 'org-switchb)
16268 (defun org-buffer-list (&optional predicate exclude-tmp)
16269 "Return a list of Org buffers.
16270 PREDICATE can be `export', `files' or `agenda'.
16272 export restrict the list to Export buffers.
16273 files restrict the list to buffers visiting Org files.
16274 agenda restrict the list to buffers visiting agenda files.
16276 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16277 (let* ((bfn nil)
16278 (agenda-files (and (eq predicate 'agenda)
16279 (mapcar 'file-truename (org-agenda-files t))))
16280 (filter
16281 (cond
16282 ((eq predicate 'files)
16283 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16284 ((eq predicate 'export)
16285 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16286 ((eq predicate 'agenda)
16287 (lambda (b)
16288 (with-current-buffer b
16289 (and (eq major-mode 'org-mode)
16290 (setq bfn (buffer-file-name b))
16291 (member (file-truename bfn) agenda-files)))))
16292 (t (lambda (b) (with-current-buffer b
16293 (or (eq major-mode 'org-mode)
16294 (string-match "\*Org .*Export"
16295 (buffer-name b)))))))))
16296 (delq nil
16297 (mapcar
16298 (lambda(b)
16299 (if (and (funcall filter b)
16300 (or (not exclude-tmp)
16301 (not (string-match "tmp" (buffer-name b)))))
16303 nil))
16304 (buffer-list)))))
16306 (defun org-agenda-files (&optional unrestricted archives)
16307 "Get the list of agenda files.
16308 Optional UNRESTRICTED means return the full list even if a restriction
16309 is currently in place.
16310 When ARCHIVES is t, include all archive files that are really being
16311 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16312 `org-agenda-archives-mode' is t."
16313 (let ((files
16314 (cond
16315 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16316 ((stringp org-agenda-files) (org-read-agenda-file-list))
16317 ((listp org-agenda-files) org-agenda-files)
16318 (t (error "Invalid value of `org-agenda-files'")))))
16319 (setq files (apply 'append
16320 (mapcar (lambda (f)
16321 (if (file-directory-p f)
16322 (directory-files
16323 f t org-agenda-file-regexp)
16324 (list f)))
16325 files)))
16326 (when org-agenda-skip-unavailable-files
16327 (setq files (delq nil
16328 (mapcar (function
16329 (lambda (file)
16330 (and (file-readable-p file) file)))
16331 files))))
16332 (when (or (eq archives t)
16333 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16334 (setq files (org-add-archive-files files)))
16335 files))
16337 (defun org-agenda-file-p (&optional file)
16338 "Return non-nil, if FILE is an agenda file.
16339 If FILE is omitted, use the file associated with the current
16340 buffer."
16341 (member (or file (buffer-file-name))
16342 (org-agenda-files t)))
16344 (defun org-edit-agenda-file-list ()
16345 "Edit the list of agenda files.
16346 Depending on setup, this either uses customize to edit the variable
16347 `org-agenda-files', or it visits the file that is holding the list. In the
16348 latter case, the buffer is set up in a way that saving it automatically kills
16349 the buffer and restores the previous window configuration."
16350 (interactive)
16351 (if (stringp org-agenda-files)
16352 (let ((cw (current-window-configuration)))
16353 (find-file org-agenda-files)
16354 (org-set-local 'org-window-configuration cw)
16355 (org-add-hook 'after-save-hook
16356 (lambda ()
16357 (set-window-configuration
16358 (prog1 org-window-configuration
16359 (kill-buffer (current-buffer))))
16360 (org-install-agenda-files-menu)
16361 (message "New agenda file list installed"))
16362 nil 'local)
16363 (message "%s" (substitute-command-keys
16364 "Edit list and finish with \\[save-buffer]")))
16365 (customize-variable 'org-agenda-files)))
16367 (defun org-store-new-agenda-file-list (list)
16368 "Set new value for the agenda file list and save it correctly."
16369 (if (stringp org-agenda-files)
16370 (let ((fe (org-read-agenda-file-list t)) b u)
16371 (while (setq b (find-buffer-visiting org-agenda-files))
16372 (kill-buffer b))
16373 (with-temp-file org-agenda-files
16374 (insert
16375 (mapconcat
16376 (lambda (f) ;; Keep un-expanded entries.
16377 (if (setq u (assoc f fe))
16378 (cdr u)
16380 list "\n")
16381 "\n")))
16382 (let ((org-mode-hook nil) (org-inhibit-startup t)
16383 (org-insert-mode-line-in-empty-file nil))
16384 (setq org-agenda-files list)
16385 (customize-save-variable 'org-agenda-files org-agenda-files))))
16387 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16388 "Read the list of agenda files from a file.
16389 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16390 filenames, used by `org-store-new-agenda-file-list' to write back
16391 un-expanded file names."
16392 (when (file-directory-p org-agenda-files)
16393 (error "`org-agenda-files' cannot be a single directory"))
16394 (when (stringp org-agenda-files)
16395 (with-temp-buffer
16396 (insert-file-contents org-agenda-files)
16397 (mapcar
16398 (lambda (f)
16399 (let ((e (expand-file-name (substitute-in-file-name f)
16400 org-directory)))
16401 (if pair-with-expansion
16402 (cons e f)
16403 e)))
16404 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16406 ;;;###autoload
16407 (defun org-cycle-agenda-files ()
16408 "Cycle through the files in `org-agenda-files'.
16409 If the current buffer visits an agenda file, find the next one in the list.
16410 If the current buffer does not, find the first agenda file."
16411 (interactive)
16412 (let* ((fs (org-agenda-files t))
16413 (files (append fs (list (car fs))))
16414 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16415 file)
16416 (unless files (error "No agenda files"))
16417 (catch 'exit
16418 (while (setq file (pop files))
16419 (if (equal (file-truename file) tcf)
16420 (when (car files)
16421 (find-file (car files))
16422 (throw 'exit t))))
16423 (find-file (car fs)))
16424 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16426 (defun org-agenda-file-to-front (&optional to-end)
16427 "Move/add the current file to the top of the agenda file list.
16428 If the file is not present in the list, it is added to the front. If it is
16429 present, it is moved there. With optional argument TO-END, add/move to the
16430 end of the list."
16431 (interactive "P")
16432 (let ((org-agenda-skip-unavailable-files nil)
16433 (file-alist (mapcar (lambda (x)
16434 (cons (file-truename x) x))
16435 (org-agenda-files t)))
16436 (ctf (file-truename buffer-file-name))
16437 x had)
16438 (setq x (assoc ctf file-alist) had x)
16440 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16441 (if to-end
16442 (setq file-alist (append (delq x file-alist) (list x)))
16443 (setq file-alist (cons x (delq x file-alist))))
16444 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16445 (org-install-agenda-files-menu)
16446 (message "File %s to %s of agenda file list"
16447 (if had "moved" "added") (if to-end "end" "front"))))
16449 (defun org-remove-file (&optional file)
16450 "Remove current file from the list of files in variable `org-agenda-files'.
16451 These are the files which are being checked for agenda entries.
16452 Optional argument FILE means use this file instead of the current."
16453 (interactive)
16454 (let* ((org-agenda-skip-unavailable-files nil)
16455 (file (or file buffer-file-name))
16456 (true-file (file-truename file))
16457 (afile (abbreviate-file-name file))
16458 (files (delq nil (mapcar
16459 (lambda (x)
16460 (if (equal true-file
16461 (file-truename x))
16462 nil x))
16463 (org-agenda-files t)))))
16464 (if (not (= (length files) (length (org-agenda-files t))))
16465 (progn
16466 (org-store-new-agenda-file-list files)
16467 (org-install-agenda-files-menu)
16468 (message "Removed file: %s" afile))
16469 (message "File was not in list: %s (not removed)" afile))))
16471 (defun org-file-menu-entry (file)
16472 (vector file (list 'find-file file) t))
16474 (defun org-check-agenda-file (file)
16475 "Make sure FILE exists. If not, ask user what to do."
16476 (when (not (file-exists-p file))
16477 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16478 (abbreviate-file-name file))
16479 (let ((r (downcase (read-char-exclusive))))
16480 (cond
16481 ((equal r ?r)
16482 (org-remove-file file)
16483 (throw 'nextfile t))
16484 (t (error "Abort"))))))
16486 (defun org-get-agenda-file-buffer (file)
16487 "Get a buffer visiting FILE. If the buffer needs to be created, add
16488 it to the list of buffers which might be released later."
16489 (let ((buf (org-find-base-buffer-visiting file)))
16490 (if buf
16491 buf ; just return it
16492 ;; Make a new buffer and remember it
16493 (setq buf (find-file-noselect file))
16494 (if buf (push buf org-agenda-new-buffers))
16495 buf)))
16497 (defun org-release-buffers (blist)
16498 "Release all buffers in list, asking the user for confirmation when needed.
16499 When a buffer is unmodified, it is just killed. When modified, it is saved
16500 \(if the user agrees) and then killed."
16501 (let (buf file)
16502 (while (setq buf (pop blist))
16503 (setq file (buffer-file-name buf))
16504 (when (and (buffer-modified-p buf)
16505 file
16506 (y-or-n-p (format "Save file %s? " file)))
16507 (with-current-buffer buf (save-buffer)))
16508 (kill-buffer buf))))
16510 (defun org-prepare-agenda-buffers (files)
16511 "Create buffers for all agenda files, protect archived trees and comments."
16512 (interactive)
16513 (let ((pa '(:org-archived t))
16514 (pc '(:org-comment t))
16515 (pall '(:org-archived t :org-comment t))
16516 (inhibit-read-only t)
16517 (rea (concat ":" org-archive-tag ":"))
16518 bmp file re)
16519 (save-excursion
16520 (save-restriction
16521 (while (setq file (pop files))
16522 (catch 'nextfile
16523 (if (bufferp file)
16524 (set-buffer file)
16525 (org-check-agenda-file file)
16526 (set-buffer (org-get-agenda-file-buffer file)))
16527 (widen)
16528 (setq bmp (buffer-modified-p))
16529 (org-refresh-category-properties)
16530 (setq org-todo-keywords-for-agenda
16531 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16532 (setq org-done-keywords-for-agenda
16533 (append org-done-keywords-for-agenda org-done-keywords))
16534 (setq org-todo-keyword-alist-for-agenda
16535 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16536 (setq org-drawers-for-agenda
16537 (append org-drawers-for-agenda org-drawers))
16538 (setq org-tag-alist-for-agenda
16539 (append org-tag-alist-for-agenda org-tag-alist))
16541 (save-excursion
16542 (remove-text-properties (point-min) (point-max) pall)
16543 (when org-agenda-skip-archived-trees
16544 (goto-char (point-min))
16545 (while (re-search-forward rea nil t)
16546 (if (org-at-heading-p t)
16547 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16548 (goto-char (point-min))
16549 (setq re (format org-heading-keyword-regexp-format
16550 org-comment-string))
16551 (while (re-search-forward re nil t)
16552 (add-text-properties
16553 (match-beginning 0) (org-end-of-subtree t) pc)))
16554 (set-buffer-modified-p bmp)))))
16555 (setq org-todo-keywords-for-agenda
16556 (org-uniquify org-todo-keywords-for-agenda))
16557 (setq org-todo-keyword-alist-for-agenda
16558 (org-uniquify org-todo-keyword-alist-for-agenda)
16559 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16561 ;;;; Embedded LaTeX
16563 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16564 "Keymap for the minor `org-cdlatex-mode'.")
16566 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16567 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16568 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16569 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16570 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16572 (defvar org-cdlatex-texmathp-advice-is-done nil
16573 "Flag remembering if we have applied the advice to texmathp already.")
16575 (define-minor-mode org-cdlatex-mode
16576 "Toggle the minor `org-cdlatex-mode'.
16577 This mode supports entering LaTeX environment and math in LaTeX fragments
16578 in Org-mode.
16579 \\{org-cdlatex-mode-map}"
16580 nil " OCDL" nil
16581 (when org-cdlatex-mode
16582 (require 'cdlatex)
16583 (run-hooks 'cdlatex-mode-hook)
16584 (cdlatex-compute-tables))
16585 (unless org-cdlatex-texmathp-advice-is-done
16586 (setq org-cdlatex-texmathp-advice-is-done t)
16587 (defadvice texmathp (around org-math-always-on activate)
16588 "Always return t in org-mode buffers.
16589 This is because we want to insert math symbols without dollars even outside
16590 the LaTeX math segments. If Orgmode thinks that point is actually inside
16591 an embedded LaTeX fragment, let texmathp do its job.
16592 \\[org-cdlatex-mode-map]"
16593 (interactive)
16594 (let (p)
16595 (cond
16596 ((not (eq major-mode 'org-mode)) ad-do-it)
16597 ((eq this-command 'cdlatex-math-symbol)
16598 (setq ad-return-value t
16599 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16601 (let ((p (org-inside-LaTeX-fragment-p)))
16602 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16603 (setq ad-return-value t
16604 texmathp-why '("Org-mode embedded math" . 0))
16605 (if p ad-do-it)))))))))
16607 (defun turn-on-org-cdlatex ()
16608 "Unconditionally turn on `org-cdlatex-mode'."
16609 (org-cdlatex-mode 1))
16611 (defun org-inside-LaTeX-fragment-p ()
16612 "Test if point is inside a LaTeX fragment.
16613 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16614 sequence appearing also before point.
16615 Even though the matchers for math are configurable, this function assumes
16616 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16617 delimiters are skipped when they have been removed by customization.
16618 The return value is nil, or a cons cell with the delimiter and the
16619 position of this delimiter.
16621 This function does a reasonably good job, but can locally be fooled by
16622 for example currency specifications. For example it will assume being in
16623 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16624 fragments that are properly closed, but during editing, we have to live
16625 with the uncertainty caused by missing closing delimiters. This function
16626 looks only before point, not after."
16627 (catch 'exit
16628 (let ((pos (point))
16629 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16630 (lim (progn
16631 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16632 (point)))
16633 dd-on str (start 0) m re)
16634 (goto-char pos)
16635 (when dodollar
16636 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16637 re (nth 1 (assoc "$" org-latex-regexps)))
16638 (while (string-match re str start)
16639 (cond
16640 ((= (match-end 0) (length str))
16641 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16642 ((= (match-end 0) (- (length str) 5))
16643 (throw 'exit nil))
16644 (t (setq start (match-end 0))))))
16645 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16646 (goto-char pos)
16647 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16648 (and (match-beginning 2) (throw 'exit nil))
16649 ;; count $$
16650 (while (re-search-backward "\\$\\$" lim t)
16651 (setq dd-on (not dd-on)))
16652 (goto-char pos)
16653 (if dd-on (cons "$$" m))))))
16655 (defun org-inside-latex-macro-p ()
16656 "Is point inside a LaTeX macro or its arguments?"
16657 (save-match-data
16658 (org-in-regexp
16659 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16661 (defun org-try-cdlatex-tab ()
16662 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16663 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16664 - inside a LaTeX fragment, or
16665 - after the first word in a line, where an abbreviation expansion could
16666 insert a LaTeX environment."
16667 (when org-cdlatex-mode
16668 (cond
16669 ;; Before any word on the line: No expansion possible.
16670 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16671 ;; Just after first word on the line: Expand it. Make sure it
16672 ;; cannot happen on headlines, though.
16673 ((save-excursion
16674 (skip-chars-backward "a-zA-Z0-9*")
16675 (skip-chars-backward " \t")
16676 (and (bolp) (not (org-at-heading-p))))
16677 (cdlatex-tab) t)
16678 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16680 (defun org-cdlatex-underscore-caret (&optional arg)
16681 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16682 Revert to the normal definition outside of these fragments."
16683 (interactive "P")
16684 (if (org-inside-LaTeX-fragment-p)
16685 (call-interactively 'cdlatex-sub-superscript)
16686 (let (org-cdlatex-mode)
16687 (call-interactively (key-binding (vector last-input-event))))))
16689 (defun org-cdlatex-math-modify (&optional arg)
16690 "Execute `cdlatex-math-modify' in LaTeX fragments.
16691 Revert to the normal definition outside of these fragments."
16692 (interactive "P")
16693 (if (org-inside-LaTeX-fragment-p)
16694 (call-interactively 'cdlatex-math-modify)
16695 (let (org-cdlatex-mode)
16696 (call-interactively (key-binding (vector last-input-event))))))
16698 (defvar org-latex-fragment-image-overlays nil
16699 "List of overlays carrying the images of latex fragments.")
16700 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16702 (defun org-remove-latex-fragment-image-overlays ()
16703 "Remove all overlays with LaTeX fragment images in current buffer."
16704 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16705 (setq org-latex-fragment-image-overlays nil))
16707 (defun org-preview-latex-fragment (&optional subtree)
16708 "Preview the LaTeX fragment at point, or all locally or globally.
16709 If the cursor is in a LaTeX fragment, create the image and overlay
16710 it over the source code. If there is no fragment at point, display
16711 all fragments in the current text, from one headline to the next. With
16712 prefix SUBTREE, display all fragments in the current subtree. With a
16713 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16714 the cursor is before the first headline,
16715 display all fragments in the buffer.
16716 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16717 (interactive "P")
16718 (unless buffer-file-name
16719 (error "Can't preview LaTeX fragment in a non-file buffer"))
16720 (org-remove-latex-fragment-image-overlays)
16721 (save-excursion
16722 (save-restriction
16723 (let (beg end at msg)
16724 (cond
16725 ((or (equal subtree '(16))
16726 (not (save-excursion
16727 (re-search-backward org-outline-regexp-bol nil t))))
16728 (setq beg (point-min) end (point-max)
16729 msg "Creating images for buffer...%s"))
16730 ((equal subtree '(4))
16731 (org-back-to-heading)
16732 (setq beg (point) end (org-end-of-subtree t)
16733 msg "Creating images for subtree...%s"))
16735 (if (setq at (org-inside-LaTeX-fragment-p))
16736 (goto-char (max (point-min) (- (cdr at) 2)))
16737 (org-back-to-heading))
16738 (setq beg (point) end (progn (outline-next-heading) (point))
16739 msg (if at "Creating image...%s"
16740 "Creating images for entry...%s"))))
16741 (message msg "")
16742 (narrow-to-region beg end)
16743 (goto-char beg)
16744 (org-format-latex
16745 (concat "ltxpng/" (file-name-sans-extension
16746 (file-name-nondirectory
16747 buffer-file-name)))
16748 default-directory 'overlays msg at 'forbuffer 'dvipng)
16749 (message msg "done. Use `C-c C-c' to remove images.")))))
16751 (defvar org-latex-regexps
16752 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16753 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16754 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16755 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16756 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16757 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16758 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16759 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16760 "Regular expressions for matching embedded LaTeX.")
16762 (defvar org-export-have-math nil) ;; dynamic scoping
16763 (defun org-format-latex (prefix &optional dir overlays msg at
16764 forbuffer processing-type)
16765 "Replace LaTeX fragments with links to an image, and produce images.
16766 Some of the options can be changed using the variable
16767 `org-format-latex-options'."
16768 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16769 (let* ((prefixnodir (file-name-nondirectory prefix))
16770 (absprefix (expand-file-name prefix dir))
16771 (todir (file-name-directory absprefix))
16772 (opt org-format-latex-options)
16773 (matchers (plist-get opt :matchers))
16774 (re-list org-latex-regexps)
16775 (org-format-latex-header-extra
16776 (plist-get (org-infile-export-plist) :latex-header-extra))
16777 (cnt 0) txt hash link beg end re e checkdir
16778 executables-checked string
16779 m n block-type block linkfile movefile ov)
16780 ;; Check the different regular expressions
16781 (while (setq e (pop re-list))
16782 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16783 block (if block-type "\n\n" ""))
16784 (when (member m matchers)
16785 (goto-char (point-min))
16786 (while (re-search-forward re nil t)
16787 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16788 (not (get-text-property (match-beginning n)
16789 'org-protected))
16790 (or (not overlays)
16791 (not (eq (get-char-property (match-beginning n)
16792 'org-overlay-type)
16793 'org-latex-overlay))))
16794 (setq org-export-have-math t)
16795 (cond
16796 ((eq processing-type 'verbatim)
16797 ;; Leave the text verbatim, just protect it
16798 (add-text-properties (match-beginning n) (match-end n)
16799 '(org-protected t)))
16800 ((eq processing-type 'mathjax)
16801 ;; Prepare for MathJax processing
16802 (setq string (match-string n))
16803 (if (member m '("$" "$1"))
16804 (save-excursion
16805 (delete-region (match-beginning n) (match-end n))
16806 (goto-char (match-beginning n))
16807 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16808 "\\)")
16809 '(org-protected t))))
16810 (add-text-properties (match-beginning n) (match-end n)
16811 '(org-protected t))))
16812 ((eq processing-type 'dvipng)
16813 ;; Process to an image
16814 (setq txt (match-string n)
16815 beg (match-beginning n) end (match-end n)
16816 cnt (1+ cnt))
16817 (let (print-length print-level) ; make sure full list is printed
16818 (setq hash (sha1 (prin1-to-string
16819 (list org-format-latex-header
16820 org-format-latex-header-extra
16821 org-export-latex-default-packages-alist
16822 org-export-latex-packages-alist
16823 org-format-latex-options
16824 forbuffer txt)))
16825 linkfile (format "%s_%s.png" prefix hash)
16826 movefile (format "%s_%s.png" absprefix hash)))
16827 (setq link (concat block "[[file:" linkfile "]]" block))
16828 (if msg (message msg cnt))
16829 (goto-char beg)
16830 (unless checkdir ; make sure the directory exists
16831 (setq checkdir t)
16832 (or (file-directory-p todir) (make-directory todir t)))
16834 (unless executables-checked
16835 (org-check-external-command
16836 "latex" "needed to convert LaTeX fragments to images")
16837 (org-check-external-command
16838 "dvipng" "needed to convert LaTeX fragments to images")
16839 (setq executables-checked t))
16841 (unless (file-exists-p movefile)
16842 (org-create-formula-image
16843 txt movefile opt forbuffer))
16844 (if overlays
16845 (progn
16846 (mapc (lambda (o)
16847 (if (eq (overlay-get o 'org-overlay-type)
16848 'org-latex-overlay)
16849 (delete-overlay o)))
16850 (overlays-in beg end))
16851 (setq ov (make-overlay beg end))
16852 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16853 (if (featurep 'xemacs)
16854 (progn
16855 (overlay-put ov 'invisible t)
16856 (overlay-put
16857 ov 'end-glyph
16858 (make-glyph (vector 'png :file movefile))))
16859 (overlay-put
16860 ov 'display
16861 (list 'image :type 'png :file movefile :ascent 'center)))
16862 (push ov org-latex-fragment-image-overlays)
16863 (goto-char end))
16864 (delete-region beg end)
16865 (insert (org-add-props link
16866 (list 'org-latex-src
16867 (replace-regexp-in-string
16868 "\"" "" txt)
16869 'org-latex-src-embed-type
16870 (if block-type 'paragraph 'character))))))
16871 ((eq processing-type 'mathml)
16872 ;; Process to MathML
16873 (unless executables-checked
16874 (unless (save-match-data (org-format-latex-mathml-available-p))
16875 (error "LaTeX to MathML converter not configured"))
16876 (setq executables-checked t))
16877 (setq txt (match-string n)
16878 beg (match-beginning n) end (match-end n)
16879 cnt (1+ cnt))
16880 (if msg (message msg cnt))
16881 (goto-char beg)
16882 (delete-region beg end)
16883 (insert (org-format-latex-as-mathml
16884 txt block-type prefix dir)))
16886 (error "Unknown conversion type %s for latex fragments"
16887 processing-type)))))))))
16889 (defun org-create-math-formula (latex-frag &optional mathml-file)
16890 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16891 Use `org-latex-to-mathml-convert-command'. If the conversion is
16892 sucessful, return the portion between \"<math...> </math>\"
16893 elements otherwise return nil. When MATHML-FILE is specified,
16894 write the results in to that file. When invoked as an
16895 interactive command, prompt for LATEX-FRAG, with initial value
16896 set to the current active region and echo the results for user
16897 inspection."
16898 (interactive (list (let ((frag (when (region-active-p)
16899 (buffer-substring-no-properties
16900 (region-beginning) (region-end)))))
16901 (read-string "LaTeX Fragment: " frag nil frag))))
16902 (unless latex-frag (error "Invalid latex-frag"))
16903 (let* ((tmp-in-file (file-relative-name
16904 (make-temp-name (expand-file-name "ltxmathml-in"))))
16905 (ignore (write-region latex-frag nil tmp-in-file))
16906 (tmp-out-file (file-relative-name
16907 (make-temp-name (expand-file-name "ltxmathml-out"))))
16908 (cmd (format-spec
16909 org-latex-to-mathml-convert-command
16910 `((?j . ,(shell-quote-argument
16911 (expand-file-name org-latex-to-mathml-jar-file)))
16912 (?I . ,(shell-quote-argument tmp-in-file))
16913 (?o . ,(shell-quote-argument tmp-out-file)))))
16914 mathml shell-command-output)
16915 (when (org-called-interactively-p 'any)
16916 (unless (org-format-latex-mathml-available-p)
16917 (error "LaTeX to MathML converter not configured")))
16918 (message "Running %s" cmd)
16919 (setq shell-command-output (shell-command-to-string cmd))
16920 (setq mathml
16921 (when (file-readable-p tmp-out-file)
16922 (with-current-buffer (find-file-noselect tmp-out-file t)
16923 (goto-char (point-min))
16924 (when (re-search-forward
16925 (concat
16926 (regexp-quote
16927 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16928 "\\(.\\|\n\\)*"
16929 (regexp-quote "</math>")) nil t)
16930 (prog1 (match-string 0) (kill-buffer))))))
16931 (cond
16932 (mathml
16933 (setq mathml
16934 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16935 (when mathml-file
16936 (write-region mathml nil mathml-file))
16937 (when (org-called-interactively-p 'any)
16938 (message mathml)))
16939 ((message "LaTeX to MathML conversion failed")
16940 (message shell-command-output)))
16941 (delete-file tmp-in-file)
16942 (when (file-exists-p tmp-out-file)
16943 (delete-file tmp-out-file))
16944 mathml))
16946 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16947 prefix &optional dir)
16948 "Use `org-create-math-formula' but check local cache first."
16949 (let* ((absprefix (expand-file-name prefix dir))
16950 (print-length nil) (print-level nil)
16951 (formula-id (concat
16952 "formula-"
16953 (sha1
16954 (prin1-to-string
16955 (list latex-frag
16956 org-latex-to-mathml-convert-command)))))
16957 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16958 (formula-cache-dir (file-name-directory formula-cache)))
16960 (unless (file-directory-p formula-cache-dir)
16961 (make-directory formula-cache-dir t))
16963 (unless (file-exists-p formula-cache)
16964 (org-create-math-formula latex-frag formula-cache))
16966 (if (file-exists-p formula-cache)
16967 ;; Successful conversion. Return the link to MathML file.
16968 (org-add-props
16969 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16970 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16971 'org-latex-src-embed-type (if latex-frag-type
16972 'paragraph 'character)))
16973 ;; Failed conversion. Return the LaTeX fragment verbatim
16974 (add-text-properties
16975 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16976 latex-frag)))
16978 ;; This function borrows from Ganesh Swami's latex2png.el
16979 (defun org-create-formula-image (string tofile options buffer)
16980 "This calls dvipng."
16981 (require 'org-latex)
16982 (let* ((tmpdir (if (featurep 'xemacs)
16983 (temp-directory)
16984 temporary-file-directory))
16985 (texfilebase (make-temp-name
16986 (expand-file-name "orgtex" tmpdir)))
16987 (texfile (concat texfilebase ".tex"))
16988 (dvifile (concat texfilebase ".dvi"))
16989 (pngfile (concat texfilebase ".png"))
16990 (fnh (if (featurep 'xemacs)
16991 (font-height (face-font 'default))
16992 (face-attribute 'default :height nil)))
16993 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16994 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16995 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16996 "Black"))
16997 (bg (or (plist-get options (if buffer :background :html-background))
16998 "Transparent")))
16999 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17000 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17001 (with-temp-file texfile
17002 (insert (org-splice-latex-header
17003 org-format-latex-header
17004 org-export-latex-default-packages-alist
17005 org-export-latex-packages-alist t
17006 org-format-latex-header-extra))
17007 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17008 (require 'org-latex)
17009 (org-export-latex-fix-inputenc))
17010 (let ((dir default-directory))
17011 (condition-case nil
17012 (progn
17013 (cd tmpdir)
17014 (call-process "latex" nil nil nil texfile))
17015 (error nil))
17016 (cd dir))
17017 (if (not (file-exists-p dvifile))
17018 (progn (message "Failed to create dvi file from %s" texfile) nil)
17019 (condition-case nil
17020 (if (featurep 'xemacs)
17021 (call-process "dvipng" nil nil nil
17022 "-fg" fg "-bg" bg
17023 "-T" "tight"
17024 "-o" pngfile
17025 dvifile)
17026 (call-process "dvipng" nil nil nil
17027 "-fg" fg "-bg" bg
17028 "-D" dpi
17029 ;;"-x" scale "-y" scale
17030 "-T" "tight"
17031 "-o" pngfile
17032 dvifile))
17033 (error nil))
17034 (if (not (file-exists-p pngfile))
17035 (if org-format-latex-signal-error
17036 (error "Failed to create png file from %s" texfile)
17037 (message "Failed to create png file from %s" texfile)
17038 nil)
17039 ;; Use the requested file name and clean up
17040 (copy-file pngfile tofile 'replace)
17041 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17042 (delete-file (concat texfilebase e)))
17043 pngfile))))
17045 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17046 "Fill a LaTeX header template TPL.
17047 In the template, the following place holders will be recognized:
17049 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17050 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17051 [PACKAGES] \\usepackage statements for PKG
17052 [NO-PACKAGES] do not include PKG
17053 [EXTRA] the string EXTRA
17054 [NO-EXTRA] do not include EXTRA
17056 For backward compatibility, if both the positive and the negative place
17057 holder is missing, the positive one (without the \"NO-\") will be
17058 assumed to be present at the end of the template.
17059 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17060 EXTRA is a string.
17061 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17062 (let (rpl (end ""))
17063 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17064 (setq rpl (if (or (match-end 1) (not def-pkg))
17065 "" (org-latex-packages-to-string def-pkg snippets-p t))
17066 tpl (replace-match rpl t t tpl))
17067 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17069 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17070 (setq rpl (if (or (match-end 1) (not pkg))
17071 "" (org-latex-packages-to-string pkg snippets-p t))
17072 tpl (replace-match rpl t t tpl))
17073 (if pkg (setq end
17074 (concat end "\n"
17075 (org-latex-packages-to-string pkg snippets-p)))))
17077 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17078 (setq rpl (if (or (match-end 1) (not extra))
17079 "" (concat extra "\n"))
17080 tpl (replace-match rpl t t tpl))
17081 (if (and extra (string-match "\\S-" extra))
17082 (setq end (concat end "\n" extra))))
17084 (if (string-match "\\S-" end)
17085 (concat tpl "\n" end)
17086 tpl)))
17088 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17089 "Turn an alist of packages into a string with the \\usepackage macros."
17090 (setq pkg (mapconcat (lambda(p)
17091 (cond
17092 ((stringp p) p)
17093 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17094 (format "%% Package %s omitted" (cadr p)))
17095 ((equal "" (car p))
17096 (format "\\usepackage{%s}" (cadr p)))
17098 (format "\\usepackage[%s]{%s}"
17099 (car p) (cadr p)))))
17101 "\n"))
17102 (if newline (concat pkg "\n") pkg))
17104 (defun org-dvipng-color (attr)
17105 "Return an rgb color specification for dvipng."
17106 (apply 'format "rgb %s %s %s"
17107 (mapcar 'org-normalize-color
17108 (if (featurep 'xemacs)
17109 (color-rgb-components
17110 (face-property 'default
17111 (cond ((eq attr :foreground) 'foreground)
17112 ((eq attr :background) 'background))))
17113 (color-values (face-attribute 'default attr nil))))))
17115 (defun org-normalize-color (value)
17116 "Return string to be used as color value for an RGB component."
17117 (format "%g" (/ value 65535.0)))
17119 ;; Image display
17122 (defvar org-inline-image-overlays nil)
17123 (make-variable-buffer-local 'org-inline-image-overlays)
17125 (defun org-toggle-inline-images (&optional include-linked)
17126 "Toggle the display of inline images.
17127 INCLUDE-LINKED is passed to `org-display-inline-images'."
17128 (interactive "P")
17129 (if org-inline-image-overlays
17130 (progn
17131 (org-remove-inline-images)
17132 (message "Inline image display turned off"))
17133 (org-display-inline-images include-linked)
17134 (if org-inline-image-overlays
17135 (message "%d images displayed inline"
17136 (length org-inline-image-overlays))
17137 (message "No images to display inline"))))
17139 (defun org-display-inline-images (&optional include-linked refresh beg end)
17140 "Display inline images.
17141 Normally only links without a description part are inlined, because this
17142 is how it will work for export. When INCLUDE-LINKED is set, also links
17143 with a description part will be inlined. This can be nice for a quick
17144 look at those images, but it does not reflect what exported files will look
17145 like.
17146 When REFRESH is set, refresh existing images between BEG and END.
17147 This will create new image displays only if necessary.
17148 BEG and END default to the buffer boundaries."
17149 (interactive "P")
17150 (unless refresh
17151 (org-remove-inline-images)
17152 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17153 (save-excursion
17154 (save-restriction
17155 (widen)
17156 (setq beg (or beg (point-min)) end (or end (point-max)))
17157 (goto-char (point-min))
17158 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17159 (substring (org-image-file-name-regexp) 0 -2)
17160 "\\)\\]" (if include-linked "" "\\]")))
17161 old file ov img)
17162 (while (re-search-forward re end t)
17163 (setq old (get-char-property-and-overlay (match-beginning 1)
17164 'org-image-overlay))
17165 (setq file (expand-file-name
17166 (concat (or (match-string 3) "") (match-string 4))))
17167 (when (file-exists-p file)
17168 (if (and (car-safe old) refresh)
17169 (image-refresh (overlay-get (cdr old) 'display))
17170 (setq img (save-match-data (create-image file)))
17171 (when img
17172 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17173 (overlay-put ov 'display img)
17174 (overlay-put ov 'face 'default)
17175 (overlay-put ov 'org-image-overlay t)
17176 (overlay-put ov 'modification-hooks
17177 (list 'org-display-inline-modification-hook))
17178 (push ov org-inline-image-overlays)))))))))
17180 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17181 "Remove inline-display overlay if a corresponding region is modified."
17182 (let ((inhibit-modification-hooks t))
17183 (when (and ov after)
17184 (delete ov org-inline-image-overlays)
17185 (delete-overlay ov))))
17187 (defun org-remove-inline-images ()
17188 "Remove inline display of images."
17189 (interactive)
17190 (mapc 'delete-overlay org-inline-image-overlays)
17191 (setq org-inline-image-overlays nil))
17193 ;;;; Key bindings
17195 ;; Outline functions from `outline-mode-prefix-map'
17196 ;; that can be remapped in Org:
17197 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17198 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17199 (define-key org-mode-map [remap outline-forward-same-level]
17200 'org-forward-same-level)
17201 (define-key org-mode-map [remap outline-backward-same-level]
17202 'org-backward-same-level)
17203 (define-key org-mode-map [remap show-branches]
17204 'org-kill-note-or-show-branches)
17205 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17206 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17207 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17209 ;; Outline functions from `outline-mode-prefix-map'
17210 ;; that can not be remapped in Org:
17211 ;; - the column "key binding" shows whether the Outline function is still
17212 ;; available in Org mode on the same key that it has been bound to in
17213 ;; Outline mode:
17214 ;; - "overridden": key used for a different functionality in Org mode
17215 ;; - else: key still bound to the same Outline function in Org mode
17216 ;; | Outline function | key binding | Org replacement |
17217 ;; |------------------------------------+-------------+-----------------------|
17218 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17219 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17220 ;; | `show-children' | `C-c C-i' | visibility cycling |
17221 ;; | `hide-subtree' | overridden | visibility cycling |
17222 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17223 ;; | `hide-body' | overridden | no replacement |
17224 ;; | `show-all' | overridden | no replacement |
17225 ;; | `hide-entry' | overridden | visibility cycling |
17226 ;; | `show-entry' | overridden | no replacement |
17227 ;; | `hide-leaves' | overridden | no replacement |
17228 ;; | `hide-sublevels' | overridden | no replacement |
17229 ;; | `hide-other' | overridden | no replacement |
17230 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17231 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17233 ;; Make `C-c C-x' a prefix key
17234 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17236 ;; TAB key with modifiers
17237 (org-defkey org-mode-map "\C-i" 'org-cycle)
17238 (org-defkey org-mode-map [(tab)] 'org-cycle)
17239 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17240 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17241 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17242 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17243 ;; The following line is necessary under Suse GNU/Linux
17244 (unless (featurep 'xemacs)
17245 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17246 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17247 (define-key org-mode-map [backtab] 'org-shifttab)
17249 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17250 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17251 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17253 ;; Cursor keys with modifiers
17254 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17255 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17256 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17257 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17259 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17260 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17261 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17262 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17264 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17265 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17266 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17267 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17269 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17270 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17271 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17272 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17274 ;; Babel keys
17275 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17276 (mapc (lambda (pair)
17277 (define-key org-babel-map (car pair) (cdr pair)))
17278 org-babel-key-bindings)
17280 ;;; Extra keys for tty access.
17281 ;; We only set them when really needed because otherwise the
17282 ;; menus don't show the simple keys
17284 (when (or org-use-extra-keys
17285 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17286 (not window-system))
17287 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17288 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17289 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17290 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17291 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17292 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17293 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17294 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17295 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17296 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17297 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17298 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17299 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17300 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17301 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17302 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17303 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17304 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17305 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17306 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17307 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17308 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17309 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17310 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17311 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17312 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17313 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17314 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17316 ;; All the other keys
17318 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17319 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17320 (if (boundp 'narrow-map)
17321 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17322 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17323 (if (boundp 'narrow-map)
17324 (org-defkey narrow-map "b" 'org-narrow-to-block)
17325 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17326 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17327 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17328 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17329 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17330 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17331 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17332 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17333 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17334 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17335 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17336 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17337 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17338 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17339 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17340 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17341 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17342 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17343 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17344 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17345 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17346 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17347 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17348 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17349 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17350 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17351 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17352 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17353 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17354 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17355 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17356 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17357 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17358 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17359 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17360 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17361 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17362 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17363 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17364 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17365 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17366 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17367 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17368 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17369 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17370 (org-defkey org-mode-map "\C-c^" 'org-sort)
17371 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17372 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17373 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17374 (org-defkey org-mode-map "\C-m" 'org-return)
17375 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17376 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17377 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17378 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17379 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17380 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17381 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17382 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17383 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17384 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17385 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17386 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17387 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17388 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17389 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17390 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17391 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17392 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17393 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17394 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17395 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17396 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17398 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17399 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17400 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17401 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17403 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17404 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17405 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17406 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17407 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17408 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17409 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17410 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17411 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17412 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17413 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17414 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17415 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17416 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17417 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17418 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17419 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17420 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17422 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17423 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17424 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17425 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17426 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17428 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17430 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17432 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17433 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17435 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17438 (when (featurep 'xemacs)
17439 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17442 (defconst org-speed-commands-default
17444 ("Outline Navigation")
17445 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17446 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17447 ("f" . (org-speed-move-safe 'org-forward-same-level))
17448 ("b" . (org-speed-move-safe 'org-backward-same-level))
17449 ("u" . (org-speed-move-safe 'outline-up-heading))
17450 ("j" . org-goto)
17451 ("g" . (org-refile t))
17452 ("Outline Visibility")
17453 ("c" . org-cycle)
17454 ("C" . org-shifttab)
17455 (" " . org-display-outline-path)
17456 ("Outline Structure Editing")
17457 ("U" . org-shiftmetaup)
17458 ("D" . org-shiftmetadown)
17459 ("r" . org-metaright)
17460 ("l" . org-metaleft)
17461 ("R" . org-shiftmetaright)
17462 ("L" . org-shiftmetaleft)
17463 ("i" . (progn (forward-char 1) (call-interactively
17464 'org-insert-heading-respect-content)))
17465 ("^" . org-sort)
17466 ("w" . org-refile)
17467 ("a" . org-archive-subtree-default-with-confirmation)
17468 ("." . org-mark-subtree)
17469 ("Clock Commands")
17470 ("I" . org-clock-in)
17471 ("O" . org-clock-out)
17472 ("Meta Data Editing")
17473 ("t" . org-todo)
17474 ("0" . (org-priority ?\ ))
17475 ("1" . (org-priority ?A))
17476 ("2" . (org-priority ?B))
17477 ("3" . (org-priority ?C))
17478 (";" . org-set-tags-command)
17479 ("e" . org-set-effort)
17480 ("Agenda Views etc")
17481 ("v" . org-agenda)
17482 ("/" . org-sparse-tree)
17483 ("Misc")
17484 ("o" . org-open-at-point)
17485 ("?" . org-speed-command-help)
17486 ("<" . (org-agenda-set-restriction-lock 'subtree))
17487 (">" . (org-agenda-remove-restriction-lock))
17489 "The default speed commands.")
17491 (defun org-print-speed-command (e)
17492 (if (> (length (car e)) 1)
17493 (progn
17494 (princ "\n")
17495 (princ (car e))
17496 (princ "\n")
17497 (princ (make-string (length (car e)) ?-))
17498 (princ "\n"))
17499 (princ (car e))
17500 (princ " ")
17501 (if (symbolp (cdr e))
17502 (princ (symbol-name (cdr e)))
17503 (prin1 (cdr e)))
17504 (princ "\n")))
17506 (defun org-speed-command-help ()
17507 "Show the available speed commands."
17508 (interactive)
17509 (if (not org-use-speed-commands)
17510 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17511 (with-output-to-temp-buffer "*Help*"
17512 (princ "User-defined Speed commands\n===========================\n")
17513 (mapc 'org-print-speed-command org-speed-commands-user)
17514 (princ "\n")
17515 (princ "Built-in Speed commands\n=======================\n")
17516 (mapc 'org-print-speed-command org-speed-commands-default))
17517 (with-current-buffer "*Help*"
17518 (setq truncate-lines t))))
17520 (defun org-speed-move-safe (cmd)
17521 "Execute CMD, but make sure that the cursor always ends up in a headline.
17522 If not, return to the original position and throw an error."
17523 (interactive)
17524 (let ((pos (point)))
17525 (call-interactively cmd)
17526 (unless (and (bolp) (org-at-heading-p))
17527 (goto-char pos)
17528 (error "Boundary reached while executing %s" cmd))))
17530 (defvar org-self-insert-command-undo-counter 0)
17532 (defvar org-table-auto-blank-field) ; defined in org-table.el
17533 (defvar org-speed-command nil)
17535 (defun org-speed-command-default-hook (keys)
17536 "Hook for activating single-letter speed commands.
17537 `org-speed-commands-default' specifies a minimal command set.
17538 Use `org-speed-commands-user' for further customization."
17539 (when (or (and (bolp) (looking-at org-outline-regexp))
17540 (and (functionp org-use-speed-commands)
17541 (funcall org-use-speed-commands)))
17542 (cdr (assoc keys (append org-speed-commands-user
17543 org-speed-commands-default)))))
17545 (defun org-babel-speed-command-hook (keys)
17546 "Hook for activating single-letter code block commands."
17547 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17548 (cdr (assoc keys org-babel-key-bindings))))
17550 (defcustom org-speed-command-hook
17551 '(org-speed-command-default-hook org-babel-speed-command-hook)
17552 "Hook for activating speed commands at strategic locations.
17553 Hook functions are called in sequence until a valid handler is
17554 found.
17556 Each hook takes a single argument, a user-pressed command key
17557 which is also a `self-insert-command' from the global map.
17559 Within the hook, examine the cursor position and the command key
17560 and return nil or a valid handler as appropriate. Handler could
17561 be one of an interactive command, a function, or a form.
17563 Set `org-use-speed-commands' to non-nil value to enable this
17564 hook. The default setting is `org-speed-command-default-hook'."
17565 :group 'org-structure
17566 :type 'hook)
17568 (defun org-self-insert-command (N)
17569 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17570 If the cursor is in a table looking at whitespace, the whitespace is
17571 overwritten, and the table is not marked as requiring realignment."
17572 (interactive "p")
17573 (org-check-before-invisible-edit 'insert)
17574 (cond
17575 ((and org-use-speed-commands
17576 (setq org-speed-command
17577 (run-hook-with-args-until-success
17578 'org-speed-command-hook (this-command-keys))))
17579 (cond
17580 ((commandp org-speed-command)
17581 (setq this-command org-speed-command)
17582 (call-interactively org-speed-command))
17583 ((functionp org-speed-command)
17584 (funcall org-speed-command))
17585 ((and org-speed-command (listp org-speed-command))
17586 (eval org-speed-command))
17587 (t (let (org-use-speed-commands)
17588 (call-interactively 'org-self-insert-command)))))
17589 ((and
17590 (org-table-p)
17591 (progn
17592 ;; check if we blank the field, and if that triggers align
17593 (and (featurep 'org-table) org-table-auto-blank-field
17594 (member last-command
17595 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17596 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17597 ;; got extra space, this field does not determine column width
17598 (let (org-table-may-need-update) (org-table-blank-field))
17599 ;; no extra space, this field may determine column width
17600 (org-table-blank-field)))
17602 (eq N 1)
17603 (looking-at "[^|\n]* |"))
17604 (let (org-table-may-need-update)
17605 (goto-char (1- (match-end 0)))
17606 (delete-char -1)
17607 (goto-char (match-beginning 0))
17608 (self-insert-command N)))
17610 (setq org-table-may-need-update t)
17611 (self-insert-command N)
17612 (org-fix-tags-on-the-fly)
17613 (if org-self-insert-cluster-for-undo
17614 (if (not (eq last-command 'org-self-insert-command))
17615 (setq org-self-insert-command-undo-counter 1)
17616 (if (>= org-self-insert-command-undo-counter 20)
17617 (setq org-self-insert-command-undo-counter 1)
17618 (and (> org-self-insert-command-undo-counter 0)
17619 buffer-undo-list (listp buffer-undo-list)
17620 (not (cadr buffer-undo-list)) ; remove nil entry
17621 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17622 (setq org-self-insert-command-undo-counter
17623 (1+ org-self-insert-command-undo-counter))))))))
17625 (defun org-check-before-invisible-edit (kind)
17626 "Check is editing if kind KIND would be dangerous with invisible text around.
17627 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17628 ;; First, try to get out of here as quickly as possible, to reduce overhead
17629 (if (and org-catch-invisible-edits
17630 (or (not (boundp 'visible-mode)) (not visible-mode))
17631 (or (get-char-property (point) 'invisible)
17632 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17633 ;; OK, we need to take a closer look
17634 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17635 (invisible-before-point (if (bobp) nil (get-char-property
17636 (1- (point)) 'invisible)))
17637 (border-and-ok-direction
17639 ;; Check if we are acting predictably before invisible text
17640 (and invisible-at-point (not invisible-before-point)
17641 (memq kind '(insert delete-backward)))
17642 ;; Check if we are acting predictably after invisible text
17643 ;; This works not well, and I have turned it off. It seems
17644 ;; better to always show and stop after invisible text.
17645 ;; (and (not invisible-at-point) invisible-before-point
17646 ;; (memq kind '(insert delete)))
17649 (when (or (memq invisible-at-point '(outline org-hide-block))
17650 (memq invisible-before-point '(outline org-hide-block)))
17651 (if (eq org-catch-invisible-edits 'error)
17652 (error "Editing in invisible areas is prohibited - make visible first"))
17653 ;; Make the area visible
17654 (save-excursion
17655 (if invisible-before-point
17656 (goto-char (previous-single-char-property-change
17657 (point) 'invisible)))
17658 (org-cycle))
17659 (cond
17660 ((eq org-catch-invisible-edits 'show)
17661 ;; That's it, we do the edit after showing
17662 (message
17663 "Unfolding invisible region around point before editing")
17664 (sit-for 1))
17665 ((and (eq org-catch-invisible-edits 'smart)
17666 border-and-ok-direction)
17667 (message "Unfolding invisible region around point before editing"))
17669 ;; Don't do the edit, make the user repeat it in full visibility
17670 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17672 (defun org-fix-tags-on-the-fly ()
17673 (when (and (equal (char-after (point-at-bol)) ?*)
17674 (org-at-heading-p))
17675 (org-align-tags-here org-tags-column)))
17677 (defun org-delete-backward-char (N)
17678 "Like `delete-backward-char', insert whitespace at field end in tables.
17679 When deleting backwards, in tables this function will insert whitespace in
17680 front of the next \"|\" separator, to keep the table aligned. The table will
17681 still be marked for re-alignment if the field did fill the entire column,
17682 because, in this case the deletion might narrow the column."
17683 (interactive "p")
17684 (org-check-before-invisible-edit 'delete-backward)
17685 (if (and (org-table-p)
17686 (eq N 1)
17687 (string-match "|" (buffer-substring (point-at-bol) (point)))
17688 (looking-at ".*?|"))
17689 (let ((pos (point))
17690 (noalign (looking-at "[^|\n\r]* |"))
17691 (c org-table-may-need-update))
17692 (backward-delete-char N)
17693 (if (not overwrite-mode)
17694 (progn
17695 (skip-chars-forward "^|")
17696 (insert " ")
17697 (goto-char (1- pos))))
17698 ;; noalign: if there were two spaces at the end, this field
17699 ;; does not determine the width of the column.
17700 (if noalign (setq org-table-may-need-update c)))
17701 (backward-delete-char N)
17702 (org-fix-tags-on-the-fly)))
17704 (defun org-delete-char (N)
17705 "Like `delete-char', but insert whitespace at field end in tables.
17706 When deleting characters, in tables this function will insert whitespace in
17707 front of the next \"|\" separator, to keep the table aligned. The table will
17708 still be marked for re-alignment if the field did fill the entire column,
17709 because, in this case the deletion might narrow the column."
17710 (interactive "p")
17711 (org-check-before-invisible-edit 'delete)
17712 (if (and (org-table-p)
17713 (not (bolp))
17714 (not (= (char-after) ?|))
17715 (eq N 1))
17716 (if (looking-at ".*?|")
17717 (let ((pos (point))
17718 (noalign (looking-at "[^|\n\r]* |"))
17719 (c org-table-may-need-update))
17720 (replace-match (concat
17721 (substring (match-string 0) 1 -1)
17722 " |"))
17723 (goto-char pos)
17724 ;; noalign: if there were two spaces at the end, this field
17725 ;; does not determine the width of the column.
17726 (if noalign (setq org-table-may-need-update c)))
17727 (delete-char N))
17728 (delete-char N)
17729 (org-fix-tags-on-the-fly)))
17731 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17732 (put 'org-self-insert-command 'delete-selection t)
17733 (put 'orgtbl-self-insert-command 'delete-selection t)
17734 (put 'org-delete-char 'delete-selection 'supersede)
17735 (put 'org-delete-backward-char 'delete-selection 'supersede)
17736 (put 'org-yank 'delete-selection 'yank)
17738 ;; Make `flyspell-mode' delay after some commands
17739 (put 'org-self-insert-command 'flyspell-delayed t)
17740 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17741 (put 'org-delete-char 'flyspell-delayed t)
17742 (put 'org-delete-backward-char 'flyspell-delayed t)
17744 ;; Make pabbrev-mode expand after org-mode commands
17745 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17746 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17748 ;; How to do this: Measure non-white length of current string
17749 ;; If equal to column width, we should realign.
17751 (defun org-remap (map &rest commands)
17752 "In MAP, remap the functions given in COMMANDS.
17753 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17754 (let (new old)
17755 (while commands
17756 (setq old (pop commands) new (pop commands))
17757 (if (fboundp 'command-remapping)
17758 (org-defkey map (vector 'remap old) new)
17759 (substitute-key-definition old new map global-map)))))
17761 (when (eq org-enable-table-editor 'optimized)
17762 ;; If the user wants maximum table support, we need to hijack
17763 ;; some standard editing functions
17764 (org-remap org-mode-map
17765 'self-insert-command 'org-self-insert-command
17766 'delete-char 'org-delete-char
17767 'delete-backward-char 'org-delete-backward-char)
17768 (org-defkey org-mode-map "|" 'org-force-self-insert))
17770 (defvar org-ctrl-c-ctrl-c-hook nil
17771 "Hook for functions attaching themselves to `C-c C-c'.
17773 This can be used to add additional functionality to the C-c C-c
17774 key which executes context-dependent commands. This hook is run
17775 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17776 run after the last test.
17778 Each function will be called with no arguments. The function
17779 must check if the context is appropriate for it to act. If yes,
17780 it should do its thing and then return a non-nil value. If the
17781 context is wrong, just do nothing and return nil.")
17783 (defvar org-ctrl-c-ctrl-c-final-hook nil
17784 "Hook for functions attaching themselves to `C-c C-c'.
17786 This can be used to add additional functionality to the C-c C-c
17787 key which executes context-dependent commands. This hook is run
17788 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17789 before the first test.
17791 Each function will be called with no arguments. The function
17792 must check if the context is appropriate for it to act. If yes,
17793 it should do its thing and then return a non-nil value. If the
17794 context is wrong, just do nothing and return nil.")
17796 (defvar org-tab-first-hook nil
17797 "Hook for functions to attach themselves to TAB.
17798 See `org-ctrl-c-ctrl-c-hook' for more information.
17799 This hook runs as the first action when TAB is pressed, even before
17800 `org-cycle' messes around with the `outline-regexp' to cater for
17801 inline tasks and plain list item folding.
17802 If any function in this hook returns t, any other actions that
17803 would have been caused by TAB (such as table field motion or visibility
17804 cycling) will not occur.")
17806 (defvar org-tab-after-check-for-table-hook nil
17807 "Hook for functions to attach themselves to TAB.
17808 See `org-ctrl-c-ctrl-c-hook' for more information.
17809 This hook runs after it has been established that the cursor is not in a
17810 table, but before checking if the cursor is in a headline or if global cycling
17811 should be done.
17812 If any function in this hook returns t, not other actions like visibility
17813 cycling will be done.")
17815 (defvar org-tab-after-check-for-cycling-hook nil
17816 "Hook for functions to attach themselves to TAB.
17817 See `org-ctrl-c-ctrl-c-hook' for more information.
17818 This hook runs after it has been established that not table field motion and
17819 not visibility should be done because of current context. This is probably
17820 the place where a package like yasnippets can hook in.")
17822 (defvar org-tab-before-tab-emulation-hook nil
17823 "Hook for functions to attach themselves to TAB.
17824 See `org-ctrl-c-ctrl-c-hook' for more information.
17825 This hook runs after every other options for TAB have been exhausted, but
17826 before indentation and \t insertion takes place.")
17828 (defvar org-metaleft-hook nil
17829 "Hook for functions attaching themselves to `M-left'.
17830 See `org-ctrl-c-ctrl-c-hook' for more information.")
17831 (defvar org-metaright-hook nil
17832 "Hook for functions attaching themselves to `M-right'.
17833 See `org-ctrl-c-ctrl-c-hook' for more information.")
17834 (defvar org-metaup-hook nil
17835 "Hook for functions attaching themselves to `M-up'.
17836 See `org-ctrl-c-ctrl-c-hook' for more information.")
17837 (defvar org-metadown-hook nil
17838 "Hook for functions attaching themselves to `M-down'.
17839 See `org-ctrl-c-ctrl-c-hook' for more information.")
17840 (defvar org-shiftmetaleft-hook nil
17841 "Hook for functions attaching themselves to `M-S-left'.
17842 See `org-ctrl-c-ctrl-c-hook' for more information.")
17843 (defvar org-shiftmetaright-hook nil
17844 "Hook for functions attaching themselves to `M-S-right'.
17845 See `org-ctrl-c-ctrl-c-hook' for more information.")
17846 (defvar org-shiftmetaup-hook nil
17847 "Hook for functions attaching themselves to `M-S-up'.
17848 See `org-ctrl-c-ctrl-c-hook' for more information.")
17849 (defvar org-shiftmetadown-hook nil
17850 "Hook for functions attaching themselves to `M-S-down'.
17851 See `org-ctrl-c-ctrl-c-hook' for more information.")
17852 (defvar org-metareturn-hook nil
17853 "Hook for functions attaching themselves to `M-RET'.
17854 See `org-ctrl-c-ctrl-c-hook' for more information.")
17855 (defvar org-shiftup-hook nil
17856 "Hook for functions attaching themselves to `S-up'.
17857 See `org-ctrl-c-ctrl-c-hook' for more information.")
17858 (defvar org-shiftup-final-hook nil
17859 "Hook for functions attaching themselves to `S-up'.
17860 This one runs after all other options except shift-select have been excluded.
17861 See `org-ctrl-c-ctrl-c-hook' for more information.")
17862 (defvar org-shiftdown-hook nil
17863 "Hook for functions attaching themselves to `S-down'.
17864 See `org-ctrl-c-ctrl-c-hook' for more information.")
17865 (defvar org-shiftdown-final-hook nil
17866 "Hook for functions attaching themselves to `S-down'.
17867 This one runs after all other options except shift-select have been excluded.
17868 See `org-ctrl-c-ctrl-c-hook' for more information.")
17869 (defvar org-shiftleft-hook nil
17870 "Hook for functions attaching themselves to `S-left'.
17871 See `org-ctrl-c-ctrl-c-hook' for more information.")
17872 (defvar org-shiftleft-final-hook nil
17873 "Hook for functions attaching themselves to `S-left'.
17874 This one runs after all other options except shift-select have been excluded.
17875 See `org-ctrl-c-ctrl-c-hook' for more information.")
17876 (defvar org-shiftright-hook nil
17877 "Hook for functions attaching themselves to `S-right'.
17878 See `org-ctrl-c-ctrl-c-hook' for more information.")
17879 (defvar org-shiftright-final-hook nil
17880 "Hook for functions attaching themselves to `S-right'.
17881 This one runs after all other options except shift-select have been excluded.
17882 See `org-ctrl-c-ctrl-c-hook' for more information.")
17884 (defun org-modifier-cursor-error ()
17885 "Throw an error, a modified cursor command was applied in wrong context."
17886 (error "This command is active in special context like tables, headlines or items"))
17888 (defun org-shiftselect-error ()
17889 "Throw an error because Shift-Cursor command was applied in wrong context."
17890 (if (and (boundp 'shift-select-mode) shift-select-mode)
17891 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17892 (error "This command works only in special context like headlines or timestamps")))
17894 (defun org-call-for-shift-select (cmd)
17895 (let ((this-command-keys-shift-translated t))
17896 (call-interactively cmd)))
17898 (defun org-shifttab (&optional arg)
17899 "Global visibility cycling or move to previous table field.
17900 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17901 on context.
17902 See the individual commands for more information."
17903 (interactive "P")
17904 (cond
17905 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17906 ((integerp arg)
17907 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17908 (message "Content view to level: %d" arg)
17909 (org-content (prefix-numeric-value arg2))
17910 (setq org-cycle-global-status 'overview)))
17911 (t (call-interactively 'org-global-cycle))))
17913 (defun org-shiftmetaleft ()
17914 "Promote subtree or delete table column.
17915 Calls `org-promote-subtree', `org-outdent-item',
17916 or `org-table-delete-column', depending on context.
17917 See the individual commands for more information."
17918 (interactive)
17919 (cond
17920 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17921 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17922 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
17923 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17924 (t (org-modifier-cursor-error))))
17926 (defun org-shiftmetaright ()
17927 "Demote subtree or insert table column.
17928 Calls `org-demote-subtree', `org-indent-item',
17929 or `org-table-insert-column', depending on context.
17930 See the individual commands for more information."
17931 (interactive)
17932 (cond
17933 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17934 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17935 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
17936 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17937 (t (org-modifier-cursor-error))))
17939 (defun org-shiftmetaup (&optional arg)
17940 "Move subtree up or kill table row.
17941 Calls `org-move-subtree-up' or `org-table-kill-row' or
17942 `org-move-item-up' depending on context. See the individual commands
17943 for more information."
17944 (interactive "P")
17945 (cond
17946 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17947 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17948 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
17949 ((org-at-item-p) (call-interactively 'org-move-item-up))
17950 (t (org-modifier-cursor-error))))
17952 (defun org-shiftmetadown (&optional arg)
17953 "Move subtree down or insert table row.
17954 Calls `org-move-subtree-down' or `org-table-insert-row' or
17955 `org-move-item-down', depending on context. See the individual
17956 commands for more information."
17957 (interactive "P")
17958 (cond
17959 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17960 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17961 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
17962 ((org-at-item-p) (call-interactively 'org-move-item-down))
17963 (t (org-modifier-cursor-error))))
17965 (defsubst org-hidden-tree-error ()
17966 (error
17967 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17969 (defun org-metaleft (&optional arg)
17970 "Promote heading or move table column to left.
17971 Calls `org-do-promote' or `org-table-move-column', depending on context.
17972 With no specific context, calls the Emacs default `backward-word'.
17973 See the individual commands for more information."
17974 (interactive "P")
17975 (cond
17976 ((run-hook-with-args-until-success 'org-metaleft-hook))
17977 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17978 ((org-with-limited-levels
17979 (or (org-at-heading-p)
17980 (and (org-region-active-p)
17981 (save-excursion
17982 (goto-char (region-beginning))
17983 (org-at-heading-p)))))
17984 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17985 (call-interactively 'org-do-promote))
17986 ;; At an inline task.
17987 ((org-at-heading-p)
17988 (call-interactively 'org-inlinetask-promote))
17989 ((or (org-at-item-p)
17990 (and (org-region-active-p)
17991 (save-excursion
17992 (goto-char (region-beginning))
17993 (org-at-item-p))))
17994 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17995 (call-interactively 'org-outdent-item))
17996 (t (call-interactively 'backward-word))))
17998 (defun org-metaright (&optional arg)
17999 "Demote subtree or move table column to right.
18000 Calls `org-do-demote' or `org-table-move-column', depending on context.
18001 With no specific context, calls the Emacs default `forward-word'.
18002 See the individual commands for more information."
18003 (interactive "P")
18004 (cond
18005 ((run-hook-with-args-until-success 'org-metaright-hook))
18006 ((org-at-table-p) (call-interactively 'org-table-move-column))
18007 ((org-with-limited-levels
18008 (or (org-at-heading-p)
18009 (and (org-region-active-p)
18010 (save-excursion
18011 (goto-char (region-beginning))
18012 (org-at-heading-p)))))
18013 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18014 (call-interactively 'org-do-demote))
18015 ;; At an inline task.
18016 ((org-at-heading-p)
18017 (call-interactively 'org-inlinetask-demote))
18018 ((or (org-at-item-p)
18019 (and (org-region-active-p)
18020 (save-excursion
18021 (goto-char (region-beginning))
18022 (org-at-item-p))))
18023 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18024 (call-interactively 'org-indent-item))
18025 (t (call-interactively 'forward-word))))
18027 (defun org-check-for-hidden (what)
18028 "Check if there are hidden headlines/items in the current visual line.
18029 WHAT can be either `headlines' or `items'. If the current line is
18030 an outline or item heading and it has a folded subtree below it,
18031 this function returns t, nil otherwise."
18032 (let ((re (cond
18033 ((eq what 'headlines) org-outline-regexp-bol)
18034 ((eq what 'items) (org-item-beginning-re))
18035 (t (error "This should not happen"))))
18036 beg end)
18037 (save-excursion
18038 (catch 'exit
18039 (unless (org-region-active-p)
18040 (setq beg (point-at-bol))
18041 (beginning-of-line 2)
18042 (while (and (not (eobp)) ;; this is like `next-line'
18043 (get-char-property (1- (point)) 'invisible))
18044 (beginning-of-line 2))
18045 (setq end (point))
18046 (goto-char beg)
18047 (goto-char (point-at-eol))
18048 (setq end (max end (point)))
18049 (while (re-search-forward re end t)
18050 (if (get-char-property (match-beginning 0) 'invisible)
18051 (throw 'exit t))))
18052 nil))))
18054 (defun org-metaup (&optional arg)
18055 "Move subtree up or move table row up.
18056 Calls `org-move-subtree-up' or `org-table-move-row' or
18057 `org-move-item-up', depending on context. See the individual commands
18058 for more information."
18059 (interactive "P")
18060 (cond
18061 ((run-hook-with-args-until-success 'org-metaup-hook))
18062 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18063 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18064 ((org-at-item-p) (call-interactively 'org-move-item-up))
18065 (t (transpose-lines 1) (beginning-of-line -1))))
18067 (defun org-metadown (&optional arg)
18068 "Move subtree down or move table row down.
18069 Calls `org-move-subtree-down' or `org-table-move-row' or
18070 `org-move-item-down', depending on context. See the individual
18071 commands for more information."
18072 (interactive "P")
18073 (cond
18074 ((run-hook-with-args-until-success 'org-metadown-hook))
18075 ((org-at-table-p) (call-interactively 'org-table-move-row))
18076 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18077 ((org-at-item-p) (call-interactively 'org-move-item-down))
18078 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18080 (defun org-shiftup (&optional arg)
18081 "Increase item in timestamp or increase priority of current headline.
18082 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18083 depending on context. See the individual commands for more information."
18084 (interactive "P")
18085 (cond
18086 ((run-hook-with-args-until-success 'org-shiftup-hook))
18087 ((and org-support-shift-select (org-region-active-p))
18088 (org-call-for-shift-select 'previous-line))
18089 ((org-at-timestamp-p t)
18090 (call-interactively (if org-edit-timestamp-down-means-later
18091 'org-timestamp-down 'org-timestamp-up)))
18092 ((and (not (eq org-support-shift-select 'always))
18093 org-enable-priority-commands
18094 (org-at-heading-p))
18095 (call-interactively 'org-priority-up))
18096 ((and (not org-support-shift-select) (org-at-item-p))
18097 (call-interactively 'org-previous-item))
18098 ((org-clocktable-try-shift 'up arg))
18099 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18100 (org-support-shift-select
18101 (org-call-for-shift-select 'previous-line))
18102 (t (org-shiftselect-error))))
18104 (defun org-shiftdown (&optional arg)
18105 "Decrease item in timestamp or decrease priority of current headline.
18106 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18107 depending on context. See the individual commands for more information."
18108 (interactive "P")
18109 (cond
18110 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18111 ((and org-support-shift-select (org-region-active-p))
18112 (org-call-for-shift-select 'next-line))
18113 ((org-at-timestamp-p t)
18114 (call-interactively (if org-edit-timestamp-down-means-later
18115 'org-timestamp-up 'org-timestamp-down)))
18116 ((and (not (eq org-support-shift-select 'always))
18117 org-enable-priority-commands
18118 (org-at-heading-p))
18119 (call-interactively 'org-priority-down))
18120 ((and (not org-support-shift-select) (org-at-item-p))
18121 (call-interactively 'org-next-item))
18122 ((org-clocktable-try-shift 'down arg))
18123 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18124 (org-support-shift-select
18125 (org-call-for-shift-select 'next-line))
18126 (t (org-shiftselect-error))))
18128 (defun org-shiftright (&optional arg)
18129 "Cycle the thing at point or in the current line, depending on context.
18130 Depending on context, this does one of the following:
18132 - switch a timestamp at point one day into the future
18133 - on a headline, switch to the next TODO keyword.
18134 - on an item, switch entire list to the next bullet type
18135 - on a property line, switch to the next allowed value
18136 - on a clocktable definition line, move time block into the future"
18137 (interactive "P")
18138 (cond
18139 ((run-hook-with-args-until-success 'org-shiftright-hook))
18140 ((and org-support-shift-select (org-region-active-p))
18141 (org-call-for-shift-select 'forward-char))
18142 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18143 ((and (not (eq org-support-shift-select 'always))
18144 (org-at-heading-p))
18145 (let ((org-inhibit-logging
18146 (not org-treat-S-cursor-todo-selection-as-state-change))
18147 (org-inhibit-blocking
18148 (not org-treat-S-cursor-todo-selection-as-state-change)))
18149 (org-call-with-arg 'org-todo 'right)))
18150 ((or (and org-support-shift-select
18151 (not (eq org-support-shift-select 'always))
18152 (org-at-item-bullet-p))
18153 (and (not org-support-shift-select) (org-at-item-p)))
18154 (org-call-with-arg 'org-cycle-list-bullet nil))
18155 ((and (not (eq org-support-shift-select 'always))
18156 (org-at-property-p))
18157 (call-interactively 'org-property-next-allowed-value))
18158 ((org-clocktable-try-shift 'right arg))
18159 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18160 (org-support-shift-select
18161 (org-call-for-shift-select 'forward-char))
18162 (t (org-shiftselect-error))))
18164 (defun org-shiftleft (&optional arg)
18165 "Cycle the thing at point or in the current line, depending on context.
18166 Depending on context, this does one of the following:
18168 - switch a timestamp at point one day into the past
18169 - on a headline, switch to the previous TODO keyword.
18170 - on an item, switch entire list to the previous bullet type
18171 - on a property line, switch to the previous allowed value
18172 - on a clocktable definition line, move time block into the past"
18173 (interactive "P")
18174 (cond
18175 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18176 ((and org-support-shift-select (org-region-active-p))
18177 (org-call-for-shift-select 'backward-char))
18178 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18179 ((and (not (eq org-support-shift-select 'always))
18180 (org-at-heading-p))
18181 (let ((org-inhibit-logging
18182 (not org-treat-S-cursor-todo-selection-as-state-change))
18183 (org-inhibit-blocking
18184 (not org-treat-S-cursor-todo-selection-as-state-change)))
18185 (org-call-with-arg 'org-todo 'left)))
18186 ((or (and org-support-shift-select
18187 (not (eq org-support-shift-select 'always))
18188 (org-at-item-bullet-p))
18189 (and (not org-support-shift-select) (org-at-item-p)))
18190 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18191 ((and (not (eq org-support-shift-select 'always))
18192 (org-at-property-p))
18193 (call-interactively 'org-property-previous-allowed-value))
18194 ((org-clocktable-try-shift 'left arg))
18195 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18196 (org-support-shift-select
18197 (org-call-for-shift-select 'backward-char))
18198 (t (org-shiftselect-error))))
18200 (defun org-shiftcontrolright ()
18201 "Switch to next TODO set."
18202 (interactive)
18203 (cond
18204 ((and org-support-shift-select (org-region-active-p))
18205 (org-call-for-shift-select 'forward-word))
18206 ((and (not (eq org-support-shift-select 'always))
18207 (org-at-heading-p))
18208 (org-call-with-arg 'org-todo 'nextset))
18209 (org-support-shift-select
18210 (org-call-for-shift-select 'forward-word))
18211 (t (org-shiftselect-error))))
18213 (defun org-shiftcontrolleft ()
18214 "Switch to previous TODO set."
18215 (interactive)
18216 (cond
18217 ((and org-support-shift-select (org-region-active-p))
18218 (org-call-for-shift-select 'backward-word))
18219 ((and (not (eq org-support-shift-select 'always))
18220 (org-at-heading-p))
18221 (org-call-with-arg 'org-todo 'previousset))
18222 (org-support-shift-select
18223 (org-call-for-shift-select 'backward-word))
18224 (t (org-shiftselect-error))))
18226 (defun org-shiftcontrolup ()
18227 "Change timestamps synchronously up in CLOCK log lines."
18228 (interactive)
18229 (cond ((and (not org-support-shift-select)
18230 (org-at-clock-log-p)
18231 (org-at-timestamp-p t))
18232 (org-clock-timestamps-up))
18233 (t (org-shiftselect-error))))
18235 (defun org-shiftcontroldown ()
18236 "Change timestamps synchronously down in CLOCK log lines."
18237 (interactive)
18238 (cond ((and (not org-support-shift-select)
18239 (org-at-clock-log-p)
18240 (org-at-timestamp-p t))
18241 (org-clock-timestamps-down))
18242 (t (org-shiftselect-error))))
18244 (defun org-ctrl-c-ret ()
18245 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18246 (interactive)
18247 (cond
18248 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18249 (t (call-interactively 'org-insert-heading))))
18251 (defun org-find-visible ()
18252 (let ((s (point)))
18253 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18254 (get-char-property s 'invisible)))
18256 (defun org-find-invisible ()
18257 (let ((s (point)))
18258 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18259 (not (get-char-property s 'invisible))))
18262 (defun org-copy-visible (beg end)
18263 "Copy the visible parts of the region."
18264 (interactive "r")
18265 (let (snippets s)
18266 (save-excursion
18267 (save-restriction
18268 (narrow-to-region beg end)
18269 (setq s (goto-char (point-min)))
18270 (while (not (= (point) (point-max)))
18271 (goto-char (org-find-invisible))
18272 (push (buffer-substring s (point)) snippets)
18273 (setq s (goto-char (org-find-visible))))))
18274 (kill-new (apply 'concat (nreverse snippets)))))
18276 (defun org-copy-special ()
18277 "Copy region in table or copy current subtree.
18278 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18279 See the individual commands for more information."
18280 (interactive)
18281 (call-interactively
18282 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18284 (defun org-cut-special ()
18285 "Cut region in table or cut current subtree.
18286 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18287 See the individual commands for more information."
18288 (interactive)
18289 (call-interactively
18290 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18292 (defun org-paste-special (arg)
18293 "Paste rectangular region into table, or past subtree relative to level.
18294 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18295 See the individual commands for more information."
18296 (interactive "P")
18297 (if (org-at-table-p)
18298 (org-table-paste-rectangle)
18299 (org-paste-subtree arg)))
18301 (defun org-edit-special (&optional arg)
18302 "Call a special editor for the stuff at point.
18303 When at a table, call the formula editor with `org-table-edit-formulas'.
18304 When at the first line of an src example, call `org-edit-src-code'.
18305 When in an #+include line, visit the include file. Otherwise call
18306 `ffap' to visit the file at point."
18307 (interactive)
18308 ;; possibly prep session before editing source
18309 (when arg
18310 (let* ((info (org-babel-get-src-block-info))
18311 (lang (nth 0 info))
18312 (params (nth 2 info))
18313 (session (cdr (assoc :session params))))
18314 (when (and info session) ;; we are in a source-code block with a session
18315 (funcall
18316 (intern (concat "org-babel-prep-session:" lang)) session params))))
18317 (cond ;; proceed with `org-edit-special'
18318 ((save-excursion
18319 (beginning-of-line 1)
18320 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18321 (find-file (org-trim (match-string 1))))
18322 ((org-edit-src-code))
18323 ((org-edit-fixed-width-region))
18324 ((org-at-table.el-p)
18325 (org-edit-src-code))
18326 ((or (org-at-table-p)
18327 (save-excursion
18328 (beginning-of-line 1)
18329 (looking-at "[ \t]*#\\+TBLFM:")))
18330 (call-interactively 'org-table-edit-formulas))
18331 (t (call-interactively 'ffap))))
18333 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18334 (defun org-ctrl-c-ctrl-c (&optional arg)
18335 "Set tags in headline, or update according to changed information at point.
18337 This command does many different things, depending on context:
18339 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18340 this is what we do.
18342 - If the cursor is on a statistics cookie, update it.
18344 - If the cursor is in a headline, prompt for tags and insert them
18345 into the current line, aligned to `org-tags-column'. When called
18346 with prefix arg, realign all tags in the current buffer.
18348 - If the cursor is in one of the special #+KEYWORD lines, this
18349 triggers scanning the buffer for these lines and updating the
18350 information.
18352 - If the cursor is inside a table, realign the table. This command
18353 works even if the automatic table editor has been turned off.
18355 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18356 the entire table.
18358 - If the cursor is at a footnote reference or definition, jump to
18359 the corresponding definition or references, respectively.
18361 - If the cursor is a the beginning of a dynamic block, update it.
18363 - If the current buffer is a capture buffer, close note and file it.
18365 - If the cursor is on a <<<target>>>, update radio targets and
18366 corresponding links in this buffer.
18368 - If the cursor is on a numbered item in a plain list, renumber the
18369 ordered list.
18371 - If the cursor is on a checkbox, toggle it.
18373 - If the cursor is on a code block, evaluate it. The variable
18374 `org-confirm-babel-evaluate' can be used to control prompting
18375 before code block evaluation, by default every code block
18376 evaluation requires confirmation. Code block evaluation can be
18377 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18378 (interactive "P")
18379 (let ((org-enable-table-editor t))
18380 (cond
18381 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18382 org-occur-highlights
18383 org-latex-fragment-image-overlays)
18384 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18385 (org-remove-occur-highlights)
18386 (org-remove-latex-fragment-image-overlays)
18387 (message "Temporary highlights/overlays removed from current buffer"))
18388 ((and (local-variable-p 'org-finish-function (current-buffer))
18389 (fboundp org-finish-function))
18390 (funcall org-finish-function))
18391 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18392 ((org-in-regexp org-ts-regexp-both)
18393 (org-timestamp-change 0 'day))
18394 ((or (looking-at org-property-start-re)
18395 (org-at-property-p))
18396 (call-interactively 'org-property-action))
18397 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18398 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18399 (or (org-at-heading-p) (org-at-item-p)))
18400 (call-interactively 'org-update-statistics-cookies))
18401 ((org-at-heading-p) (call-interactively 'org-set-tags))
18402 ((org-at-table.el-p)
18403 (message "Use C-c ' to edit table.el tables"))
18404 ((org-at-table-p)
18405 (org-table-maybe-eval-formula)
18406 (if arg
18407 (call-interactively 'org-table-recalculate)
18408 (org-table-maybe-recalculate-line))
18409 (call-interactively 'org-table-align)
18410 (orgtbl-send-table 'maybe))
18411 ((or (org-footnote-at-reference-p)
18412 (org-footnote-at-definition-p))
18413 (call-interactively 'org-footnote-action))
18414 ((org-at-item-checkbox-p)
18415 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18416 ;; list only if at top item.
18417 (let* ((cbox (match-string 1))
18418 (struct (org-list-struct))
18419 (old-struct (copy-tree struct))
18420 (parents (org-list-parents-alist struct))
18421 (orderedp (org-entry-get nil "ORDERED"))
18422 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18423 block-item)
18424 ;; Use a light version of `org-toggle-checkbox' to avoid
18425 ;; computing list structure twice.
18426 (let ((new-box (cond
18427 ((equal arg '(16)) "[-]")
18428 ((equal arg '(4)) nil)
18429 ((equal "[X]" cbox) "[ ]")
18430 (t "[X]"))))
18431 (if (and firstp arg)
18432 ;; If at first item of sub-list, remove check-box from
18433 ;; every item at the same level.
18434 (mapc
18435 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18436 (org-list-get-all-items
18437 (point-at-bol) struct (org-list-prevs-alist struct)))
18438 (org-list-set-checkbox (point-at-bol) struct new-box)))
18439 ;; Replicate `org-list-write-struct', while grabbing a return
18440 ;; value from `org-list-struct-fix-box'.
18441 (org-list-struct-fix-ind struct parents 2)
18442 (org-list-struct-fix-item-end struct)
18443 (let ((prevs (org-list-prevs-alist struct)))
18444 (org-list-struct-fix-bul struct prevs)
18445 (org-list-struct-fix-ind struct parents)
18446 (setq block-item
18447 (org-list-struct-fix-box struct parents prevs orderedp)))
18448 (org-list-struct-apply-struct struct old-struct)
18449 (org-update-checkbox-count-maybe)
18450 (when block-item
18451 (message
18452 "Checkboxes were removed due to unchecked box at line %d"
18453 (org-current-line block-item)))
18454 (when firstp (org-list-send-list 'maybe))))
18455 ((org-at-item-p)
18456 ;; Cursor at an item: repair list. Do checkbox related actions
18457 ;; only if function was called with an argument. Send list only
18458 ;; if at top item.
18459 (let* ((struct (org-list-struct))
18460 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18461 old-struct)
18462 (when arg
18463 (setq old-struct (copy-tree struct))
18464 (if firstp
18465 ;; If at first item of sub-list, add check-box to every
18466 ;; item at the same level.
18467 (mapc
18468 (lambda (pos)
18469 (unless (org-list-get-checkbox pos struct)
18470 (org-list-set-checkbox pos struct "[ ]")))
18471 (org-list-get-all-items
18472 (point-at-bol) struct (org-list-prevs-alist struct)))
18473 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18474 (org-list-write-struct
18475 struct (org-list-parents-alist struct) old-struct)
18476 (when arg (org-update-checkbox-count-maybe))
18477 (when firstp (org-list-send-list 'maybe))))
18478 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18479 ;; Dynamic block
18480 (beginning-of-line 1)
18481 (save-excursion (org-update-dblock)))
18482 ((save-excursion
18483 (beginning-of-line 1)
18484 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18485 (cond
18486 ((equal (match-string 1) "TBLFM")
18487 ;; Recalculate the table before this line
18488 (save-excursion
18489 (beginning-of-line 1)
18490 (skip-chars-backward " \r\n\t")
18491 (if (org-at-table-p)
18492 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18494 (let ((org-inhibit-startup-visibility-stuff t)
18495 (org-startup-align-all-tables nil))
18496 (when (boundp 'org-table-coordinate-overlays)
18497 (mapc 'delete-overlay org-table-coordinate-overlays)
18498 (setq org-table-coordinate-overlays nil))
18499 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18500 (message "Local setup has been refreshed"))))
18501 ((org-clock-update-time-maybe))
18503 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18504 (error "C-c C-c can do nothing useful at this location"))))))
18506 (defun org-mode-restart ()
18507 "Restart Org-mode, to scan again for special lines.
18508 Also updates the keyword regular expressions."
18509 (interactive)
18510 (org-mode)
18511 (message "Org-mode restarted"))
18513 (defun org-kill-note-or-show-branches ()
18514 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18515 (interactive)
18516 (if (not org-finish-function)
18517 (progn
18518 (hide-subtree)
18519 (call-interactively 'show-branches))
18520 (let ((org-note-abort t))
18521 (funcall org-finish-function))))
18523 (defun org-return (&optional indent)
18524 "Goto next table row or insert a newline.
18525 Calls `org-table-next-row' or `newline', depending on context.
18526 See the individual commands for more information."
18527 (interactive)
18528 (cond
18529 ((bobp) (if indent (newline-and-indent) (newline)))
18530 ((org-at-table-p)
18531 (org-table-justify-field-maybe)
18532 (call-interactively 'org-table-next-row))
18533 ;; when `newline-and-indent' is called within a list, make sure
18534 ;; text moved stays inside the item.
18535 ((and (org-in-item-p) indent)
18536 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18537 (progn
18538 (save-match-data (newline))
18539 (org-indent-line-to (length (match-string 0))))
18540 (let ((ind (org-get-indentation)))
18541 (newline)
18542 (if (org-looking-back org-list-end-re)
18543 (org-indent-line-function)
18544 (org-indent-line-to ind)))))
18545 ((and org-return-follows-link
18546 (let ((tprop (get-text-property (point) 'face)))
18547 (or (eq tprop 'org-link)
18548 (and (listp tprop) (memq 'org-link tprop)))))
18549 (call-interactively 'org-open-at-point))
18550 ((and (org-at-heading-p)
18551 (looking-at
18552 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18553 (org-show-entry)
18554 (end-of-line 1)
18555 (newline))
18556 (t (if indent (newline-and-indent) (newline)))))
18558 (defun org-return-indent ()
18559 "Goto next table row or insert a newline and indent.
18560 Calls `org-table-next-row' or `newline-and-indent', depending on
18561 context. See the individual commands for more information."
18562 (interactive)
18563 (org-return t))
18565 (defun org-ctrl-c-star ()
18566 "Compute table, or change heading status of lines.
18567 Calls `org-table-recalculate' or `org-toggle-heading',
18568 depending on context."
18569 (interactive)
18570 (cond
18571 ((org-at-table-p)
18572 (call-interactively 'org-table-recalculate))
18574 ;; Convert all lines in region to list items
18575 (call-interactively 'org-toggle-heading))))
18577 (defun org-ctrl-c-minus ()
18578 "Insert separator line in table or modify bullet status of line.
18579 Also turns a plain line or a region of lines into list items.
18580 Calls `org-table-insert-hline', `org-toggle-item', or
18581 `org-cycle-list-bullet', depending on context."
18582 (interactive)
18583 (cond
18584 ((org-at-table-p)
18585 (call-interactively 'org-table-insert-hline))
18586 ((org-region-active-p)
18587 (call-interactively 'org-toggle-item))
18588 ((org-in-item-p)
18589 (call-interactively 'org-cycle-list-bullet))
18591 (call-interactively 'org-toggle-item))))
18593 (defun org-toggle-item (arg)
18594 "Convert headings or normal lines to items, items to normal lines.
18595 If there is no active region, only the current line is considered.
18597 If the first non blank line in the region is an headline, convert
18598 all headlines to items, shifting text accordingly.
18600 If it is an item, convert all items to normal lines.
18602 If it is normal text, change region into an item. With a prefix
18603 argument ARG, change each line in region into an item."
18604 (interactive "P")
18605 (let ((shift-text
18606 (function
18607 ;; Shift text in current section to IND, from point to END.
18608 ;; The function leaves point to END line.
18609 (lambda (ind end)
18610 (let ((min-i 1000) (end (copy-marker end)))
18611 ;; First determine the minimum indentation (MIN-I) of
18612 ;; the text.
18613 (save-excursion
18614 (catch 'exit
18615 (while (< (point) end)
18616 (let ((i (org-get-indentation)))
18617 (cond
18618 ;; Skip blank lines and inline tasks.
18619 ((looking-at "^[ \t]*$"))
18620 ((looking-at org-outline-regexp-bol))
18621 ;; We can't find less than 0 indentation.
18622 ((zerop i) (throw 'exit (setq min-i 0)))
18623 ((< i min-i) (setq min-i i))))
18624 (forward-line))))
18625 ;; Then indent each line so that a line indented to
18626 ;; MIN-I becomes indented to IND. Ignore blank lines
18627 ;; and inline tasks in the process.
18628 (let ((delta (- ind min-i)))
18629 (while (< (point) end)
18630 (unless (or (looking-at "^[ \t]*$")
18631 (looking-at org-outline-regexp-bol))
18632 (org-indent-line-to (+ (org-get-indentation) delta)))
18633 (forward-line)))))))
18634 (skip-blanks
18635 (function
18636 ;; Return beginning of first non-blank line, starting from
18637 ;; line at POS.
18638 (lambda (pos)
18639 (save-excursion
18640 (goto-char pos)
18641 (skip-chars-forward " \r\t\n")
18642 (point-at-bol)))))
18643 beg end)
18644 ;; Determine boundaries of changes.
18645 (if (org-region-active-p)
18646 (setq beg (funcall skip-blanks (region-beginning))
18647 end (copy-marker (region-end)))
18648 (setq beg (funcall skip-blanks (point-at-bol))
18649 end (copy-marker (point-at-eol))))
18650 ;; Depending on the starting line, choose an action on the text
18651 ;; between BEG and END.
18652 (org-with-limited-levels
18653 (save-excursion
18654 (goto-char beg)
18655 (cond
18656 ;; Case 1. Start at an item: de-itemize. Note that it only
18657 ;; happens when a region is active: `org-ctrl-c-minus'
18658 ;; would call `org-cycle-list-bullet' otherwise.
18659 ((org-at-item-p)
18660 (while (< (point) end)
18661 (when (org-at-item-p)
18662 (skip-chars-forward " \t")
18663 (delete-region (point) (match-end 0)))
18664 (forward-line)))
18665 ;; Case 2. Start at an heading: convert to items.
18666 ((org-at-heading-p)
18667 (let* ((bul (org-list-bullet-string "-"))
18668 (bul-len (length bul))
18669 ;; Indentation of the first heading. It should be
18670 ;; relative to the indentation of its parent, if any.
18671 (start-ind (save-excursion
18672 (cond
18673 ((not org-adapt-indentation) 0)
18674 ((not (outline-previous-heading)) 0)
18675 (t (length (match-string 0))))))
18676 ;; Level of first heading. Further headings will be
18677 ;; compared to it to determine hierarchy in the list.
18678 (ref-level (org-reduced-level (org-outline-level))))
18679 (while (< (point) end)
18680 (let* ((level (org-reduced-level (org-outline-level)))
18681 (delta (max 0 (- level ref-level))))
18682 ;; If current headline is less indented than the first
18683 ;; one, set it as reference, in order to preserve
18684 ;; subtrees.
18685 (when (< level ref-level) (setq ref-level level))
18686 (replace-match bul t t)
18687 (org-indent-line-to (+ start-ind (* delta bul-len)))
18688 ;; Ensure all text down to END (or SECTION-END) belongs
18689 ;; to the newly created item.
18690 (let ((section-end (save-excursion
18691 (or (outline-next-heading) (point)))))
18692 (forward-line)
18693 (funcall shift-text
18694 (+ start-ind (* (1+ delta) bul-len))
18695 (min end section-end)))))))
18696 ;; Case 3. Normal line with ARG: turn each non-item line into
18697 ;; an item.
18698 (arg
18699 (while (< (point) end)
18700 (unless (or (org-at-heading-p) (org-at-item-p))
18701 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18702 (replace-match
18703 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18704 (forward-line)))
18705 ;; Case 4. Normal line without ARG: make the first line of
18706 ;; region an item, and shift indentation of others
18707 ;; lines to set them as item's body.
18708 (t (let* ((bul (org-list-bullet-string "-"))
18709 (bul-len (length bul))
18710 (ref-ind (org-get-indentation)))
18711 (skip-chars-forward " \t")
18712 (insert bul)
18713 (forward-line)
18714 (while (< (point) end)
18715 ;; Ensure that lines less indented than first one
18716 ;; still get included in item body.
18717 (funcall shift-text
18718 (+ ref-ind bul-len)
18719 (min end (save-excursion (or (outline-next-heading)
18720 (point)))))
18721 (forward-line)))))))))
18723 (defun org-toggle-heading (&optional nstars)
18724 "Convert headings to normal text, or items or text to headings.
18725 If there is no active region, only the current line is considered.
18727 If the first non blank line is an headline, remove the stars from
18728 all headlines in the region.
18730 If it is a plain list item, turn all plain list items into headings.
18732 If it is a normal line, turn each and every normal line (i.e. not
18733 an heading or an item) in the region into a heading.
18735 When converting a line into a heading, the number of stars is chosen
18736 such that the lines become children of the current entry. However,
18737 when a prefix argument is given, its value determines the number of
18738 stars to add."
18739 (interactive "P")
18740 (let ((skip-blanks
18741 (function
18742 ;; Return beginning of first non-blank line, starting from
18743 ;; line at POS.
18744 (lambda (pos)
18745 (save-excursion
18746 (goto-char pos)
18747 (skip-chars-forward " \r\t\n")
18748 (point-at-bol)))))
18749 beg end)
18750 ;; Determine boundaries of changes. If region ends at a bol, do
18751 ;; not consider the last line to be in the region.
18752 (if (org-region-active-p)
18753 (setq beg (funcall skip-blanks (region-beginning))
18754 end (copy-marker (save-excursion
18755 (goto-char (region-end))
18756 (if (bolp) (point) (point-at-eol)))))
18757 (setq beg (funcall skip-blanks (point-at-bol))
18758 end (copy-marker (point-at-eol))))
18759 ;; Ensure inline tasks don't count as headings.
18760 (org-with-limited-levels
18761 (save-excursion
18762 (goto-char beg)
18763 (cond
18764 ;; Case 1. Started at an heading: de-star headings.
18765 ((org-at-heading-p)
18766 (while (< (point) end)
18767 (when (org-at-heading-p t)
18768 (looking-at org-outline-regexp) (replace-match ""))
18769 (forward-line)))
18770 ;; Case 2. Started at an item: change items into headlines.
18771 ;; One star will be added by `org-list-to-subtree'.
18772 ((org-at-item-p)
18773 (let* ((stars (make-string
18774 (if nstars
18775 ;; subtract the star that will be added again by
18776 ;; `org-list-to-subtree'
18777 (1- (prefix-numeric-value current-prefix-arg))
18778 (or (org-current-level) 0))
18779 ?*))
18780 (add-stars
18781 (cond (nstars "") ; stars from prefix only
18782 ((equal stars "") "") ; before first heading
18783 (org-odd-levels-only "*") ; inside heading, odd
18784 (t "")))) ; inside heading, oddeven
18785 (while (< (point) end)
18786 (when (org-at-item-p)
18787 ;; Pay attention to cases when region ends before list.
18788 (let* ((struct (org-list-struct))
18789 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18790 (save-restriction
18791 (narrow-to-region (point) list-end)
18792 (insert
18793 (org-list-to-subtree
18794 (org-list-parse-list t)
18795 '(:istart (concat stars add-stars (funcall get-stars depth))
18796 :icount (concat stars add-stars (funcall get-stars depth))))))))
18797 (forward-line))))
18798 ;; Case 3. Started at normal text: make every line an heading,
18799 ;; skipping headlines and items.
18800 (t (let* ((stars (make-string
18801 (if nstars
18802 (prefix-numeric-value current-prefix-arg)
18803 (or (org-current-level) 0))
18804 ?*))
18805 (add-stars
18806 (cond (nstars "") ; stars from prefix only
18807 ((equal stars "") "*") ; before first heading
18808 (org-odd-levels-only "**") ; inside heading, odd
18809 (t "*"))) ; inside heading, oddeven
18810 (rpl (concat stars add-stars " ")))
18811 (while (< (point) end)
18812 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18813 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18814 (replace-match (concat rpl (match-string 2))))
18815 (forward-line)))))))))
18817 (defun org-meta-return (&optional arg)
18818 "Insert a new heading or wrap a region in a table.
18819 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18820 See the individual commands for more information."
18821 (interactive "P")
18822 (cond
18823 ((run-hook-with-args-until-success 'org-metareturn-hook))
18824 ((org-at-table-p)
18825 (call-interactively 'org-table-wrap-region))
18826 (t (call-interactively 'org-insert-heading))))
18828 ;;; Menu entries
18830 ;; Define the Org-mode menus
18831 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18832 '("Tbl"
18833 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18834 ["Next Field" org-cycle (org-at-table-p)]
18835 ["Previous Field" org-shifttab (org-at-table-p)]
18836 ["Next Row" org-return (org-at-table-p)]
18837 "--"
18838 ["Blank Field" org-table-blank-field (org-at-table-p)]
18839 ["Edit Field" org-table-edit-field (org-at-table-p)]
18840 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18841 "--"
18842 ("Column"
18843 ["Move Column Left" org-metaleft (org-at-table-p)]
18844 ["Move Column Right" org-metaright (org-at-table-p)]
18845 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18846 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18847 ("Row"
18848 ["Move Row Up" org-metaup (org-at-table-p)]
18849 ["Move Row Down" org-metadown (org-at-table-p)]
18850 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18851 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18852 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18853 "--"
18854 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18855 ("Rectangle"
18856 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18857 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18858 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18859 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18860 "--"
18861 ("Calculate"
18862 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18863 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18864 ["Edit Formulas" org-edit-special (org-at-table-p)]
18865 "--"
18866 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18867 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18868 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18869 "--"
18870 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18871 "--"
18872 ["Sum Column/Rectangle" org-table-sum
18873 (or (org-at-table-p) (org-region-active-p))]
18874 ["Which Column?" org-table-current-column (org-at-table-p)])
18875 ["Debug Formulas"
18876 org-table-toggle-formula-debugger
18877 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18878 ["Show Col/Row Numbers"
18879 org-table-toggle-coordinate-overlays
18880 :style toggle
18881 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18882 "--"
18883 ["Create" org-table-create (and (not (org-at-table-p))
18884 org-enable-table-editor)]
18885 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18886 ["Import from File" org-table-import (not (org-at-table-p))]
18887 ["Export to File" org-table-export (org-at-table-p)]
18888 "--"
18889 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18891 (easy-menu-define org-org-menu org-mode-map "Org menu"
18892 '("Org"
18893 ("Show/Hide"
18894 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18895 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18896 ["Sparse Tree..." org-sparse-tree t]
18897 ["Reveal Context" org-reveal t]
18898 ["Show All" show-all t]
18899 "--"
18900 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18901 "--"
18902 ["New Heading" org-insert-heading t]
18903 ("Navigate Headings"
18904 ["Up" outline-up-heading t]
18905 ["Next" outline-next-visible-heading t]
18906 ["Previous" outline-previous-visible-heading t]
18907 ["Next Same Level" outline-forward-same-level t]
18908 ["Previous Same Level" outline-backward-same-level t]
18909 "--"
18910 ["Jump" org-goto t])
18911 ("Edit Structure"
18912 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18913 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18914 "--"
18915 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18916 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18917 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18918 "--"
18919 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18920 "--"
18921 ["Copy visible text" org-copy-visible t]
18922 "--"
18923 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18924 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18925 ["Demote Heading" org-metaright (not (org-at-table-p))]
18926 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18927 "--"
18928 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18929 "--"
18930 ["Convert to odd levels" org-convert-to-odd-levels t]
18931 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18932 ("Editing"
18933 ["Emphasis..." org-emphasize t]
18934 ["Edit Source Example" org-edit-special t]
18935 "--"
18936 ["Footnote new/jump" org-footnote-action t]
18937 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18938 ("Archive"
18939 ["Archive (default method)" org-archive-subtree-default t]
18940 "--"
18941 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18942 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18943 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18945 "--"
18946 ("Hyperlinks"
18947 ["Store Link (Global)" org-store-link t]
18948 ["Find existing link to here" org-occur-link-in-agenda-files t]
18949 ["Insert Link" org-insert-link t]
18950 ["Follow Link" org-open-at-point t]
18951 "--"
18952 ["Next link" org-next-link t]
18953 ["Previous link" org-previous-link t]
18954 "--"
18955 ["Descriptive Links"
18956 org-toggle-link-display
18957 :style radio
18958 :selected org-descriptive-links
18960 ["Literal Links"
18961 org-toggle-link-display
18962 :style radio
18963 :selected (not org-descriptive-links)])
18964 "--"
18965 ("TODO Lists"
18966 ["TODO/DONE/-" org-todo t]
18967 ("Select keyword"
18968 ["Next keyword" org-shiftright (org-at-heading-p)]
18969 ["Previous keyword" org-shiftleft (org-at-heading-p)]
18970 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18971 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
18972 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
18973 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18974 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18975 "--"
18976 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18977 :selected org-enforce-todo-dependencies :style toggle :active t]
18978 "Settings for tree at point"
18979 ["Do Children sequentially" org-toggle-ordered-property :style radio
18980 :selected (org-entry-get nil "ORDERED")
18981 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18982 ["Do Children parallel" org-toggle-ordered-property :style radio
18983 :selected (not (org-entry-get nil "ORDERED"))
18984 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18985 "--"
18986 ["Set Priority" org-priority t]
18987 ["Priority Up" org-shiftup t]
18988 ["Priority Down" org-shiftdown t]
18989 "--"
18990 ["Get news from all feeds" org-feed-update-all t]
18991 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18992 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18993 ("TAGS and Properties"
18994 ["Set Tags" org-set-tags-command t]
18995 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18996 "--"
18997 ["Set property" org-set-property t]
18998 ["Column view of properties" org-columns t]
18999 ["Insert Column View DBlock" org-insert-columns-dblock t])
19000 ("Dates and Scheduling"
19001 ["Timestamp" org-time-stamp t]
19002 ["Timestamp (inactive)" org-time-stamp-inactive t]
19003 ("Change Date"
19004 ["1 Day Later" org-shiftright t]
19005 ["1 Day Earlier" org-shiftleft t]
19006 ["1 ... Later" org-shiftup t]
19007 ["1 ... Earlier" org-shiftdown t])
19008 ["Compute Time Range" org-evaluate-time-range t]
19009 ["Schedule Item" org-schedule t]
19010 ["Deadline" org-deadline t]
19011 "--"
19012 ["Custom time format" org-toggle-time-stamp-overlays
19013 :style radio :selected org-display-custom-times]
19014 "--"
19015 ["Goto Calendar" org-goto-calendar t]
19016 ["Date from Calendar" org-date-from-calendar t]
19017 "--"
19018 ["Start/Restart Timer" org-timer-start t]
19019 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19020 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19021 ["Insert Timer String" org-timer t]
19022 ["Insert Timer Item" org-timer-item t])
19023 ("Logging work"
19024 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19025 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19026 ["Clock out" org-clock-out t]
19027 ["Clock cancel" org-clock-cancel t]
19028 "--"
19029 ["Mark as default task" org-clock-mark-default-task t]
19030 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19031 ["Goto running clock" org-clock-goto t]
19032 "--"
19033 ["Display times" org-clock-display t]
19034 ["Create clock table" org-clock-report t]
19035 "--"
19036 ["Record DONE time"
19037 (progn (setq org-log-done (not org-log-done))
19038 (message "Switching to %s will %s record a timestamp"
19039 (car org-done-keywords)
19040 (if org-log-done "automatically" "not")))
19041 :style toggle :selected org-log-done])
19042 "--"
19043 ["Agenda Command..." org-agenda t]
19044 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19045 ("File List for Agenda")
19046 ("Special views current file"
19047 ["TODO Tree" org-show-todo-tree t]
19048 ["Check Deadlines" org-check-deadlines t]
19049 ["Timeline" org-timeline t]
19050 ["Tags/Property tree" org-match-sparse-tree t])
19051 "--"
19052 ["Export/Publish..." org-export t]
19053 ("LaTeX"
19054 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19055 :selected org-cdlatex-mode]
19056 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19057 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19058 ["Modify math symbol" org-cdlatex-math-modify
19059 (org-inside-LaTeX-fragment-p)]
19060 ["Insert citation" org-reftex-citation t]
19061 "--"
19062 ["Template for BEAMER" org-insert-beamer-options-template t])
19063 "--"
19064 ("MobileOrg"
19065 ["Push Files and Views" org-mobile-push t]
19066 ["Get Captured and Flagged" org-mobile-pull t]
19067 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19068 "--"
19069 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19070 "--"
19071 ("Documentation"
19072 ["Show Version" org-version t]
19073 ["Info Documentation" org-info t])
19074 ("Customize"
19075 ["Browse Org Group" org-customize t]
19076 "--"
19077 ["Expand This Menu" org-create-customize-menu
19078 (fboundp 'customize-menu-create)])
19079 ["Send bug report" org-submit-bug-report t]
19080 "--"
19081 ("Refresh/Reload"
19082 ["Refresh setup current buffer" org-mode-restart t]
19083 ["Reload Org (after update)" org-reload t]
19084 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19087 (defun org-info (&optional node)
19088 "Read documentation for Org-mode in the info system.
19089 With optional NODE, go directly to that node."
19090 (interactive)
19091 (info (format "(org)%s" (or node ""))))
19093 ;;;###autoload
19094 (defun org-submit-bug-report ()
19095 "Submit a bug report on Org-mode via mail.
19097 Don't hesitate to report any problems or inaccurate documentation.
19099 If you don't have setup sending mail from (X)Emacs, please copy the
19100 output buffer into your mail program, as it gives us important
19101 information about your Org-mode version and configuration."
19102 (interactive)
19103 (require 'reporter)
19104 (org-load-modules-maybe)
19105 (org-require-autoloaded-modules)
19106 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19107 (reporter-submit-bug-report
19108 "emacs-orgmode@gnu.org"
19109 (org-version)
19110 (let (list)
19111 (save-window-excursion
19112 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19113 (delete-other-windows)
19114 (erase-buffer)
19115 (insert "You are about to submit a bug report to the Org-mode mailing list.
19117 We would like to add your full Org-mode and Outline configuration to the
19118 bug report. This greatly simplifies the work of the maintainer and
19119 other experts on the mailing list.
19121 HOWEVER, some variables you have customized may contain private
19122 information. The names of customers, colleagues, or friends, might
19123 appear in the form of file names, tags, todo states, or search strings.
19124 If you answer yes to the prompt, you might want to check and remove
19125 such private information before sending the email.")
19126 (add-text-properties (point-min) (point-max) '(face org-warning))
19127 (when (yes-or-no-p "Include your Org-mode configuration ")
19128 (mapatoms
19129 (lambda (v)
19130 (and (boundp v)
19131 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19132 (or (and (symbol-value v)
19133 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19134 (and
19135 (get v 'custom-type) (get v 'standard-value)
19136 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19137 (push v list)))))
19138 (kill-buffer (get-buffer "*Warn about privacy*"))
19139 list))
19140 nil nil
19141 "Remember to cover the basics, that is, what you expected to happen and
19142 what in fact did happen. You don't know how to make a good report? See
19144 http://orgmode.org/manual/Feedback.html#Feedback
19146 Your bug report will be posted to the Org-mode mailing list.
19147 ------------------------------------------------------------------------")
19148 (save-excursion
19149 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19150 (replace-match "\\1Bug: \\3 [\\2]")))))
19153 (defun org-install-agenda-files-menu ()
19154 (let ((bl (buffer-list)))
19155 (save-excursion
19156 (while bl
19157 (set-buffer (pop bl))
19158 (if (eq major-mode 'org-mode) (setq bl nil)))
19159 (when (eq major-mode 'org-mode)
19160 (easy-menu-change
19161 '("Org") "File List for Agenda"
19162 (append
19163 (list
19164 ["Edit File List" (org-edit-agenda-file-list) t]
19165 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19166 ["Remove Current File from List" org-remove-file t]
19167 ["Cycle through agenda files" org-cycle-agenda-files t]
19168 ["Occur in all agenda files" org-occur-in-agenda-files t]
19169 "--")
19170 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19172 ;;;; Documentation
19174 ;;;###autoload
19175 (defun org-require-autoloaded-modules ()
19176 (interactive)
19177 (mapc 'require
19178 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19179 org-docbook org-exp org-html org-icalendar
19180 org-id org-latex
19181 org-publish org-remember org-table
19182 org-timer org-xoxo)))
19184 ;;;###autoload
19185 (defun org-reload (&optional uncompiled)
19186 "Reload all org lisp files.
19187 With prefix arg UNCOMPILED, load the uncompiled versions."
19188 (interactive "P")
19189 (require 'find-func)
19190 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19191 (dir-org (file-name-directory (org-find-library-name "org")))
19192 (dir-org-contrib (ignore-errors
19193 (file-name-directory
19194 (org-find-library-name "org-contribdir"))))
19195 (babel-files
19196 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19197 (append (list nil "comint" "eval" "exp" "keys"
19198 "lob" "ref" "table" "tangle")
19199 (delq nil
19200 (mapcar
19201 (lambda (lang)
19202 (when (cdr lang) (symbol-name (car lang))))
19203 org-babel-load-languages)))))
19204 (files
19205 (append (directory-files dir-org t file-re)
19206 babel-files
19207 (and dir-org-contrib
19208 (directory-files dir-org-contrib t file-re))))
19209 (remove-re (concat (if (featurep 'xemacs)
19210 "org-colview" "org-colview-xemacs")
19211 "\\'")))
19212 (setq files (mapcar 'file-name-sans-extension files))
19213 (setq files (mapcar
19214 (lambda (x) (if (string-match remove-re x) nil x))
19215 files))
19216 (setq files (delq nil files))
19217 (mapc
19218 (lambda (f)
19219 (when (featurep (intern (file-name-nondirectory f)))
19220 (if (and (not uncompiled)
19221 (file-exists-p (concat f ".elc")))
19222 (load (concat f ".elc") nil nil t)
19223 (load (concat f ".el") nil nil t))))
19224 files))
19225 (org-version))
19227 ;;;###autoload
19228 (defun org-customize ()
19229 "Call the customize function with org as argument."
19230 (interactive)
19231 (org-load-modules-maybe)
19232 (org-require-autoloaded-modules)
19233 (customize-browse 'org))
19235 (defun org-create-customize-menu ()
19236 "Create a full customization menu for Org-mode, insert it into the menu."
19237 (interactive)
19238 (org-load-modules-maybe)
19239 (org-require-autoloaded-modules)
19240 (if (fboundp 'customize-menu-create)
19241 (progn
19242 (easy-menu-change
19243 '("Org") "Customize"
19244 `(["Browse Org group" org-customize t]
19245 "--"
19246 ,(customize-menu-create 'org)
19247 ["Set" Custom-set t]
19248 ["Save" Custom-save t]
19249 ["Reset to Current" Custom-reset-current t]
19250 ["Reset to Saved" Custom-reset-saved t]
19251 ["Reset to Standard Settings" Custom-reset-standard t]))
19252 (message "\"Org\"-menu now contains full customization menu"))
19253 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19255 ;;;; Miscellaneous stuff
19257 ;;; Generally useful functions
19259 (defun org-get-at-bol (property)
19260 "Get text property PROPERTY at beginning of line."
19261 (get-text-property (point-at-bol) property))
19263 (defun org-find-text-property-in-string (prop s)
19264 "Return the first non-nil value of property PROP in string S."
19265 (or (get-text-property 0 prop s)
19266 (get-text-property (or (next-single-property-change 0 prop s) 0)
19267 prop s)))
19269 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19270 "Display the given MESSAGE as a warning."
19271 (if (fboundp 'display-warning)
19272 (display-warning 'org message
19273 (if (featurep 'xemacs) 'warning :warning))
19274 (let ((buf (get-buffer-create "*Org warnings*")))
19275 (with-current-buffer buf
19276 (goto-char (point-max))
19277 (insert "Warning (Org): " message)
19278 (unless (bolp)
19279 (newline)))
19280 (display-buffer buf)
19281 (sit-for 0))))
19283 (defun org-eval (form)
19284 "Eval FORM and return result."
19285 (condition-case error
19286 (eval form)
19287 (error (format "%%![Error: %s]" error))))
19289 (defun org-in-clocktable-p ()
19290 "Check if the cursor is in a clocktable."
19291 (let ((pos (point)) start)
19292 (save-excursion
19293 (end-of-line 1)
19294 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19295 (setq start (match-beginning 0))
19296 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19297 (>= (match-end 0) pos)
19298 start))))
19300 (defun org-in-commented-line ()
19301 "Is point in a line starting with `#'?"
19302 (equal (char-after (point-at-bol)) ?#))
19304 (defun org-in-indented-comment-line ()
19305 "Is point in a line starting with `#' after some white space?"
19306 (save-excursion
19307 (save-match-data
19308 (goto-char (point-at-bol))
19309 (looking-at "[ \t]*#"))))
19311 (defun org-in-verbatim-emphasis ()
19312 (save-match-data
19313 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19315 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19316 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19317 (if (and marker (marker-buffer marker)
19318 (buffer-live-p (marker-buffer marker)))
19319 (progn
19320 (org-pop-to-buffer-same-window (marker-buffer marker))
19321 (if (or (> marker (point-max)) (< marker (point-min)))
19322 (widen))
19323 (goto-char marker)
19324 (org-show-context 'org-goto))
19325 (if bookmark
19326 (bookmark-jump bookmark)
19327 (error "Cannot find location"))))
19329 (defun org-quote-csv-field (s)
19330 "Quote field for inclusion in CSV material."
19331 (if (string-match "[\",]" s)
19332 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19335 (defun org-force-self-insert (N)
19336 "Needed to enforce self-insert under remapping."
19337 (interactive "p")
19338 (self-insert-command N))
19340 (defun org-string-width (s)
19341 "Compute width of string, ignoring invisible characters.
19342 This ignores character with invisibility property `org-link', and also
19343 characters with property `org-cwidth', because these will become invisible
19344 upon the next fontification round."
19345 (let (b l)
19346 (when (or (eq t buffer-invisibility-spec)
19347 (assq 'org-link buffer-invisibility-spec))
19348 (while (setq b (text-property-any 0 (length s)
19349 'invisible 'org-link s))
19350 (setq s (concat (substring s 0 b)
19351 (substring s (or (next-single-property-change
19352 b 'invisible s) (length s)))))))
19353 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19354 (setq s (concat (substring s 0 b)
19355 (substring s (or (next-single-property-change
19356 b 'org-cwidth s) (length s))))))
19357 (setq l (string-width s) b -1)
19358 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19359 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19362 (defun org-shorten-string (s maxlength)
19363 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19364 If the string is shorter or has length MAXLENGTH, just return the
19365 original string. If it is longer, the functions finds a space in the
19366 string, breaks this string off at that locations and adds three dots
19367 as ellipsis. Including the ellipsis, the string will not be longer
19368 than MAXLENGTH. If finding a good breaking point in the string does
19369 not work, the string is just chopped off in the middle of a word
19370 if necessary."
19371 (if (<= (length s) maxlength)
19373 (let* ((n (max (- maxlength 4) 1))
19374 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19375 (if (string-match re s)
19376 (concat (match-string 1 s) "...")
19377 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19379 (defun org-get-indentation (&optional line)
19380 "Get the indentation of the current line, interpreting tabs.
19381 When LINE is given, assume it represents a line and compute its indentation."
19382 (if line
19383 (if (string-match "^ *" (org-remove-tabs line))
19384 (match-end 0))
19385 (save-excursion
19386 (beginning-of-line 1)
19387 (skip-chars-forward " \t")
19388 (current-column))))
19390 (defun org-get-string-indentation (s)
19391 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19392 (let ((n -1) (i 0) (w tab-width) c)
19393 (catch 'exit
19394 (while (< (setq n (1+ n)) (length s))
19395 (setq c (aref s n))
19396 (cond ((= c ?\ ) (setq i (1+ i)))
19397 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19398 (t (throw 'exit t)))))
19401 (defun org-remove-tabs (s &optional width)
19402 "Replace tabulators in S with spaces.
19403 Assumes that s is a single line, starting in column 0."
19404 (setq width (or width tab-width))
19405 (while (string-match "\t" s)
19406 (setq s (replace-match
19407 (make-string
19408 (- (* width (/ (+ (match-beginning 0) width) width))
19409 (match-beginning 0)) ?\ )
19410 t t s)))
19413 (defun org-fix-indentation (line ind)
19414 "Fix indentation in LINE.
19415 IND is a cons cell with target and minimum indentation.
19416 If the current indentation in LINE is smaller than the minimum,
19417 leave it alone. If it is larger than ind, set it to the target."
19418 (let* ((l (org-remove-tabs line))
19419 (i (org-get-indentation l))
19420 (i1 (car ind)) (i2 (cdr ind)))
19421 (if (>= i i2) (setq l (substring line i2)))
19422 (if (> i1 0)
19423 (concat (make-string i1 ?\ ) l)
19424 l)))
19426 (defun org-remove-indentation (code &optional n)
19427 "Remove the maximum common indentation from the lines in CODE.
19428 N may optionally be the number of spaces to remove."
19429 (with-temp-buffer
19430 (insert code)
19431 (org-do-remove-indentation n)
19432 (buffer-string)))
19434 (defun org-do-remove-indentation (&optional n)
19435 "Remove the maximum common indentation from the buffer."
19436 (untabify (point-min) (point-max))
19437 (let ((min 10000) re)
19438 (if n
19439 (setq min n)
19440 (goto-char (point-min))
19441 (while (re-search-forward "^ *[^ \n]" nil t)
19442 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19443 (unless (or (= min 0) (= min 10000))
19444 (setq re (format "^ \\{%d\\}" min))
19445 (goto-char (point-min))
19446 (while (re-search-forward re nil t)
19447 (replace-match "")
19448 (end-of-line 1))
19449 min)))
19451 (defun org-fill-template (template alist)
19452 "Find each %key of ALIST in TEMPLATE and replace it."
19453 (let ((case-fold-search nil)
19454 entry key value)
19455 (setq alist (sort (copy-sequence alist)
19456 (lambda (a b) (< (length (car a)) (length (car b))))))
19457 (while (setq entry (pop alist))
19458 (setq template
19459 (replace-regexp-in-string
19460 (concat "%" (regexp-quote (car entry)))
19461 (cdr entry) template t t)))
19462 template))
19464 (defun org-base-buffer (buffer)
19465 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19466 (if (not buffer)
19467 buffer
19468 (or (buffer-base-buffer buffer)
19469 buffer)))
19471 (defun org-trim (s)
19472 "Remove whitespace at beginning and end of string."
19473 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19474 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19477 (defun org-wrap (string &optional width lines)
19478 "Wrap string to either a number of lines, or a width in characters.
19479 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19480 that costs. If there is a word longer than WIDTH, the text is actually
19481 wrapped to the length of that word.
19482 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19483 many lines, whatever width that takes.
19484 The return value is a list of lines, without newlines at the end."
19485 (let* ((words (org-split-string string "[ \t\n]+"))
19486 (maxword (apply 'max (mapcar 'org-string-width words)))
19487 w ll)
19488 (cond (width
19489 (org-do-wrap words (max maxword width)))
19490 (lines
19491 (setq w maxword)
19492 (setq ll (org-do-wrap words maxword))
19493 (if (<= (length ll) lines)
19495 (setq ll words)
19496 (while (> (length ll) lines)
19497 (setq w (1+ w))
19498 (setq ll (org-do-wrap words w)))
19499 ll))
19500 (t (error "Cannot wrap this")))))
19502 (defun org-do-wrap (words width)
19503 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19504 (let (lines line)
19505 (while words
19506 (setq line (pop words))
19507 (while (and words (< (+ (length line) (length (car words))) width))
19508 (setq line (concat line " " (pop words))))
19509 (setq lines (push line lines)))
19510 (nreverse lines)))
19512 (defun org-split-string (string &optional separators)
19513 "Splits STRING into substrings at SEPARATORS.
19514 No empty strings are returned if there are matches at the beginning
19515 and end of string."
19516 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19517 (start 0)
19518 notfirst
19519 (list nil))
19520 (while (and (string-match rexp string
19521 (if (and notfirst
19522 (= start (match-beginning 0))
19523 (< start (length string)))
19524 (1+ start) start))
19525 (< (match-beginning 0) (length string)))
19526 (setq notfirst t)
19527 (or (eq (match-beginning 0) 0)
19528 (and (eq (match-beginning 0) (match-end 0))
19529 (eq (match-beginning 0) start))
19530 (setq list
19531 (cons (substring string start (match-beginning 0))
19532 list)))
19533 (setq start (match-end 0)))
19534 (or (eq start (length string))
19535 (setq list
19536 (cons (substring string start)
19537 list)))
19538 (nreverse list)))
19540 (defun org-quote-vert (s)
19541 "Replace \"|\" with \"\\vert\"."
19542 (while (string-match "|" s)
19543 (setq s (replace-match "\\vert" t t s)))
19546 (defun org-uuidgen-p (s)
19547 "Is S an ID created by UUIDGEN?"
19548 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19550 (defun org-context ()
19551 "Return a list of contexts of the current cursor position.
19552 If several contexts apply, all are returned.
19553 Each context entry is a list with a symbol naming the context, and
19554 two positions indicating start and end of the context. Possible
19555 contexts are:
19557 :headline anywhere in a headline
19558 :headline-stars on the leading stars in a headline
19559 :todo-keyword on a TODO keyword (including DONE) in a headline
19560 :tags on the TAGS in a headline
19561 :priority on the priority cookie in a headline
19562 :item on the first line of a plain list item
19563 :item-bullet on the bullet/number of a plain list item
19564 :checkbox on the checkbox in a plain list item
19565 :table in an org-mode table
19566 :table-special on a special filed in a table
19567 :table-table in a table.el table
19568 :link on a hyperlink
19569 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19570 :target on a <<target>>
19571 :radio-target on a <<<radio-target>>>
19572 :latex-fragment on a LaTeX fragment
19573 :latex-preview on a LaTeX fragment with overlaid preview image
19575 This function expects the position to be visible because it uses font-lock
19576 faces as a help to recognize the following contexts: :table-special, :link,
19577 and :keyword."
19578 (let* ((f (get-text-property (point) 'face))
19579 (faces (if (listp f) f (list f)))
19580 (p (point)) clist o)
19581 ;; First the large context
19582 (cond
19583 ((org-at-heading-p t)
19584 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19585 (when (progn
19586 (beginning-of-line 1)
19587 (looking-at org-todo-line-tags-regexp))
19588 (push (org-point-in-group p 1 :headline-stars) clist)
19589 (push (org-point-in-group p 2 :todo-keyword) clist)
19590 (push (org-point-in-group p 4 :tags) clist))
19591 (goto-char p)
19592 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19593 (if (looking-at "\\[#[A-Z0-9]\\]")
19594 (push (org-point-in-group p 0 :priority) clist)))
19596 ((org-at-item-p)
19597 (push (org-point-in-group p 2 :item-bullet) clist)
19598 (push (list :item (point-at-bol)
19599 (save-excursion (org-end-of-item) (point)))
19600 clist)
19601 (and (org-at-item-checkbox-p)
19602 (push (org-point-in-group p 0 :checkbox) clist)))
19604 ((org-at-table-p)
19605 (push (list :table (org-table-begin) (org-table-end)) clist)
19606 (if (memq 'org-formula faces)
19607 (push (list :table-special
19608 (previous-single-property-change p 'face)
19609 (next-single-property-change p 'face)) clist)))
19610 ((org-at-table-p 'any)
19611 (push (list :table-table) clist)))
19612 (goto-char p)
19614 ;; Now the small context
19615 (cond
19616 ((org-at-timestamp-p)
19617 (push (org-point-in-group p 0 :timestamp) clist))
19618 ((memq 'org-link faces)
19619 (push (list :link
19620 (previous-single-property-change p 'face)
19621 (next-single-property-change p 'face)) clist))
19622 ((memq 'org-special-keyword faces)
19623 (push (list :keyword
19624 (previous-single-property-change p 'face)
19625 (next-single-property-change p 'face)) clist))
19626 ((org-at-target-p)
19627 (push (org-point-in-group p 0 :target) clist)
19628 (goto-char (1- (match-beginning 0)))
19629 (if (looking-at org-radio-target-regexp)
19630 (push (org-point-in-group p 0 :radio-target) clist))
19631 (goto-char p))
19632 ((setq o (car (delq nil
19633 (mapcar
19634 (lambda (x)
19635 (if (memq x org-latex-fragment-image-overlays) x))
19636 (overlays-at (point))))))
19637 (push (list :latex-fragment
19638 (overlay-start o) (overlay-end o)) clist)
19639 (push (list :latex-preview
19640 (overlay-start o) (overlay-end o)) clist))
19641 ((org-inside-LaTeX-fragment-p)
19642 ;; FIXME: positions wrong.
19643 (push (list :latex-fragment (point) (point)) clist)))
19645 (setq clist (nreverse (delq nil clist)))
19646 clist))
19648 ;; FIXME: Compare with at-regexp-p Do we need both?
19649 (defun org-in-regexp (re &optional nlines visually)
19650 "Check if point is inside a match of regexp.
19651 Normally only the current line is checked, but you can include NLINES extra
19652 lines both before and after point into the search.
19653 If VISUALLY is set, require that the cursor is not after the match but
19654 really on, so that the block visually is on the match."
19655 (catch 'exit
19656 (let ((pos (point))
19657 (eol (point-at-eol (+ 1 (or nlines 0))))
19658 (inc (if visually 1 0)))
19659 (save-excursion
19660 (beginning-of-line (- 1 (or nlines 0)))
19661 (while (re-search-forward re eol t)
19662 (if (and (<= (match-beginning 0) pos)
19663 (>= (+ inc (match-end 0)) pos))
19664 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19666 (defun org-at-regexp-p (regexp)
19667 "Is point inside a match of REGEXP in the current line?"
19668 (catch 'exit
19669 (save-excursion
19670 (let ((pos (point)) (end (point-at-eol)))
19671 (beginning-of-line 1)
19672 (while (re-search-forward regexp end t)
19673 (if (and (<= (match-beginning 0) pos)
19674 (>= (match-end 0) pos))
19675 (throw 'exit t)))
19676 nil))))
19678 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19679 "Non-nil when point is between matches of START-RE and END-RE.
19681 Also return a non-nil value when point is on one of the matches.
19683 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19684 buffer positions. Default values are the positions of headlines
19685 surrounding the point.
19687 The functions returns a cons cell whose car (resp. cdr) is the
19688 position before START-RE (resp. after END-RE)."
19689 (save-match-data
19690 (let ((pos (point))
19691 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19692 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19693 beg end)
19694 (save-excursion
19695 ;; Point is on a block when on START-RE or if START-RE can be
19696 ;; found before it...
19697 (and (or (org-at-regexp-p start-re)
19698 (re-search-backward start-re limit-up t))
19699 (setq beg (match-beginning 0))
19700 ;; ... and END-RE after it...
19701 (goto-char (match-end 0))
19702 (re-search-forward end-re limit-down t)
19703 (> (setq end (match-end 0)) pos)
19704 ;; ... without another START-RE in-between.
19705 (goto-char (match-beginning 0))
19706 (not (re-search-backward start-re (1+ beg) t))
19707 ;; Return value.
19708 (cons beg end))))))
19710 (defun org-in-block-p (names)
19711 "Non-nil when point belongs to a block whose name belongs to NAMES.
19713 NAMES is a list of strings containing names of blocks.
19715 Return first block name matched, or nil. Beware that in case of
19716 nested blocks, the returned name may not belong to the closest
19717 block from point."
19718 (save-match-data
19719 (catch 'exit
19720 (let ((case-fold-search t)
19721 (lim-up (save-excursion (outline-previous-heading)))
19722 (lim-down (save-excursion (outline-next-heading))))
19723 (mapc (lambda (name)
19724 (let ((n (regexp-quote name)))
19725 (when (org-between-regexps-p
19726 (concat "^[ \t]*#\\+begin_" n)
19727 (concat "^[ \t]*#\\+end_" n)
19728 lim-up lim-down)
19729 (throw 'exit n))))
19730 names))
19731 nil)))
19733 (defun org-occur-in-agenda-files (regexp &optional nlines)
19734 "Call `multi-occur' with buffers for all agenda files."
19735 (interactive "sOrg-files matching: \np")
19736 (let* ((files (org-agenda-files))
19737 (tnames (mapcar 'file-truename files))
19738 (extra org-agenda-text-search-extra-files)
19740 (when (eq (car extra) 'agenda-archives)
19741 (setq extra (cdr extra))
19742 (setq files (org-add-archive-files files)))
19743 (while (setq f (pop extra))
19744 (unless (member (file-truename f) tnames)
19745 (add-to-list 'files f 'append)
19746 (add-to-list 'tnames (file-truename f) 'append)))
19747 (multi-occur
19748 (mapcar (lambda (x)
19749 (with-current-buffer
19750 (or (get-file-buffer x) (find-file-noselect x))
19751 (widen)
19752 (current-buffer)))
19753 files)
19754 regexp)))
19756 (if (boundp 'occur-mode-find-occurrence-hook)
19757 ;; Emacs 23
19758 (add-hook 'occur-mode-find-occurrence-hook
19759 (lambda ()
19760 (when (eq major-mode 'org-mode)
19761 (org-reveal))))
19762 ;; Emacs 22
19763 (defadvice occur-mode-goto-occurrence
19764 (after org-occur-reveal activate)
19765 (and (eq major-mode 'org-mode) (org-reveal)))
19766 (defadvice occur-mode-goto-occurrence-other-window
19767 (after org-occur-reveal activate)
19768 (and (eq major-mode 'org-mode) (org-reveal)))
19769 (defadvice occur-mode-display-occurrence
19770 (after org-occur-reveal activate)
19771 (when (eq major-mode 'org-mode)
19772 (let ((pos (occur-mode-find-occurrence)))
19773 (with-current-buffer (marker-buffer pos)
19774 (save-excursion
19775 (goto-char pos)
19776 (org-reveal)))))))
19778 (defun org-occur-link-in-agenda-files ()
19779 "Create a link and search for it in the agendas.
19780 The link is not stored in `org-stored-links', it is just created
19781 for the search purpose."
19782 (interactive)
19783 (let ((link (condition-case nil
19784 (org-store-link nil)
19785 (error "Unable to create a link to here"))))
19786 (org-occur-in-agenda-files (regexp-quote link))))
19788 (defun org-uniquify (list)
19789 "Remove duplicate elements from LIST."
19790 (let (res)
19791 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19792 res))
19794 (defun org-delete-all (elts list)
19795 "Remove all elements in ELTS from LIST."
19796 (while elts
19797 (setq list (delete (pop elts) list)))
19798 list)
19800 (defun org-count (cl-item cl-seq)
19801 "Count the number of occurrences of ITEM in SEQ.
19802 Taken from `count' in cl-seq.el with all keyword arguments removed."
19803 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19804 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19805 (while (< cl-start cl-end)
19806 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19807 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19808 (setq cl-start (1+ cl-start)))
19809 cl-count))
19811 (defun org-remove-if (predicate seq)
19812 "Remove everything from SEQ that fulfills PREDICATE."
19813 (let (res e)
19814 (while seq
19815 (setq e (pop seq))
19816 (if (not (funcall predicate e)) (push e res)))
19817 (nreverse res)))
19819 (defun org-remove-if-not (predicate seq)
19820 "Remove everything from SEQ that does not fulfill PREDICATE."
19821 (let (res e)
19822 (while seq
19823 (setq e (pop seq))
19824 (if (funcall predicate e) (push e res)))
19825 (nreverse res)))
19827 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19828 "Reduce two-argument FUNCTION across SEQ.
19829 Taken from `reduce' in cl-seq.el with all keyword arguments but
19830 \":initial-value\" removed."
19831 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19832 (cadr (memq :initial-value cl-keys)))
19833 (cl-seq (pop cl-seq))
19834 (t (funcall cl-func)))))
19835 (while cl-seq
19836 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19837 cl-accum))
19839 (defun org-back-over-empty-lines ()
19840 "Move backwards over whitespace, to the beginning of the first empty line.
19841 Returns the number of empty lines passed."
19842 (let ((pos (point)))
19843 (if (cdr (assoc 'heading org-blank-before-new-entry))
19844 (skip-chars-backward " \t\n\r")
19845 (unless (eobp)
19846 (forward-line -1)))
19847 (beginning-of-line 2)
19848 (goto-char (min (point) pos))
19849 (count-lines (point) pos)))
19851 (defun org-skip-whitespace ()
19852 (skip-chars-forward " \t\n\r"))
19854 (defun org-point-in-group (point group &optional context)
19855 "Check if POINT is in match-group GROUP.
19856 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19857 match. If the match group does not exist or point is not inside it,
19858 return nil."
19859 (and (match-beginning group)
19860 (>= point (match-beginning group))
19861 (<= point (match-end group))
19862 (if context
19863 (list context (match-beginning group) (match-end group))
19864 t)))
19866 (defun org-switch-to-buffer-other-window (&rest args)
19867 "Switch to buffer in a second window on the current frame.
19868 In particular, do not allow pop-up frames.
19869 Returns the newly created buffer."
19870 (let (pop-up-frames special-display-buffer-names special-display-regexps
19871 special-display-function)
19872 (apply 'switch-to-buffer-other-window args)))
19874 (defun org-combine-plists (&rest plists)
19875 "Create a single property list from all plists in PLISTS.
19876 The process starts by copying the first list, and then setting properties
19877 from the other lists. Settings in the last list are the most significant
19878 ones and overrule settings in the other lists."
19879 (let ((rtn (copy-sequence (pop plists)))
19880 p v ls)
19881 (while plists
19882 (setq ls (pop plists))
19883 (while ls
19884 (setq p (pop ls) v (pop ls))
19885 (setq rtn (plist-put rtn p v))))
19886 rtn))
19888 (defun org-move-line-down (arg)
19889 "Move the current line down. With prefix argument, move it past ARG lines."
19890 (interactive "p")
19891 (let ((col (current-column))
19892 beg end pos)
19893 (beginning-of-line 1) (setq beg (point))
19894 (beginning-of-line 2) (setq end (point))
19895 (beginning-of-line (+ 1 arg))
19896 (setq pos (move-marker (make-marker) (point)))
19897 (insert (delete-and-extract-region beg end))
19898 (goto-char pos)
19899 (org-move-to-column col)))
19901 (defun org-move-line-up (arg)
19902 "Move the current line up. With prefix argument, move it past ARG lines."
19903 (interactive "p")
19904 (let ((col (current-column))
19905 beg end pos)
19906 (beginning-of-line 1) (setq beg (point))
19907 (beginning-of-line 2) (setq end (point))
19908 (beginning-of-line (- arg))
19909 (setq pos (move-marker (make-marker) (point)))
19910 (insert (delete-and-extract-region beg end))
19911 (goto-char pos)
19912 (org-move-to-column col)))
19914 (defun org-replace-escapes (string table)
19915 "Replace %-escapes in STRING with values in TABLE.
19916 TABLE is an association list with keys like \"%a\" and string values.
19917 The sequences in STRING may contain normal field width and padding information,
19918 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19919 so values can contain further %-escapes if they are define later in TABLE."
19920 (let ((tbl (copy-alist table))
19921 (case-fold-search nil)
19922 (pchg 0)
19923 e re rpl)
19924 (while (setq e (pop tbl))
19925 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19926 (when (and (cdr e) (string-match re (cdr e)))
19927 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19928 (safe "SREF"))
19929 (add-text-properties 0 3 (list 'sref sref) safe)
19930 (setcdr e (replace-match safe t t (cdr e)))))
19931 (while (string-match re string)
19932 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19933 (cdr e)))
19934 (setq string (replace-match rpl t t string))))
19935 (while (setq pchg (next-property-change pchg string))
19936 (let ((sref (get-text-property pchg 'sref string)))
19937 (when (and sref (string-match "SREF" string pchg))
19938 (setq string (replace-match sref t t string)))))
19939 string))
19941 (defun org-sublist (list start end)
19942 "Return a section of LIST, from START to END.
19943 Counting starts at 1."
19944 (let (rtn (c start))
19945 (setq list (nthcdr (1- start) list))
19946 (while (and list (<= c end))
19947 (push (pop list) rtn)
19948 (setq c (1+ c)))
19949 (nreverse rtn)))
19951 (defun org-find-base-buffer-visiting (file)
19952 "Like `find-buffer-visiting' but always return the base buffer and
19953 not an indirect buffer."
19954 (let ((buf (or (get-file-buffer file)
19955 (find-buffer-visiting file))))
19956 (if buf
19957 (or (buffer-base-buffer buf) buf)
19958 nil)))
19960 (defun org-image-file-name-regexp (&optional extensions)
19961 "Return regexp matching the file names of images.
19962 If EXTENSIONS is given, only match these."
19963 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19964 (image-file-name-regexp)
19965 (let ((image-file-name-extensions
19966 (or extensions
19967 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19968 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19969 (concat "\\."
19970 (regexp-opt (nconc (mapcar 'upcase
19971 image-file-name-extensions)
19972 image-file-name-extensions)
19974 "\\'"))))
19976 (defun org-file-image-p (file &optional extensions)
19977 "Return non-nil if FILE is an image."
19978 (save-match-data
19979 (string-match (org-image-file-name-regexp extensions) file)))
19981 (defun org-get-cursor-date ()
19982 "Return the date at cursor in as a time.
19983 This works in the calendar and in the agenda, anywhere else it just
19984 returns the current time."
19985 (let (date day defd)
19986 (cond
19987 ((eq major-mode 'calendar-mode)
19988 (setq date (calendar-cursor-to-date)
19989 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19990 ((eq major-mode 'org-agenda-mode)
19991 (setq day (get-text-property (point) 'day))
19992 (if day
19993 (setq date (calendar-gregorian-from-absolute day)
19994 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19995 (nth 2 date))))))
19996 (or defd (current-time))))
19998 (defvar org-agenda-action-marker (make-marker)
19999 "Marker pointing to the entry for the next agenda action.")
20001 (defun org-mark-entry-for-agenda-action ()
20002 "Mark the current entry as target of an agenda action.
20003 Agenda actions are actions executed from the agenda with the key `k',
20004 which make use of the date at the cursor."
20005 (interactive)
20006 (move-marker org-agenda-action-marker
20007 (save-excursion (org-back-to-heading t) (point))
20008 (current-buffer))
20009 (message
20010 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20012 (defun org-mark-subtree ()
20013 "Mark the current subtree.
20014 This puts point at the start of the current subtree, and mark at the end.
20016 If point is in an inline task, mark that task instead."
20017 (interactive)
20018 (let ((inline-task-p
20019 (and (featurep 'org-inlinetask)
20020 (org-inlinetask-in-task-p)))
20021 (beg))
20022 ;; Get beginning of subtree
20023 (cond
20024 (inline-task-p (org-inlinetask-goto-beginning))
20025 ((org-at-heading-p) (beginning-of-line))
20026 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20027 (setq beg (point))
20028 ;; Get end of it
20029 (if inline-task-p
20030 (org-inlinetask-goto-end)
20031 (org-end-of-subtree))
20032 ;; Mark zone
20033 (push-mark (point) nil t)
20034 (goto-char beg)))
20036 ;;; Paragraph filling stuff.
20037 ;; We want this to be just right, so use the full arsenal.
20039 (defun org-indent-line-function ()
20040 "Indent line depending on context."
20041 (interactive)
20042 (let* ((pos (point))
20043 (itemp (org-at-item-p))
20044 (case-fold-search t)
20045 (org-drawer-regexp (or org-drawer-regexp "\000"))
20046 (inline-task-p (and (featurep 'org-inlinetask)
20047 (org-inlinetask-in-task-p)))
20048 (inline-re (and inline-task-p
20049 (org-inlinetask-outline-regexp)))
20050 column)
20051 (beginning-of-line 1)
20052 (cond
20053 ;; Comments
20054 ((looking-at "# ") (setq column 0))
20055 ;; Headings
20056 ((looking-at org-outline-regexp) (setq column 0))
20057 ;; Included files
20058 ((looking-at "#\\+include:") (setq column 0))
20059 ;; Footnote definition
20060 ((looking-at org-footnote-definition-re) (setq column 0))
20061 ;; Literal examples
20062 ((looking-at "[ \t]*:\\( \\|$\\)")
20063 (setq column (org-get-indentation))) ; do nothing
20064 ;; Lists
20065 ((ignore-errors (goto-char (org-in-item-p)))
20066 (setq column (if itemp
20067 (org-get-indentation)
20068 (org-list-item-body-column (point))))
20069 (goto-char pos))
20070 ;; Drawers
20071 ((and (looking-at "[ \t]*:END:")
20072 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20073 (save-excursion
20074 (goto-char (1- (match-beginning 1)))
20075 (setq column (current-column))))
20076 ;; Special blocks
20077 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20078 (save-excursion
20079 (re-search-backward
20080 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20081 (setq column (org-get-indentation (match-string 0))))
20082 ((and (not (looking-at "[ \t]*#\\+begin_"))
20083 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20084 (save-excursion
20085 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20086 (setq column
20087 (cond ((equal (downcase (match-string 1)) "src")
20088 ;; src blocks: let `org-edit-src-exit' handle them
20089 (org-get-indentation))
20090 ((equal (downcase (match-string 1)) "example")
20091 (max (org-get-indentation)
20092 (org-get-indentation (match-string 0))))
20094 (org-get-indentation (match-string 0))))))
20095 ;; This line has nothing special, look at the previous relevant
20096 ;; line to compute indentation
20098 (beginning-of-line 0)
20099 (while (and (not (bobp))
20100 (not (looking-at org-drawer-regexp))
20101 ;; When point started in an inline task, do not move
20102 ;; above task starting line.
20103 (not (and inline-task-p (looking-at inline-re)))
20104 ;; Skip drawers, blocks, empty lines, verbatim,
20105 ;; comments, tables, footnotes definitions, lists,
20106 ;; inline tasks.
20107 (or (and (looking-at "[ \t]*:END:")
20108 (re-search-backward org-drawer-regexp nil t))
20109 (and (looking-at "[ \t]*#\\+end_")
20110 (re-search-backward "[ \t]*#\\+begin_"nil t))
20111 (looking-at "[ \t]*[\n:#|]")
20112 (looking-at org-footnote-definition-re)
20113 (and (ignore-errors (goto-char (org-in-item-p)))
20114 (goto-char
20115 (org-list-get-top-point (org-list-struct))))
20116 (and (not inline-task-p)
20117 (featurep 'org-inlinetask)
20118 (org-inlinetask-in-task-p)
20119 (or (org-inlinetask-goto-beginning) t))))
20120 (beginning-of-line 0))
20121 (cond
20122 ;; There was an heading above.
20123 ((looking-at "\\*+[ \t]+")
20124 (if (not org-adapt-indentation)
20125 (setq column 0)
20126 (goto-char (match-end 0))
20127 (setq column (current-column))))
20128 ;; A drawer had started and is unfinished
20129 ((looking-at org-drawer-regexp)
20130 (goto-char (1- (match-beginning 1)))
20131 (setq column (current-column)))
20132 ;; Else, nothing noticeable found: get indentation and go on.
20133 (t (setq column (org-get-indentation))))))
20134 ;; Now apply indentation and move cursor accordingly
20135 (goto-char pos)
20136 (if (<= (current-column) (current-indentation))
20137 (org-indent-line-to column)
20138 (save-excursion (org-indent-line-to column)))
20139 ;; Special polishing for properties, see `org-property-format'
20140 (setq column (current-column))
20141 (beginning-of-line 1)
20142 (if (looking-at
20143 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20144 (replace-match (concat (match-string 1)
20145 (format org-property-format
20146 (match-string 2) (match-string 3)))
20147 t t))
20148 (org-move-to-column column)))
20150 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20151 "Variable to store copy of `adaptive-fill-regexp'.
20152 Since `adaptive-fill-regexp' is set to never match, we need to
20153 store a backup of its value before entering `org-mode' so that
20154 the functionality can be provided as a fall-back.")
20156 (defun org-set-autofill-regexps ()
20157 (interactive)
20158 ;; In the paragraph separator we include headlines, because filling
20159 ;; text in a line directly attached to a headline would otherwise
20160 ;; fill the headline as well.
20161 (org-set-local 'comment-start-skip "^#+[ \t]*")
20162 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20163 ;; The paragraph starter includes hand-formatted lists.
20164 (org-set-local
20165 'paragraph-start
20166 (concat
20167 "\f" "\\|"
20168 "[ ]*$" "\\|"
20169 org-outline-regexp "\\|"
20170 "[ \t]*#" "\\|"
20171 (org-item-re) "\\|"
20172 "[ \t]*[:|]" "\\|"
20173 "\\$\\$" "\\|"
20174 "\\\\\\(begin\\|end\\|[][]\\)"))
20175 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20176 ;; But only if the user has not turned off tables or fixed-width regions
20177 (org-set-local
20178 'auto-fill-inhibit-regexp
20179 (concat org-outline-regexp
20180 "\\|#\\+"
20181 "\\|[ \t]*" org-keyword-time-regexp
20182 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20183 (concat
20184 "\\|[ \t]*["
20185 (if org-enable-table-editor "|" "")
20186 (if org-enable-fixed-width-editor ":" "")
20187 "]"))))
20188 ;; We use our own fill-paragraph function, to make sure that tables
20189 ;; and fixed-width regions are not wrapped. That function will pass
20190 ;; through to `fill-paragraph' when appropriate.
20191 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20192 ;; Prevent auto-fill from inserting unwanted new items.
20193 (if (boundp 'fill-nobreak-predicate)
20194 (org-set-local 'fill-nobreak-predicate
20195 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20196 fill-nobreak-predicate
20197 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20198 ;; Adaptive filling: To get full control, first make sure that
20199 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20200 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20201 (org-set-local 'org-adaptive-fill-regexp-backup
20202 adaptive-fill-regexp))
20203 (org-set-local 'adaptive-fill-regexp "\000")
20204 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20205 (org-set-local 'adaptive-fill-function
20206 'org-adaptive-fill-function)
20207 (org-set-local
20208 'align-mode-rules-list
20209 '((org-in-buffer-settings
20210 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20211 (modes . '(org-mode))))))
20213 (defun org-fill-item-nobreak-p ()
20214 "Non-nil when a line break at point would insert a new item."
20215 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20217 (defun org-fill-paragraph (&optional justify)
20218 "Re-align a table, pass through to fill-paragraph if no table."
20219 (let ((table-p (org-at-table-p))
20220 (table.el-p (org-at-table.el-p))
20221 (itemp (org-in-item-p)))
20222 (cond ((and (equal (char-after (point-at-bol)) ?*)
20223 (save-excursion (goto-char (point-at-bol))
20224 (looking-at org-outline-regexp)))
20225 t) ; skip headlines
20226 (table.el-p t) ; skip table.el tables
20227 (table-p (org-table-align) t) ; align Org tables
20228 (itemp ; align text in items
20229 (let* ((struct (save-excursion (goto-char itemp)
20230 (org-list-struct)))
20231 (parents (org-list-parents-alist struct))
20232 (children (org-list-get-children itemp struct parents))
20233 beg end prev next prefix)
20234 ;; Determine in which part of item point is: before
20235 ;; first child, after last child, between two
20236 ;; sub-lists, or simply in item if there's no child.
20237 (cond
20238 ((not children)
20239 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20240 beg itemp
20241 end (org-list-get-item-end itemp struct)))
20242 ((< (point) (setq next (car children)))
20243 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20244 beg itemp
20245 end next))
20246 ((> (point) (setq prev (car (last children))))
20247 (setq beg (org-list-get-item-end prev struct)
20248 end (org-list-get-item-end itemp struct)
20249 prefix (save-excursion
20250 (goto-char beg)
20251 (skip-chars-forward " \t")
20252 (make-string (current-column) ?\ ))))
20253 (t (catch 'exit
20254 (while (setq next (pop children))
20255 (if (> (point) next)
20256 (setq prev next)
20257 (setq beg (org-list-get-item-end prev struct)
20258 end next
20259 prefix (save-excursion
20260 (goto-char beg)
20261 (skip-chars-forward " \t")
20262 (make-string (current-column) ?\ )))
20263 (throw 'exit nil))))))
20264 ;; Use `fill-paragraph' with buffer narrowed to item
20265 ;; without any child, and with our computed PREFIX.
20266 (flet ((fill-context-prefix (from to &optional flr) prefix))
20267 (save-restriction
20268 (narrow-to-region beg end)
20269 (save-excursion (fill-paragraph justify)))) t))
20270 ;; Special case where point is not in a list but is on
20271 ;; a paragraph adjacent to a list: make sure this paragraph
20272 ;; doesn't get merged with the end of the list by narrowing
20273 ;; buffer first.
20274 ((save-excursion (forward-paragraph -1)
20275 (setq itemp (org-in-item-p)))
20276 (let ((struct (save-excursion (goto-char itemp)
20277 (org-list-struct))))
20278 (save-restriction
20279 (narrow-to-region (org-list-get-bottom-point struct)
20280 (save-excursion (forward-paragraph 1)
20281 (point)))
20282 (fill-paragraph justify) t)))
20283 ;; Else simply call `fill-paragraph'.
20284 (t nil))))
20286 ;; For reference, this is the default value of adaptive-fill-regexp
20287 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20289 (defun org-adaptive-fill-function ()
20290 "Return a fill prefix for org-mode files."
20291 (let (itemp)
20292 (save-excursion
20293 (cond
20294 ;; Comment line
20295 ((looking-at "#[ \t]+")
20296 (match-string-no-properties 0))
20297 ;; Plain list item
20298 ((org-at-item-p)
20299 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20300 ;; Point is in a list after `backward-paragraph': original
20301 ;; point wasn't in the list, or filling would have been taken
20302 ;; care of by `org-auto-fill-function', but the list and the
20303 ;; real paragraph are not separated by a blank line. Thus, move
20304 ;; point after the list to go back to real paragraph and
20305 ;; determine fill-prefix.
20306 ((setq itemp (org-in-item-p))
20307 (goto-char itemp)
20308 (let* ((struct (org-list-struct))
20309 (bottom (org-list-get-bottom-point struct)))
20310 (goto-char bottom)
20311 (make-string (org-get-indentation) ?\ )))
20312 ;; Other text
20313 ((looking-at org-adaptive-fill-regexp-backup)
20314 (match-string-no-properties 0))))))
20316 (defun org-auto-fill-function ()
20317 "Auto-fill function."
20318 (let (itemp prefix)
20319 ;; When in a list, compute an appropriate fill-prefix and make
20320 ;; sure it will be used by `do-auto-fill'.
20321 (if (setq itemp (org-in-item-p))
20322 (progn
20323 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20324 (flet ((fill-context-prefix (from to &optional flr) prefix))
20325 (do-auto-fill)))
20326 ;; Else just use `do-auto-fill'.
20327 (do-auto-fill))))
20329 ;;; Other stuff.
20331 (defun org-toggle-fixed-width-section (arg)
20332 "Toggle the fixed-width export.
20333 If there is no active region, the QUOTE keyword at the current headline is
20334 inserted or removed. When present, it causes the text between this headline
20335 and the next to be exported as fixed-width text, and unmodified.
20336 If there is an active region, this command adds or removes a colon as the
20337 first character of this line. If the first character of a line is a colon,
20338 this line is also exported in fixed-width font."
20339 (interactive "P")
20340 (let* ((cc 0)
20341 (regionp (org-region-active-p))
20342 (beg (if regionp (region-beginning) (point)))
20343 (end (if regionp (region-end)))
20344 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20345 (case-fold-search nil)
20346 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20347 off)
20348 (if regionp
20349 (save-excursion
20350 (goto-char beg)
20351 (setq cc (current-column))
20352 (beginning-of-line 1)
20353 (setq off (looking-at re))
20354 (while (> nlines 0)
20355 (setq nlines (1- nlines))
20356 (beginning-of-line 1)
20357 (cond
20358 (arg
20359 (org-move-to-column cc t)
20360 (insert ": \n")
20361 (forward-line -1))
20362 ((and off (looking-at re))
20363 (replace-match "" t t nil 1))
20364 ((not off) (org-move-to-column cc t) (insert ": ")))
20365 (forward-line 1)))
20366 (save-excursion
20367 (org-back-to-heading)
20368 (cond
20369 ((looking-at (format org-heading-keyword-regexp-format
20370 org-quote-string))
20371 (goto-char (match-end 1))
20372 (looking-at (concat " +" org-quote-string))
20373 (replace-match "" t t)
20374 (when (eolp) (insert " ")))
20375 ((looking-at org-outline-regexp)
20376 (goto-char (match-end 0))
20377 (insert org-quote-string " ")))))))
20379 (defun org-reftex-citation ()
20380 "Use reftex-citation to insert a citation into the buffer.
20381 This looks for a line like
20383 #+BIBLIOGRAPHY: foo plain option:-d
20385 and derives from it that foo.bib is the bibliography file relevant
20386 for this document. It then installs the necessary environment for RefTeX
20387 to work in this buffer and calls `reftex-citation' to insert a citation
20388 into the buffer.
20390 Export of such citations to both LaTeX and HTML is handled by the contributed
20391 package org-exp-bibtex by Taru Karttunen."
20392 (interactive)
20393 (let ((reftex-docstruct-symbol 'rds)
20394 (reftex-cite-format "\\cite{%l}")
20395 rds bib)
20396 (save-excursion
20397 (save-restriction
20398 (widen)
20399 (let ((case-fold-search t)
20400 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20401 (if (not (save-excursion
20402 (or (re-search-forward re nil t)
20403 (re-search-backward re nil t))))
20404 (error "No bibliography defined in file")
20405 (setq bib (concat (match-string 1) ".bib")
20406 rds (list (list 'bib bib)))))))
20407 (call-interactively 'reftex-citation)))
20409 ;;;; Functions extending outline functionality
20411 (defun org-beginning-of-line (&optional arg)
20412 "Go to the beginning of the current line. If that is invisible, continue
20413 to a visible line beginning. This makes the function of C-a more intuitive.
20414 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20415 first attempt, and only move to after the tags when the cursor is already
20416 beyond the end of the headline."
20417 (interactive "P")
20418 (let ((pos (point))
20419 (special (if (consp org-special-ctrl-a/e)
20420 (car org-special-ctrl-a/e)
20421 org-special-ctrl-a/e))
20422 refpos)
20423 (if (org-bound-and-true-p line-move-visual)
20424 (beginning-of-visual-line 1)
20425 (beginning-of-line 1))
20426 (if (and arg (fboundp 'move-beginning-of-line))
20427 (call-interactively 'move-beginning-of-line)
20428 (if (bobp)
20430 (backward-char 1)
20431 (if (org-truely-invisible-p)
20432 (while (and (not (bobp)) (org-truely-invisible-p))
20433 (backward-char 1)
20434 (beginning-of-line 1))
20435 (forward-char 1))))
20436 (when special
20437 (cond
20438 ((and (looking-at org-complex-heading-regexp)
20439 (= (char-after (match-end 1)) ?\ ))
20440 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20441 (point-at-eol)))
20442 (goto-char
20443 (if (eq special t)
20444 (cond ((> pos refpos) refpos)
20445 ((= pos (point)) refpos)
20446 (t (point)))
20447 (cond ((> pos (point)) (point))
20448 ((not (eq last-command this-command)) (point))
20449 (t refpos)))))
20450 ((org-at-item-p)
20451 ;; Being at an item and not looking at an the item means point
20452 ;; was previously moved to beginning of a visual line, whiche
20453 ;; doesn't contain the item. Therefore, do nothing special,
20454 ;; just stay here.
20455 (when (looking-at org-list-full-item-re)
20456 ;; Set special position at first white space character after
20457 ;; bullet, and check-box, if any.
20458 (let ((after-bullet
20459 (let ((box (match-end 3)))
20460 (if (not box) (match-end 1)
20461 (let ((after (char-after box)))
20462 (if (and after (= after ? )) (1+ box) box))))))
20463 ;; Special case: Move point to special position when
20464 ;; currently after it or at beginning of line.
20465 (if (eq special t)
20466 (when (or (> pos after-bullet) (= (point) pos))
20467 (goto-char after-bullet))
20468 ;; Reversed case: Move point to special position when
20469 ;; point was already at beginning of line and command is
20470 ;; repeated.
20471 (when (and (= (point) pos) (eq last-command this-command))
20472 (goto-char after-bullet))))))))
20473 (org-no-warnings
20474 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20476 (defun org-end-of-line (&optional arg)
20477 "Go to the end of the line.
20478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20479 first attempt, and only move to after the tags when the cursor is already
20480 beyond the end of the headline."
20481 (interactive "P")
20482 (let ((special (if (consp org-special-ctrl-a/e)
20483 (cdr org-special-ctrl-a/e)
20484 org-special-ctrl-a/e)))
20485 (cond
20486 ((or (not special) arg
20487 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20488 (call-interactively
20489 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20490 ((fboundp 'move-end-of-line) 'move-end-of-line)
20491 (t 'end-of-line))))
20492 ((org-at-heading-p)
20493 (let ((pos (point)))
20494 (beginning-of-line 1)
20495 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20496 (if (eq special t)
20497 (if (or (< pos (match-beginning 1))
20498 (= pos (match-end 0)))
20499 (goto-char (match-beginning 1))
20500 (goto-char (match-end 0)))
20501 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20502 (goto-char (match-end 0))
20503 (goto-char (match-beginning 1))))
20504 (call-interactively (if (fboundp 'move-end-of-line)
20505 'move-end-of-line
20506 'end-of-line)))))
20507 ((org-at-drawer-p)
20508 (move-end-of-line 1)
20509 (when (overlays-at (1- (point))) (backward-char 1)))
20510 ;; At an item: Move before any hidden text.
20511 (t (call-interactively
20512 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20513 ((fboundp 'move-end-of-line) 'move-end-of-line)
20514 (t 'end-of-line)))))
20515 (org-no-warnings
20516 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20518 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20519 (define-key org-mode-map "\C-e" 'org-end-of-line)
20521 (defun org-backward-sentence (&optional arg)
20522 "Go to beginning of sentence, or beginning of table field.
20523 This will call `backward-sentence' or `org-table-beginning-of-field',
20524 depending on context."
20525 (interactive "P")
20526 (cond
20527 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20528 (t (call-interactively 'backward-sentence))))
20530 (defun org-forward-sentence (&optional arg)
20531 "Go to end of sentence, or end of table field.
20532 This will call `forward-sentence' or `org-table-end-of-field',
20533 depending on context."
20534 (interactive "P")
20535 (cond
20536 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20537 (t (call-interactively 'forward-sentence))))
20539 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20540 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20542 (defun org-kill-line (&optional arg)
20543 "Kill line, to tags or end of line."
20544 (interactive "P")
20545 (cond
20546 ((or (not org-special-ctrl-k)
20547 (bolp)
20548 (not (org-at-heading-p)))
20549 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20550 org-ctrl-k-protect-subtree)
20551 (if (or (eq org-ctrl-k-protect-subtree 'error)
20552 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20553 (error "C-k aborted - would kill hidden subtree")))
20554 (call-interactively 'kill-line))
20555 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20556 (kill-region (point) (match-beginning 1))
20557 (org-set-tags nil t))
20558 (t (kill-region (point) (point-at-eol)))))
20560 (define-key org-mode-map "\C-k" 'org-kill-line)
20562 (defun org-yank (&optional arg)
20563 "Yank. If the kill is a subtree, treat it specially.
20564 This command will look at the current kill and check if is a single
20565 subtree, or a series of subtrees[1]. If it passes the test, and if the
20566 cursor is at the beginning of a line or after the stars of a currently
20567 empty headline, then the yank is handled specially. How exactly depends
20568 on the value of the following variables, both set by default.
20570 org-yank-folded-subtrees
20571 When set, the subtree(s) will be folded after insertion, but only
20572 if doing so would now swallow text after the yanked text.
20574 org-yank-adjusted-subtrees
20575 When set, the subtree will be promoted or demoted in order to
20576 fit into the local outline tree structure, which means that the level
20577 will be adjusted so that it becomes the smaller one of the two
20578 *visible* surrounding headings.
20580 Any prefix to this command will cause `yank' to be called directly with
20581 no special treatment. In particular, a simple \\[universal-argument] prefix \
20582 will just
20583 plainly yank the text as it is.
20585 \[1] The test checks if the first non-white line is a heading
20586 and if there are no other headings with fewer stars."
20587 (interactive "P")
20588 (org-yank-generic 'yank arg))
20590 (defun org-yank-generic (command arg)
20591 "Perform some yank-like command.
20593 This function implements the behavior described in the `org-yank'
20594 documentation. However, it has been generalized to work for any
20595 interactive command with similar behavior."
20597 ;; pretend to be command COMMAND
20598 (setq this-command command)
20600 (if arg
20601 (call-interactively command)
20603 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20604 (and (org-kill-is-subtree-p)
20605 (or (bolp)
20606 (and (looking-at "[ \t]*$")
20607 (string-match
20608 "\\`\\*+\\'"
20609 (buffer-substring (point-at-bol) (point)))))))
20610 swallowp)
20611 (cond
20612 ((and subtreep org-yank-folded-subtrees)
20613 (let ((beg (point))
20614 end)
20615 (if (and subtreep org-yank-adjusted-subtrees)
20616 (org-paste-subtree nil nil 'for-yank)
20617 (call-interactively command))
20619 (setq end (point))
20620 (goto-char beg)
20621 (when (and (bolp) subtreep
20622 (not (setq swallowp
20623 (org-yank-folding-would-swallow-text beg end))))
20624 (org-with-limited-levels
20625 (or (looking-at org-outline-regexp)
20626 (re-search-forward org-outline-regexp-bol end t))
20627 (while (and (< (point) end) (looking-at org-outline-regexp))
20628 (hide-subtree)
20629 (org-cycle-show-empty-lines 'folded)
20630 (condition-case nil
20631 (outline-forward-same-level 1)
20632 (error (goto-char end))))))
20633 (when swallowp
20634 (message
20635 "Inserted text not folded because that would swallow text"))
20637 (goto-char end)
20638 (skip-chars-forward " \t\n\r")
20639 (beginning-of-line 1)
20640 (push-mark beg 'nomsg)))
20641 ((and subtreep org-yank-adjusted-subtrees)
20642 (let ((beg (point-at-bol)))
20643 (org-paste-subtree nil nil 'for-yank)
20644 (push-mark beg 'nomsg)))
20646 (call-interactively command))))))
20648 (defun org-yank-folding-would-swallow-text (beg end)
20649 "Would hide-subtree at BEG swallow any text after END?"
20650 (let (level)
20651 (org-with-limited-levels
20652 (save-excursion
20653 (goto-char beg)
20654 (when (or (looking-at org-outline-regexp)
20655 (re-search-forward org-outline-regexp-bol end t))
20656 (setq level (org-outline-level)))
20657 (goto-char end)
20658 (skip-chars-forward " \t\r\n\v\f")
20659 (if (or (eobp)
20660 (and (bolp) (looking-at org-outline-regexp)
20661 (<= (org-outline-level) level)))
20662 nil ; Nothing would be swallowed
20663 t))))) ; something would swallow
20665 (define-key org-mode-map "\C-y" 'org-yank)
20667 (defun org-truely-invisible-p ()
20668 "Check if point is at a character currently not visible.
20669 This version does not only check the character property, but also
20670 `visible-mode'."
20671 ;; Early versions of noutline don't have `outline-invisible-p'.
20672 (if (org-bound-and-true-p visible-mode)
20674 (outline-invisible-p)))
20676 (defun org-invisible-p2 ()
20677 "Check if point is at a character currently not visible."
20678 (save-excursion
20679 (if (and (eolp) (not (bobp))) (backward-char 1))
20680 ;; Early versions of noutline don't have `outline-invisible-p'.
20681 (outline-invisible-p)))
20683 (defun org-back-to-heading (&optional invisible-ok)
20684 "Call `outline-back-to-heading', but provide a better error message."
20685 (condition-case nil
20686 (outline-back-to-heading invisible-ok)
20687 (error (error "Before first headline at position %d in buffer %s"
20688 (point) (current-buffer)))))
20690 (defun org-beginning-of-defun ()
20691 "Go to the beginning of the subtree, i.e. back to the heading."
20692 (org-back-to-heading))
20693 (defun org-end-of-defun ()
20694 "Go to the end of the subtree."
20695 (org-end-of-subtree nil t))
20697 (defun org-before-first-heading-p ()
20698 "Before first heading?"
20699 (save-excursion
20700 (end-of-line)
20701 (null (re-search-backward org-outline-regexp-bol nil t))))
20703 (defun org-at-heading-p (&optional ignored)
20704 (outline-on-heading-p t))
20705 ;; Compatibility alias with Org versions < 7.8.03
20706 (defalias 'org-on-heading-p 'org-at-heading-p)
20708 (defun org-at-drawer-p nil
20709 "Whether point is at a drawer."
20710 (save-excursion
20711 (move-beginning-of-line 1)
20712 (looking-at org-drawer-regexp)))
20714 (defun org-point-at-end-of-empty-headline ()
20715 "If point is at the end of an empty headline, return t, else nil.
20716 If the heading only contains a TODO keyword, it is still still considered
20717 empty."
20718 (and (looking-at "[ \t]*$")
20719 (save-excursion
20720 (beginning-of-line 1)
20721 (let ((case-fold-search nil))
20722 (looking-at org-todo-line-regexp)))
20723 (string= (match-string 3) "")))
20725 (defun org-at-heading-or-item-p ()
20726 (or (org-at-heading-p) (org-at-item-p)))
20728 (defun org-at-target-p ()
20729 (or (org-in-regexp org-radio-target-regexp)
20730 (org-in-regexp org-target-regexp)))
20731 ;; Compatibility alias with Org versions < 7.8.03
20732 (defalias 'org-on-target-p 'org-at-target-p)
20734 (defun org-up-heading-all (arg)
20735 "Move to the heading line of which the present line is a subheading.
20736 This function considers both visible and invisible heading lines.
20737 With argument, move up ARG levels."
20738 (if (fboundp 'outline-up-heading-all)
20739 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20740 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20742 (defun org-up-heading-safe ()
20743 "Move to the heading line of which the present line is a subheading.
20744 This version will not throw an error. It will return the level of the
20745 headline found, or nil if no higher level is found.
20747 Also, this function will be a lot faster than `outline-up-heading',
20748 because it relies on stars being the outline starters. This can really
20749 make a significant difference in outlines with very many siblings."
20750 (let (start-level re)
20751 (org-back-to-heading t)
20752 (setq start-level (funcall outline-level))
20753 (if (equal start-level 1)
20755 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20756 (if (re-search-backward re nil t)
20757 (funcall outline-level)))))
20759 (defun org-first-sibling-p ()
20760 "Is this heading the first child of its parents?"
20761 (interactive)
20762 (let ((re org-outline-regexp-bol)
20763 level l)
20764 (unless (org-at-heading-p t)
20765 (error "Not at a heading"))
20766 (setq level (funcall outline-level))
20767 (save-excursion
20768 (if (not (re-search-backward re nil t))
20770 (setq l (funcall outline-level))
20771 (< l level)))))
20773 (defun org-goto-sibling (&optional previous)
20774 "Goto the next sibling, even if it is invisible.
20775 When PREVIOUS is set, go to the previous sibling instead. Returns t
20776 when a sibling was found. When none is found, return nil and don't
20777 move point."
20778 (let ((fun (if previous 're-search-backward 're-search-forward))
20779 (pos (point))
20780 (re org-outline-regexp-bol)
20781 level l)
20782 (when (condition-case nil (org-back-to-heading t) (error nil))
20783 (setq level (funcall outline-level))
20784 (catch 'exit
20785 (or previous (forward-char 1))
20786 (while (funcall fun re nil t)
20787 (setq l (funcall outline-level))
20788 (when (< l level) (goto-char pos) (throw 'exit nil))
20789 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20790 (goto-char pos)
20791 nil))))
20793 (defun org-show-siblings ()
20794 "Show all siblings of the current headline."
20795 (save-excursion
20796 (while (org-goto-sibling) (org-flag-heading nil)))
20797 (save-excursion
20798 (while (org-goto-sibling 'previous)
20799 (org-flag-heading nil))))
20801 (defun org-goto-first-child ()
20802 "Goto the first child, even if it is invisible.
20803 Return t when a child was found. Otherwise don't move point and
20804 return nil."
20805 (let (level (pos (point)) (re org-outline-regexp-bol))
20806 (when (condition-case nil (org-back-to-heading t) (error nil))
20807 (setq level (outline-level))
20808 (forward-char 1)
20809 (if (and (re-search-forward re nil t) (> (outline-level) level))
20810 (progn (goto-char (match-beginning 0)) t)
20811 (goto-char pos) nil))))
20813 (defun org-show-hidden-entry ()
20814 "Show an entry where even the heading is hidden."
20815 (save-excursion
20816 (org-show-entry)))
20818 (defun org-flag-heading (flag &optional entry)
20819 "Flag the current heading. FLAG non-nil means make invisible.
20820 When ENTRY is non-nil, show the entire entry."
20821 (save-excursion
20822 (org-back-to-heading t)
20823 ;; Check if we should show the entire entry
20824 (if entry
20825 (progn
20826 (org-show-entry)
20827 (save-excursion
20828 (and (outline-next-heading)
20829 (org-flag-heading nil))))
20830 (outline-flag-region (max (point-min) (1- (point)))
20831 (save-excursion (outline-end-of-heading) (point))
20832 flag))))
20834 (defun org-get-next-sibling ()
20835 "Move to next heading of the same level, and return point.
20836 If there is no such heading, return nil.
20837 This is like outline-next-sibling, but invisible headings are ok."
20838 (let ((level (funcall outline-level)))
20839 (outline-next-heading)
20840 (while (and (not (eobp)) (> (funcall outline-level) level))
20841 (outline-next-heading))
20842 (if (or (eobp) (< (funcall outline-level) level))
20844 (point))))
20846 (defun org-get-last-sibling ()
20847 "Move to previous heading of the same level, and return point.
20848 If there is no such heading, return nil."
20849 (let ((opoint (point))
20850 (level (funcall outline-level)))
20851 (outline-previous-heading)
20852 (when (and (/= (point) opoint) (outline-on-heading-p t))
20853 (while (and (> (funcall outline-level) level)
20854 (not (bobp)))
20855 (outline-previous-heading))
20856 (if (< (funcall outline-level) level)
20858 (point)))))
20860 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20861 ;; This contains an exact copy of the original function, but it uses
20862 ;; `org-back-to-heading', to make it work also in invisible
20863 ;; trees. And is uses an invisible-OK argument.
20864 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20865 ;; Furthermore, when used inside Org, finding the end of a large subtree
20866 ;; with many children and grandchildren etc, this can be much faster
20867 ;; than the outline version.
20868 (org-back-to-heading invisible-OK)
20869 (let ((first t)
20870 (level (funcall outline-level)))
20871 (if (and (eq major-mode 'org-mode) (< level 1000))
20872 ;; A true heading (not a plain list item), in Org-mode
20873 ;; This means we can easily find the end by looking
20874 ;; only for the right number of stars. Using a regexp to do
20875 ;; this is so much faster than using a Lisp loop.
20876 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20877 (forward-char 1)
20878 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20879 ;; something else, do it the slow way
20880 (while (and (not (eobp))
20881 (or first (> (funcall outline-level) level)))
20882 (setq first nil)
20883 (outline-next-heading)))
20884 (unless to-heading
20885 (if (memq (preceding-char) '(?\n ?\^M))
20886 (progn
20887 ;; Go to end of line before heading
20888 (forward-char -1)
20889 (if (memq (preceding-char) '(?\n ?\^M))
20890 ;; leave blank line before heading
20891 (forward-char -1))))))
20892 (point))
20894 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20895 "Use Org version in org-mode, for dramatic speed-up."
20896 (if (eq major-mode 'org-mode)
20897 (progn
20898 (org-end-of-subtree nil t)
20899 (unless (eobp) (backward-char 1)))
20900 ad-do-it))
20902 (defun org-end-of-meta-data-and-drawers ()
20903 "Jump to the first text after meta data and drawers in the current entry.
20904 This will move over empty lines, lines with planning time stamps,
20905 clocking lines, and drawers."
20906 (org-back-to-heading t)
20907 (let ((end (save-excursion (outline-next-heading) (point)))
20908 (re (concat "\\(" org-drawer-regexp "\\)"
20909 "\\|" "[ \t]*" org-keyword-time-regexp)))
20910 (forward-line 1)
20911 (while (re-search-forward re end t)
20912 (if (not (match-end 1))
20913 ;; empty or planning line
20914 (forward-line 1)
20915 ;; a drawer, find the end
20916 (re-search-forward "^[ \t]*:END:" end 'move)
20917 (forward-line 1)))
20918 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20919 (point)))
20921 (defun org-forward-same-level (arg &optional invisible-ok)
20922 "Move forward to the arg'th subheading at same level as this one.
20923 Stop at the first and last subheadings of a superior heading.
20924 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20925 it wil also look at invisible ones."
20926 (interactive "p")
20927 (org-back-to-heading invisible-ok)
20928 (org-at-heading-p)
20929 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20930 (re (format "^\\*\\{1,%d\\} " level))
20932 (forward-char 1)
20933 (while (> arg 0)
20934 (while (and (re-search-forward re nil 'move)
20935 (setq l (- (match-end 0) (match-beginning 0) 1))
20936 (= l level)
20937 (not invisible-ok)
20938 (progn (backward-char 1) (outline-invisible-p)))
20939 (if (< l level) (setq arg 1)))
20940 (setq arg (1- arg)))
20941 (beginning-of-line 1)))
20943 (defun org-backward-same-level (arg &optional invisible-ok)
20944 "Move backward to the arg'th subheading at same level as this one.
20945 Stop at the first and last subheadings of a superior heading."
20946 (interactive "p")
20947 (org-back-to-heading)
20948 (org-at-heading-p)
20949 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20950 (re (format "^\\*\\{1,%d\\} " level))
20952 (while (> arg 0)
20953 (while (and (re-search-backward re nil 'move)
20954 (setq l (- (match-end 0) (match-beginning 0) 1))
20955 (= l level)
20956 (not invisible-ok)
20957 (outline-invisible-p))
20958 (if (< l level) (setq arg 1)))
20959 (setq arg (1- arg)))))
20961 (defun org-show-subtree ()
20962 "Show everything after this heading at deeper levels."
20963 (outline-flag-region
20964 (point)
20965 (save-excursion
20966 (org-end-of-subtree t t))
20967 nil))
20969 (defun org-show-entry ()
20970 "Show the body directly following this heading.
20971 Show the heading too, if it is currently invisible."
20972 (interactive)
20973 (save-excursion
20974 (condition-case nil
20975 (progn
20976 (org-back-to-heading t)
20977 (outline-flag-region
20978 (max (point-min) (1- (point)))
20979 (save-excursion
20980 (if (re-search-forward
20981 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20982 (match-beginning 1)
20983 (point-max)))
20984 nil)
20985 (org-cycle-hide-drawers 'children))
20986 (error nil))))
20988 (defun org-make-options-regexp (kwds &optional extra)
20989 "Make a regular expression for keyword lines."
20990 (concat
20992 "#?[ \t]*\\+\\("
20993 (mapconcat 'regexp-quote kwds "\\|")
20994 (if extra (concat "\\|" extra))
20995 "\\):[ \t]*"
20996 "\\(.*\\)"))
20998 ;; Make isearch reveal the necessary context
20999 (defun org-isearch-end ()
21000 "Reveal context after isearch exits."
21001 (when isearch-success ; only if search was successful
21002 (if (featurep 'xemacs)
21003 ;; Under XEmacs, the hook is run in the correct place,
21004 ;; we directly show the context.
21005 (org-show-context 'isearch)
21006 ;; In Emacs the hook runs *before* restoring the overlays.
21007 ;; So we have to use a one-time post-command-hook to do this.
21008 ;; (Emacs 22 has a special variable, see function `org-mode')
21009 (unless (and (boundp 'isearch-mode-end-hook-quit)
21010 isearch-mode-end-hook-quit)
21011 ;; Only when the isearch was not quitted.
21012 (org-add-hook 'post-command-hook 'org-isearch-post-command
21013 'append 'local)))))
21015 (defun org-isearch-post-command ()
21016 "Remove self from hook, and show context."
21017 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21018 (org-show-context 'isearch))
21021 ;;;; Integration with and fixes for other packages
21023 ;;; Imenu support
21025 (defvar org-imenu-markers nil
21026 "All markers currently used by Imenu.")
21027 (make-variable-buffer-local 'org-imenu-markers)
21029 (defun org-imenu-new-marker (&optional pos)
21030 "Return a new marker for use by Imenu, and remember the marker."
21031 (let ((m (make-marker)))
21032 (move-marker m (or pos (point)))
21033 (push m org-imenu-markers)
21036 (defun org-imenu-get-tree ()
21037 "Produce the index for Imenu."
21038 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21039 (setq org-imenu-markers nil)
21040 (let* ((n org-imenu-depth)
21041 (re (concat "^" (org-get-limited-outline-regexp)))
21042 (subs (make-vector (1+ n) nil))
21043 (last-level 0)
21044 m level head)
21045 (save-excursion
21046 (save-restriction
21047 (widen)
21048 (goto-char (point-max))
21049 (while (re-search-backward re nil t)
21050 (setq level (org-reduced-level (funcall outline-level)))
21051 (when (<= level n)
21052 (looking-at org-complex-heading-regexp)
21053 (setq head (org-link-display-format
21054 (org-match-string-no-properties 4))
21055 m (org-imenu-new-marker))
21056 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21057 (if (>= level last-level)
21058 (push (cons head m) (aref subs level))
21059 (push (cons head (aref subs (1+ level))) (aref subs level))
21060 (loop for i from (1+ level) to n do (aset subs i nil)))
21061 (setq last-level level)))))
21062 (aref subs 1)))
21064 (eval-after-load "imenu"
21065 '(progn
21066 (add-hook 'imenu-after-jump-hook
21067 (lambda ()
21068 (if (eq major-mode 'org-mode)
21069 (org-show-context 'org-goto))))))
21071 (defun org-link-display-format (link)
21072 "Replace a link with either the description, or the link target
21073 if no description is present"
21074 (save-match-data
21075 (if (string-match org-bracket-link-analytic-regexp link)
21076 (replace-match (if (match-end 5)
21077 (match-string 5 link)
21078 (concat (match-string 1 link)
21079 (match-string 3 link)))
21080 nil t link)
21081 link)))
21083 (defun org-toggle-link-display ()
21084 "Toggle the literal or descriptive display of links."
21085 (interactive)
21086 (if org-descriptive-links
21087 (progn (org-remove-from-invisibility-spec '(org-link))
21088 (org-restart-font-lock)
21089 (setq org-descriptive-links nil))
21090 (progn (add-to-invisibility-spec '(org-link))
21091 (org-restart-font-lock)
21092 (setq org-descriptive-links t))))
21094 ;; Speedbar support
21096 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21097 "Overlay marking the agenda restriction line in speedbar.")
21098 (overlay-put org-speedbar-restriction-lock-overlay
21099 'face 'org-agenda-restriction-lock)
21100 (overlay-put org-speedbar-restriction-lock-overlay
21101 'help-echo "Agendas are currently limited to this item.")
21102 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21104 (defun org-speedbar-set-agenda-restriction ()
21105 "Restrict future agenda commands to the location at point in speedbar.
21106 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21107 (interactive)
21108 (require 'org-agenda)
21109 (let (p m tp np dir txt)
21110 (cond
21111 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21112 'org-imenu t))
21113 (setq m (get-text-property p 'org-imenu-marker))
21114 (with-current-buffer (marker-buffer m)
21115 (goto-char m)
21116 (org-agenda-set-restriction-lock 'subtree)))
21117 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21118 'speedbar-function 'speedbar-find-file))
21119 (setq tp (previous-single-property-change
21120 (1+ p) 'speedbar-function)
21121 np (next-single-property-change
21122 tp 'speedbar-function)
21123 dir (speedbar-line-directory)
21124 txt (buffer-substring-no-properties (or tp (point-min))
21125 (or np (point-max))))
21126 (with-current-buffer (find-file-noselect
21127 (let ((default-directory dir))
21128 (expand-file-name txt)))
21129 (unless (eq major-mode 'org-mode)
21130 (error "Cannot restrict to non-Org-mode file"))
21131 (org-agenda-set-restriction-lock 'file)))
21132 (t (error "Don't know how to restrict Org-mode's agenda")))
21133 (move-overlay org-speedbar-restriction-lock-overlay
21134 (point-at-bol) (point-at-eol))
21135 (setq current-prefix-arg nil)
21136 (org-agenda-maybe-redo)))
21138 (eval-after-load "speedbar"
21139 '(progn
21140 (speedbar-add-supported-extension ".org")
21141 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21142 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21143 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21144 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21145 (add-hook 'speedbar-visiting-tag-hook
21146 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21148 ;;; Fixes and Hacks for problems with other packages
21150 ;; Make flyspell not check words in links, to not mess up our keymap
21151 (defun org-mode-flyspell-verify ()
21152 "Don't let flyspell put overlays at active buttons, or on
21153 {todo,all-time,additional-option-like}-keywords."
21154 (let ((pos (max (1- (point)) (point-min)))
21155 (word (thing-at-point 'word)))
21156 (and (not (get-text-property pos 'keymap))
21157 (not (get-text-property pos 'org-no-flyspell))
21158 (not (member word org-todo-keywords-1))
21159 (not (member word org-all-time-keywords))
21160 (not (member word org-additional-option-like-keywords)))))
21162 (defun org-remove-flyspell-overlays-in (beg end)
21163 "Remove flyspell overlays in region."
21164 (and (org-bound-and-true-p flyspell-mode)
21165 (fboundp 'flyspell-delete-region-overlays)
21166 (flyspell-delete-region-overlays beg end))
21167 (add-text-properties beg end '(org-no-flyspell t)))
21169 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21170 (eval-after-load "bookmark"
21171 '(if (boundp 'bookmark-after-jump-hook)
21172 ;; We can use the hook
21173 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21174 ;; Hook not available, use advice
21175 (defadvice bookmark-jump (after org-make-visible activate)
21176 "Make the position visible."
21177 (org-bookmark-jump-unhide))))
21179 ;; Make sure saveplace shows the location if it was hidden
21180 (eval-after-load "saveplace"
21181 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21182 "Make the position visible."
21183 (org-bookmark-jump-unhide)))
21185 ;; Make sure ecb shows the location if it was hidden
21186 (eval-after-load "ecb"
21187 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21188 "Make hierarchy visible when jumping into location from ECB tree buffer."
21189 (if (eq major-mode 'org-mode)
21190 (org-show-context))))
21192 (defun org-bookmark-jump-unhide ()
21193 "Unhide the current position, to show the bookmark location."
21194 (and (eq major-mode 'org-mode)
21195 (or (outline-invisible-p)
21196 (save-excursion (goto-char (max (point-min) (1- (point))))
21197 (outline-invisible-p)))
21198 (org-show-context 'bookmark-jump)))
21200 ;; Make session.el ignore our circular variable
21201 (eval-after-load "session"
21202 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21204 ;;;; Experimental code
21206 (defun org-closed-in-range ()
21207 "Sparse tree of items closed in a certain time range.
21208 Still experimental, may disappear in the future."
21209 (interactive)
21210 ;; Get the time interval from the user.
21211 (let* ((time1 (org-float-time
21212 (org-read-date nil 'to-time nil "Starting date: ")))
21213 (time2 (org-float-time
21214 (org-read-date nil 'to-time nil "End date:")))
21215 ;; callback function
21216 (callback (lambda ()
21217 (let ((time
21218 (org-float-time
21219 (apply 'encode-time
21220 (org-parse-time-string
21221 (match-string 1))))))
21222 ;; check if time in interval
21223 (and (>= time time1) (<= time time2))))))
21224 ;; make tree, check each match with the callback
21225 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21227 ;;;; Finish up
21229 (provide 'org)
21231 (run-hooks 'org-load-hook)
21233 ;;; org.el ends here