Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob859748a2a8a9cf741f6a2cd03d7332a3057d721a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
10 ;; Version: 7.8.03
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum))
78 (require 'calendar)
80 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
81 (when (fboundp 'defvaralias)
82 (unless (boundp 'calendar-view-holidays-initially-flag)
83 (defvaralias 'calendar-view-holidays-initially-flag
84 'view-calendar-holidays-initially))
85 (unless (boundp 'calendar-view-diary-initially-flag)
86 (defvaralias 'calendar-view-diary-initially-flag
87 'view-diary-entries-initially))
88 (unless (boundp 'diary-fancy-buffer)
89 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
91 (require 'outline) (require 'noutline)
92 ;; Other stuff we need.
93 (require 'time-date)
94 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
95 (require 'easymenu)
96 (require 'overlay)
98 (require 'org-macs)
99 (require 'org-entities)
100 (require 'org-compat)
101 (require 'org-faces)
102 (require 'org-list)
103 (require 'org-pcomplete)
104 (require 'org-src)
105 (require 'org-footnote)
107 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
108 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
109 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
111 (declare-function org-at-clock-log-p "org-clock" ())
112 (declare-function org-clock-timestamps-up "org-clock" ())
113 (declare-function org-clock-timestamps-down "org-clock" ())
115 ;; babel
116 (require 'ob)
117 (require 'ob-table)
118 (require 'ob-lob)
119 (require 'ob-ref)
120 (require 'ob-tangle)
121 (require 'ob-comint)
122 (require 'ob-keys)
124 ;; load languages based on value of `org-babel-load-languages'
125 (defvar org-babel-load-languages)
126 ;;;###autoload
127 (defun org-babel-do-load-languages (sym value)
128 "Load the languages defined in `org-babel-load-languages'."
129 (set-default sym value)
130 (mapc (lambda (pair)
131 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
132 (if active
133 (progn
134 (require (intern (concat "ob-" lang))))
135 (progn
136 (funcall 'fmakunbound
137 (intern (concat "org-babel-execute:" lang)))
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-expand-body:" lang)))))))
140 org-babel-load-languages))
142 (defcustom org-babel-load-languages '((emacs-lisp . t))
143 "Languages which can be evaluated in Org-mode buffers.
144 This list can be used to load support for any of the languages
145 below, note that each language will depend on a different set of
146 system executables and/or Emacs modes. When a language is
147 \"loaded\", then code blocks in that language can be evaluated
148 with `org-babel-execute-src-block' bound by default to C-c
149 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
150 be set to remove code block evaluation from the C-c C-c
151 keybinding. By default only Emacs Lisp (which has no
152 requirements) is loaded."
153 :group 'org-babel
154 :set 'org-babel-do-load-languages
155 :version "24.1"
156 :type '(alist :tag "Babel Languages"
157 :key-type
158 (choice
159 (const :tag "Awk" awk)
160 (const :tag "C" C)
161 (const :tag "R" R)
162 (const :tag "Asymptote" asymptote)
163 (const :tag "Calc" calc)
164 (const :tag "Clojure" clojure)
165 (const :tag "CSS" css)
166 (const :tag "Ditaa" ditaa)
167 (const :tag "Dot" dot)
168 (const :tag "Emacs Lisp" emacs-lisp)
169 (const :tag "Fortran" fortran)
170 (const :tag "Gnuplot" gnuplot)
171 (const :tag "Haskell" haskell)
172 (const :tag "IO" io)
173 (const :tag "Java" java)
174 (const :tag "Javascript" js)
175 (const :tag "LaTeX" latex)
176 (const :tag "Ledger" ledger)
177 (const :tag "Lilypond" lilypond)
178 (const :tag "Maxima" maxima)
179 (const :tag "Matlab" matlab)
180 (const :tag "Mscgen" mscgen)
181 (const :tag "Ocaml" ocaml)
182 (const :tag "Octave" octave)
183 (const :tag "Org" org)
184 (const :tag "Perl" perl)
185 (const :tag "Pico Lisp" picolisp)
186 (const :tag "PlantUML" plantuml)
187 (const :tag "Python" python)
188 (const :tag "Ruby" ruby)
189 (const :tag "Sass" sass)
190 (const :tag "Scala" scala)
191 (const :tag "Scheme" scheme)
192 (const :tag "Screen" screen)
193 (const :tag "Shell Script" sh)
194 (const :tag "Shen" shen)
195 (const :tag "Sql" sql)
196 (const :tag "Sqlite" sqlite))
197 :value-type (boolean :tag "Activate" :value t)))
199 ;;;; Customization variables
200 (defcustom org-clone-delete-id nil
201 "Remove ID property of clones of a subtree.
202 When non-nil, clones of a subtree don't inherit the ID property.
203 Otherwise they inherit the ID property with a new unique
204 identifier."
205 :type 'boolean
206 :version "24.1"
207 :group 'org-id)
209 ;;; Version
211 (defconst org-version "7.8.03"
212 "The version number of the file org.el.")
214 (defun org-version (&optional here)
215 "Show the org-mode version in the echo area.
216 With prefix arg HERE, insert it at point."
217 (interactive "P")
218 (let* ((origin default-directory)
219 (version org-version)
220 (git-version)
221 (dir (concat (file-name-directory (locate-library "org")) "../" )))
222 (when (and (file-exists-p (expand-file-name ".git" dir))
223 (executable-find "git"))
224 (unwind-protect
225 (progn
226 (cd dir)
227 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
228 (with-current-buffer "*Shell Command Output*"
229 (goto-char (point-min))
230 (setq git-version (buffer-substring (point) (point-at-eol))))
231 (subst-char-in-string ?- ?. git-version t)
232 (when (string-match "\\S-"
233 (shell-command-to-string
234 "git diff-index --name-only HEAD --"))
235 (setq git-version (concat git-version ".dirty")))
236 (setq version (concat version " (" git-version ")"))))
237 (cd origin)))
238 (setq version (format "Org-mode version %s" version))
239 (if here (insert version))
240 (message version)))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (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)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline 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-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-comment-string "COMMENT"
678 "Entries starting with this keyword will never be exported.
679 An entry can be toggled between COMMENT and normal with
680 \\[org-toggle-comment].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-quote-string "QUOTE"
686 "Entries starting with this keyword will be exported in fixed-width font.
687 Quoting applies only to the text in the entry following the headline, and does
688 not extend beyond the next headline, even if that is lower level.
689 An entry can be toggled between QUOTE and normal with
690 \\[org-toggle-fixed-width-section]."
691 :group 'org-keywords
692 :type 'string)
694 (defconst org-repeat-re
695 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
696 "Regular expression for specifying repeated events.
697 After a match, group 1 contains the repeat expression.")
699 (defgroup org-structure nil
700 "Options concerning the general structure of Org-mode files."
701 :tag "Org Structure"
702 :group 'org)
704 (defgroup org-reveal-location nil
705 "Options about how to make context of a location visible."
706 :tag "Org Reveal Location"
707 :group 'org-structure)
709 (defconst org-context-choice
710 '(choice
711 (const :tag "Always" t)
712 (const :tag "Never" nil)
713 (repeat :greedy t :tag "Individual contexts"
714 (cons
715 (choice :tag "Context"
716 (const agenda)
717 (const org-goto)
718 (const occur-tree)
719 (const tags-tree)
720 (const link-search)
721 (const mark-goto)
722 (const bookmark-jump)
723 (const isearch)
724 (const default))
725 (boolean))))
726 "Contexts for the reveal options.")
728 (defcustom org-show-hierarchy-above '((default . t))
729 "Non-nil means show full hierarchy when revealing a location.
730 Org-mode often shows locations in an org-mode file which might have
731 been invisible before. When this is set, the hierarchy of headings
732 above the exposed location is shown.
733 Turning this off for example for sparse trees makes them very compact.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. Valid contexts are
736 agenda when exposing an entry from the agenda
737 org-goto when using the command `org-goto' on key C-c C-j
738 occur-tree when using the command `org-occur' on key C-c /
739 tags-tree when constructing a sparse tree based on tags matches
740 link-search when exposing search matches associated with a link
741 mark-goto when exposing the jump goal of a mark
742 bookmark-jump when exposing a bookmark location
743 isearch when exiting from an incremental search
744 default default for all contexts not set explicitly"
745 :group 'org-reveal-location
746 :type org-context-choice)
748 (defcustom org-show-following-heading '((default . nil))
749 "Non-nil means show following heading when revealing a location.
750 Org-mode often shows locations in an org-mode file which might have
751 been invisible before. When this is set, the heading following the
752 match is shown.
753 Turning this off for example for sparse trees makes them very compact,
754 but makes it harder to edit the location of the match. In such a case,
755 use the command \\[org-reveal] to show more context.
756 Instead of t, this can also be an alist specifying this option for different
757 contexts. See `org-show-hierarchy-above' for valid contexts."
758 :group 'org-reveal-location
759 :type org-context-choice)
761 (defcustom org-show-siblings '((default . nil) (isearch t))
762 "Non-nil means show all sibling heading when revealing a location.
763 Org-mode often shows locations in an org-mode file which might have
764 been invisible before. When this is set, the sibling of the current entry
765 heading are all made visible. If `org-show-hierarchy-above' is t,
766 the same happens on each level of the hierarchy above the current entry.
768 By default this is on for the isearch context, off for all other contexts.
769 Turning this off for example for sparse trees makes them very compact,
770 but makes it harder to edit the location of the match. In such a case,
771 use the command \\[org-reveal] to show more context.
772 Instead of t, this can also be an alist specifying this option for different
773 contexts. See `org-show-hierarchy-above' for valid contexts."
774 :group 'org-reveal-location
775 :type org-context-choice)
777 (defcustom org-show-entry-below '((default . nil))
778 "Non-nil means show the entry below a headline when revealing a location.
779 Org-mode often shows locations in an org-mode file which might have
780 been invisible before. When this is set, the text below the headline that is
781 exposed is also shown.
783 By default this is off for all contexts.
784 Instead of t, this can also be an alist specifying this option for different
785 contexts. See `org-show-hierarchy-above' for valid contexts."
786 :group 'org-reveal-location
787 :type org-context-choice)
789 (defcustom org-indirect-buffer-display 'other-window
790 "How should indirect tree buffers be displayed?
791 This applies to indirect buffers created with the commands
792 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
793 Valid values are:
794 current-window Display in the current window
795 other-window Just display in another window.
796 dedicated-frame Create one new frame, and re-use it each time.
797 new-frame Make a new frame each time. Note that in this case
798 previously-made indirect buffers are kept, and you need to
799 kill these buffers yourself."
800 :group 'org-structure
801 :group 'org-agenda-windows
802 :type '(choice
803 (const :tag "In current window" current-window)
804 (const :tag "In current frame, other window" other-window)
805 (const :tag "Each time a new frame" new-frame)
806 (const :tag "One dedicated frame" dedicated-frame)))
808 (defcustom org-use-speed-commands nil
809 "Non-nil means activate single letter commands at beginning of a headline.
810 This may also be a function to test for appropriate locations where speed
811 commands should be active."
812 :group 'org-structure
813 :type '(choice
814 (const :tag "Never" nil)
815 (const :tag "At beginning of headline stars" t)
816 (function)))
818 (defcustom org-speed-commands-user nil
819 "Alist of additional speed commands.
820 This list will be checked before `org-speed-commands-default'
821 when the variable `org-use-speed-commands' is non-nil
822 and when the cursor is at the beginning of a headline.
823 The car if each entry is a string with a single letter, which must
824 be assigned to `self-insert-command' in the global map.
825 The cdr is either a command to be called interactively, a function
826 to be called, or a form to be evaluated.
827 An entry that is just a list with a single string will be interpreted
828 as a descriptive headline that will be added when listing the speed
829 commands in the Help buffer using the `?' speed command."
830 :group 'org-structure
831 :type '(repeat :value ("k" . ignore)
832 (choice :value ("k" . ignore)
833 (list :tag "Descriptive Headline" (string :tag "Headline"))
834 (cons :tag "Letter and Command"
835 (string :tag "Command letter")
836 (choice
837 (function)
838 (sexp))))))
840 (defgroup org-cycle nil
841 "Options concerning visibility cycling in Org-mode."
842 :tag "Org Cycle"
843 :group 'org-structure)
845 (defcustom org-cycle-skip-children-state-if-no-children t
846 "Non-nil means skip CHILDREN state in entries that don't have any."
847 :group 'org-cycle
848 :type 'boolean)
850 (defcustom org-cycle-max-level nil
851 "Maximum level which should still be subject to visibility cycling.
852 Levels higher than this will, for cycling, be treated as text, not a headline.
853 When `org-odd-levels-only' is set, a value of N in this variable actually
854 means 2N-1 stars as the limiting headline.
855 When nil, cycle all levels.
856 Note that the limiting level of cycling is also influenced by
857 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
858 `org-inlinetask-min-level' is, cycling will be limited to levels one less
859 than its value."
860 :group 'org-cycle
861 :type '(choice
862 (const :tag "No limit" nil)
863 (integer :tag "Maximum level")))
865 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
866 "Names of drawers. Drawers are not opened by cycling on the headline above.
867 Drawers only open with a TAB on the drawer line itself. A drawer looks like
868 this:
869 :DRAWERNAME:
870 .....
871 :END:
872 The drawer \"PROPERTIES\" is special for capturing properties through
873 the property API.
875 Drawers can be defined on the per-file basis with a line like:
877 #+DRAWERS: HIDDEN STATE PROPERTIES"
878 :group 'org-structure
879 :group 'org-cycle
880 :type '(repeat (string :tag "Drawer Name")))
882 (defcustom org-hide-block-startup nil
883 "Non-nil means entering Org-mode will fold all blocks.
884 This can also be set in on a per-file basis with
886 #+STARTUP: hideblocks
887 #+STARTUP: showblocks"
888 :group 'org-startup
889 :group 'org-cycle
890 :type 'boolean)
892 (defcustom org-cycle-global-at-bob nil
893 "Cycle globally if cursor is at beginning of buffer and not at a headline.
894 This makes it possible to do global cycling without having to use S-TAB or
895 \\[universal-argument] TAB. For this special case to work, the first line \
896 of the buffer
897 must not be a headline - it may be empty or some other text. When used in
898 this way, `org-cycle-hook' is disables temporarily, to make sure the
899 cursor stays at the beginning of the buffer.
900 When this option is nil, don't do anything special at the beginning
901 of the buffer."
902 :group 'org-cycle
903 :type 'boolean)
905 (defcustom org-cycle-level-after-item/entry-creation t
906 "Non-nil means cycle entry level or item indentation in new empty entries.
908 When the cursor is at the end of an empty headline, i.e with only stars
909 and maybe a TODO keyword, TAB will then switch the entry to become a child,
910 and then all possible ancestor states, before returning to the original state.
911 This makes data entry extremely fast: M-RET to create a new headline,
912 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
914 When the cursor is at the end of an empty plain list item, one TAB will
915 make it a subitem, two or more tabs will back up to make this an item
916 higher up in the item hierarchy."
917 :group 'org-cycle
918 :type 'boolean)
920 (defcustom org-cycle-emulate-tab t
921 "Where should `org-cycle' emulate TAB.
922 nil Never
923 white Only in completely white lines
924 whitestart Only at the beginning of lines, before the first non-white char
925 t Everywhere except in headlines
926 exc-hl-bol Everywhere except at the start of a headline
927 If TAB is used in a place where it does not emulate TAB, the current subtree
928 visibility is cycled."
929 :group 'org-cycle
930 :type '(choice (const :tag "Never" nil)
931 (const :tag "Only in completely white lines" white)
932 (const :tag "Before first char in a line" whitestart)
933 (const :tag "Everywhere except in headlines" t)
934 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
937 (defcustom org-cycle-separator-lines 2
938 "Number of empty lines needed to keep an empty line between collapsed trees.
939 If you leave an empty line between the end of a subtree and the following
940 headline, this empty line is hidden when the subtree is folded.
941 Org-mode will leave (exactly) one empty line visible if the number of
942 empty lines is equal or larger to the number given in this variable.
943 So the default 2 means at least 2 empty lines after the end of a subtree
944 are needed to produce free space between a collapsed subtree and the
945 following headline.
947 If the number is negative, and the number of empty lines is at least -N,
948 all empty lines are shown.
950 Special case: when 0, never leave empty lines in collapsed view."
951 :group 'org-cycle
952 :type 'integer)
953 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
955 (defcustom org-pre-cycle-hook nil
956 "Hook that is run before visibility cycling is happening.
957 The function(s) in this hook must accept a single argument which indicates
958 the new state that will be set right after running this hook. The
959 argument is a symbol. Before a global state change, it can have the values
960 `overview', `content', or `all'. Before a local state change, it can have
961 the values `folded', `children', or `subtree'."
962 :group 'org-cycle
963 :type 'hook)
965 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
966 org-cycle-hide-drawers
967 org-cycle-show-empty-lines
968 org-optimize-window-after-visibility-change)
969 "Hook that is run after `org-cycle' has changed the buffer visibility.
970 The function(s) in this hook must accept a single argument which indicates
971 the new state that was set by the most recent `org-cycle' command. The
972 argument is a symbol. After a global state change, it can have the values
973 `overview', `content', or `all'. After a local state change, it can have
974 the values `folded', `children', or `subtree'."
975 :group 'org-cycle
976 :type 'hook)
978 (defgroup org-edit-structure nil
979 "Options concerning structure editing in Org-mode."
980 :tag "Org Edit Structure"
981 :group 'org-structure)
983 (defcustom org-odd-levels-only nil
984 "Non-nil means skip even levels and only use odd levels for the outline.
985 This has the effect that two stars are being added/taken away in
986 promotion/demotion commands. It also influences how levels are
987 handled by the exporters.
988 Changing it requires restart of `font-lock-mode' to become effective
989 for fontification also in regions already fontified.
990 You may also set this on a per-file basis by adding one of the following
991 lines to the buffer:
993 #+STARTUP: odd
994 #+STARTUP: oddeven"
995 :group 'org-edit-structure
996 :group 'org-appearance
997 :type 'boolean)
999 (defcustom org-adapt-indentation t
1000 "Non-nil means adapt indentation to outline node level.
1002 When this variable is set, Org assumes that you write outlines by
1003 indenting text in each node to align with the headline (after the stars).
1004 The following issues are influenced by this variable:
1006 - When this is set and the *entire* text in an entry is indented, the
1007 indentation is increased by one space in a demotion command, and
1008 decreased by one in a promotion command. If any line in the entry
1009 body starts with text at column 0, indentation is not changed at all.
1011 - Property drawers and planning information is inserted indented when
1012 this variable s set. When nil, they will not be indented.
1014 - TAB indents a line relative to context. The lines below a headline
1015 will be indented when this variable is set.
1017 Note that this is all about true indentation, by adding and removing
1018 space characters. See also `org-indent.el' which does level-dependent
1019 indentation in a virtual way, i.e. at display time in Emacs."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-special-ctrl-a/e nil
1024 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1026 When t, `C-a' will bring back the cursor to the beginning of the
1027 headline text, i.e. after the stars and after a possible TODO
1028 keyword. In an item, this will be the position after bullet and
1029 check-box, if any. When the cursor is already at that position,
1030 another `C-a' will bring it to the beginning of the line.
1032 `C-e' will jump to the end of the headline, ignoring the presence
1033 of tags in the headline. A second `C-e' will then jump to the
1034 true end of the line, after any tags. This also means that, when
1035 this variable is non-nil, `C-e' also will never jump beyond the
1036 end of the heading of a folded section, i.e. not after the
1037 ellipses.
1039 When set to the symbol `reversed', the first `C-a' or `C-e' works
1040 normally, going to the true line boundary first. Only a directly
1041 following, identical keypress will bring the cursor to the
1042 special positions.
1044 This may also be a cons cell where the behavior for `C-a' and
1045 `C-e' is set separately."
1046 :group 'org-edit-structure
1047 :type '(choice
1048 (const :tag "off" nil)
1049 (const :tag "on: after stars/bullet and before tags first" t)
1050 (const :tag "reversed: true line boundary first" reversed)
1051 (cons :tag "Set C-a and C-e separately"
1052 (choice :tag "Special C-a"
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet first" t)
1055 (const :tag "reversed: before stars/bullet first" reversed))
1056 (choice :tag "Special C-e"
1057 (const :tag "off" nil)
1058 (const :tag "on: before tags first" t)
1059 (const :tag "reversed: after tags first" reversed)))))
1060 (if (fboundp 'defvaralias)
1061 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1063 (defcustom org-special-ctrl-k nil
1064 "Non-nil means `C-k' will behave specially in headlines.
1065 When nil, `C-k' will call the default `kill-line' command.
1066 When t, the following will happen while the cursor is in the headline:
1068 - When the cursor is at the beginning of a headline, kill the entire
1069 line and possible the folded subtree below the line.
1070 - When in the middle of the headline text, kill the headline up to the tags.
1071 - When after the headline text, kill the tags."
1072 :group 'org-edit-structure
1073 :type 'boolean)
1075 (defcustom org-ctrl-k-protect-subtree nil
1076 "Non-nil means, do not delete a hidden subtree with C-k.
1077 When set to the symbol `error', simply throw an error when C-k is
1078 used to kill (part-of) a headline that has hidden text behind it.
1079 Any other non-nil value will result in a query to the user, if it is
1080 OK to kill that hidden subtree. When nil, kill without remorse."
1081 :group 'org-edit-structure
1082 :version "24.1"
1083 :type '(choice
1084 (const :tag "Do not protect hidden subtrees" nil)
1085 (const :tag "Protect hidden subtrees with a security query" t)
1086 (const :tag "Never kill a hidden subtree with C-k" error)))
1088 (defcustom org-catch-invisible-edits nil
1089 "Check if in invisible region before inserting or deleting a character.
1090 Valid values are:
1092 nil Do not check, so just do invisible edits.
1093 error Throw an error and do nothing.
1094 show Make point visible, and do the requested edit.
1095 show-and-error Make point visible, then throw an error and abort the edit.
1096 smart Make point visible, and do insertion/deletion if it is
1097 adjacent to visible text and the change feels predictable.
1098 Never delete a previously invisible character or add in the
1099 middle or right after an invisible region. Basically, this
1100 allows insertion and backward-delete right before ellipses.
1101 FIXME: maybe in this case we should not even show?"
1102 :group 'org-edit-structure
1103 :version "24.1"
1104 :type '(choice
1105 (const :tag "Do not check" nil)
1106 (const :tag "Throw error when trying to edit" error)
1107 (const :tag "Unhide, but do not do the edit" show-and-error)
1108 (const :tag "Show invisible part and do the edit" show)
1109 (const :tag "Be smart and do the right thing" smart)))
1111 (defcustom org-yank-folded-subtrees t
1112 "Non-nil means when yanking subtrees, fold them.
1113 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1114 it starts with a heading and all other headings in it are either children
1115 or siblings, then fold all the subtrees. However, do this only if no
1116 text after the yank would be swallowed into a folded tree by this action."
1117 :group 'org-edit-structure
1118 :type 'boolean)
1120 (defcustom org-yank-adjusted-subtrees nil
1121 "Non-nil means when yanking subtrees, adjust the level.
1122 With this setting, `org-paste-subtree' is used to insert the subtree, see
1123 this function for details."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-M-RET-may-split-line '((default . t))
1128 "Non-nil means M-RET will split the line at the cursor position.
1129 When nil, it will go to the end of the line before making a
1130 new line.
1131 You may also set this option in a different way for different
1132 contexts. Valid contexts are:
1134 headline when creating a new headline
1135 item when creating a new item
1136 table in a table field
1137 default the value to be used for all contexts not explicitly
1138 customized"
1139 :group 'org-structure
1140 :group 'org-table
1141 :type '(choice
1142 (const :tag "Always" t)
1143 (const :tag "Never" nil)
1144 (repeat :greedy t :tag "Individual contexts"
1145 (cons
1146 (choice :tag "Context"
1147 (const headline)
1148 (const item)
1149 (const table)
1150 (const default))
1151 (boolean)))))
1154 (defcustom org-insert-heading-respect-content nil
1155 "Non-nil means insert new headings after the current subtree.
1156 When nil, the new heading is created directly after the current line.
1157 The commands \\[org-insert-heading-respect-content] and
1158 \\[org-insert-todo-heading-respect-content] turn this variable on
1159 for the duration of the command."
1160 :group 'org-structure
1161 :type 'boolean)
1163 (defcustom org-blank-before-new-entry '((heading . auto)
1164 (plain-list-item . auto))
1165 "Should `org-insert-heading' leave a blank line before new heading/item?
1166 The value is an alist, with `heading' and `plain-list-item' as CAR,
1167 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1168 which case Org will look at the surrounding headings/items and try to
1169 make an intelligent decision whether to insert a blank line or not.
1171 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1172 set, the setting here is ignored and no empty line is inserted, to avoid
1173 breaking the list structure."
1174 :group 'org-edit-structure
1175 :type '(list
1176 (cons (const heading)
1177 (choice (const :tag "Never" nil)
1178 (const :tag "Always" t)
1179 (const :tag "Auto" auto)))
1180 (cons (const plain-list-item)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))))
1185 (defcustom org-insert-heading-hook nil
1186 "Hook being run after inserting a new heading."
1187 :group 'org-edit-structure
1188 :type 'hook)
1190 (defcustom org-enable-fixed-width-editor t
1191 "Non-nil means lines starting with \":\" are treated as fixed-width.
1192 This currently only means they are never auto-wrapped.
1193 When nil, such lines will be treated like ordinary lines.
1194 See also the QUOTE keyword."
1195 :group 'org-edit-structure
1196 :type 'boolean)
1198 (defcustom org-goto-auto-isearch t
1199 "Non-nil means typing characters in `org-goto' starts incremental search."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defgroup org-sparse-trees nil
1204 "Options concerning sparse trees in Org-mode."
1205 :tag "Org Sparse Trees"
1206 :group 'org-structure)
1208 (defcustom org-highlight-sparse-tree-matches t
1209 "Non-nil means highlight all matches that define a sparse tree.
1210 The highlights will automatically disappear the next time the buffer is
1211 changed by an edit command."
1212 :group 'org-sparse-trees
1213 :type 'boolean)
1215 (defcustom org-remove-highlights-with-change t
1216 "Non-nil means any change to the buffer will remove temporary highlights.
1217 Such highlights are created by `org-occur' and `org-clock-display'.
1218 When nil, `C-c C-c needs to be used to get rid of the highlights.
1219 The highlights created by `org-preview-latex-fragment' always need
1220 `C-c C-c' to be removed."
1221 :group 'org-sparse-trees
1222 :group 'org-time
1223 :type 'boolean)
1226 (defcustom org-occur-hook '(org-first-headline-recenter)
1227 "Hook that is run after `org-occur' has constructed a sparse tree.
1228 This can be used to recenter the window to show as much of the structure
1229 as possible."
1230 :group 'org-sparse-trees
1231 :type 'hook)
1233 (defgroup org-imenu-and-speedbar nil
1234 "Options concerning imenu and speedbar in Org-mode."
1235 :tag "Org Imenu and Speedbar"
1236 :group 'org-structure)
1238 (defcustom org-imenu-depth 2
1239 "The maximum level for Imenu access to Org-mode headlines.
1240 This also applied for speedbar access."
1241 :group 'org-imenu-and-speedbar
1242 :type 'integer)
1244 (defgroup org-table nil
1245 "Options concerning tables in Org-mode."
1246 :tag "Org Table"
1247 :group 'org)
1249 (defcustom org-enable-table-editor 'optimized
1250 "Non-nil means lines starting with \"|\" are handled by the table editor.
1251 When nil, such lines will be treated like ordinary lines.
1253 When equal to the symbol `optimized', the table editor will be optimized to
1254 do the following:
1255 - Automatic overwrite mode in front of whitespace in table fields.
1256 This makes the structure of the table stay in tact as long as the edited
1257 field does not exceed the column width.
1258 - Minimize the number of realigns. Normally, the table is aligned each time
1259 TAB or RET are pressed to move to another field. With optimization this
1260 happens only if changes to a field might have changed the column width.
1261 Optimization requires replacing the functions `self-insert-command',
1262 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1263 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1264 very good at guessing when a re-align will be necessary, but you can always
1265 force one with \\[org-ctrl-c-ctrl-c].
1267 If you would like to use the optimized version in Org-mode, but the
1268 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1270 This variable can be used to turn on and off the table editor during a session,
1271 but in order to toggle optimization, a restart is required.
1273 See also the variable `org-table-auto-blank-field'."
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "off" nil)
1277 (const :tag "on" t)
1278 (const :tag "on, optimized" optimized)))
1280 (defcustom org-self-insert-cluster-for-undo t
1281 "Non-nil means cluster self-insert commands for undo when possible.
1282 If this is set, then, like in the Emacs command loop, 20 consecutive
1283 characters will be undone together.
1284 This is configurable, because there is some impact on typing performance."
1285 :group 'org-table
1286 :type 'boolean)
1288 (defcustom org-table-tab-recognizes-table.el t
1289 "Non-nil means TAB will automatically notice a table.el table.
1290 When it sees such a table, it moves point into it and - if necessary -
1291 calls `table-recognize-table'."
1292 :group 'org-table-editing
1293 :type 'boolean)
1295 (defgroup org-link nil
1296 "Options concerning links in Org-mode."
1297 :tag "Org Link"
1298 :group 'org)
1300 (defvar org-link-abbrev-alist-local nil
1301 "Buffer-local version of `org-link-abbrev-alist', which see.
1302 The value of this is taken from the #+LINK lines.")
1303 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1305 (defcustom org-link-abbrev-alist nil
1306 "Alist of link abbreviations.
1307 The car of each element is a string, to be replaced at the start of a link.
1308 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1309 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1311 [[linkkey:tag][description]]
1313 The 'linkkey' must be a word word, starting with a letter, followed
1314 by letters, numbers, '-' or '_'.
1316 If REPLACE is a string, the tag will simply be appended to create the link.
1317 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1318 the placeholder \"%h\" will cause a url-encoded version of the tag to
1319 be inserted at that point (see the function `url-hexify-string').
1321 REPLACE may also be a function that will be called with the tag as the
1322 only argument to create the link, which should be returned as a string.
1324 See the manual for examples."
1325 :group 'org-link
1326 :type '(repeat
1327 (cons
1328 (string :tag "Protocol")
1329 (choice
1330 (string :tag "Format")
1331 (function)))))
1333 (defcustom org-descriptive-links t
1334 "Non-nil means Org will display descriptive links.
1335 E.g. [[http://orgmode.org][Org website]] will be displayed as
1336 \"Org Website\", hiding the link itself and just displaying its
1337 description. When set to `nil', Org will display the full links
1338 literally.
1340 You can interactively set the value of this variable by calling
1341 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1342 :group 'org-link
1343 :type 'boolean)
1345 (defcustom org-link-file-path-type 'adaptive
1346 "How the path name in file links should be stored.
1347 Valid values are:
1349 relative Relative to the current directory, i.e. the directory of the file
1350 into which the link is being inserted.
1351 absolute Absolute path, if possible with ~ for home directory.
1352 noabbrev Absolute path, no abbreviation of home directory.
1353 adaptive Use relative path for files in the current directory and sub-
1354 directories of it. For other files, use an absolute path."
1355 :group 'org-link
1356 :type '(choice
1357 (const relative)
1358 (const absolute)
1359 (const noabbrev)
1360 (const adaptive)))
1362 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1363 "Types of links that should be activated in Org-mode files.
1364 This is a list of symbols, each leading to the activation of a certain link
1365 type. In principle, it does not hurt to turn on most link types - there may
1366 be a small gain when turning off unused link types. The types are:
1368 bracket The recommended [[link][description]] or [[link]] links with hiding.
1369 angle Links in angular brackets that may contain whitespace like
1370 <bbdb:Carsten Dominik>.
1371 plain Plain links in normal text, no whitespace, like http://google.com.
1372 radio Text that is matched by a radio target, see manual for details.
1373 tag Tag settings in a headline (link to tag search).
1374 date Time stamps (link to calendar).
1375 footnote Footnote labels.
1377 Changing this variable requires a restart of Emacs to become effective."
1378 :group 'org-link
1379 :type '(set :greedy t
1380 (const :tag "Double bracket links" bracket)
1381 (const :tag "Angular bracket links" angle)
1382 (const :tag "Plain text links" plain)
1383 (const :tag "Radio target matches" radio)
1384 (const :tag "Tags" tag)
1385 (const :tag "Timestamps" date)
1386 (const :tag "Footnotes" footnote)))
1388 (defcustom org-make-link-description-function nil
1389 "Function to use to generate link descriptions from links.
1390 If nil the link location will be used. This function must take
1391 two parameters; the first is the link and the second the
1392 description `org-insert-link' has generated, and should return the
1393 description to use."
1394 :group 'org-link
1395 :type 'function)
1397 (defgroup org-link-store nil
1398 "Options concerning storing links in Org-mode."
1399 :tag "Org Store Link"
1400 :group 'org-link)
1402 (defcustom org-email-link-description-format "Email %c: %.30s"
1403 "Format of the description part of a link to an email or usenet message.
1404 The following %-escapes will be replaced by corresponding information:
1406 %F full \"From\" field
1407 %f name, taken from \"From\" field, address if no name
1408 %T full \"To\" field
1409 %t first name in \"To\" field, address if no name
1410 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1411 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1412 %s subject
1413 %d date
1414 %m message-id.
1416 You may use normal field width specification between the % and the letter.
1417 This is for example useful to limit the length of the subject.
1419 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1420 :group 'org-link-store
1421 :type 'string)
1423 (defcustom org-from-is-user-regexp
1424 (let (r1 r2)
1425 (when (and user-mail-address (not (string= user-mail-address "")))
1426 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1427 (when (and user-full-name (not (string= user-full-name "")))
1428 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1429 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1430 "Regexp matched against the \"From:\" header of an email or usenet message.
1431 It should match if the message is from the user him/herself."
1432 :group 'org-link-store
1433 :type 'regexp)
1435 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1436 "Non-nil means storing a link to an Org file will use entry IDs.
1438 Note that before this variable is even considered, org-id must be loaded,
1439 so please customize `org-modules' and turn it on.
1441 The variable can have the following values:
1443 t Create an ID if needed to make a link to the current entry.
1445 create-if-interactive
1446 If `org-store-link' is called directly (interactively, as a user
1447 command), do create an ID to support the link. But when doing the
1448 job for remember, only use the ID if it already exists. The
1449 purpose of this setting is to avoid proliferation of unwanted
1450 IDs, just because you happen to be in an Org file when you
1451 call `org-remember' that automatically and preemptively
1452 creates a link. If you do want to get an ID link in a remember
1453 template to an entry not having an ID, create it first by
1454 explicitly creating a link to it, using `C-c C-l' first.
1456 create-if-interactive-and-no-custom-id
1457 Like create-if-interactive, but do not create an ID if there is
1458 a CUSTOM_ID property defined in the entry. This is the default.
1460 use-existing
1461 Use existing ID, do not create one.
1463 nil Never use an ID to make a link, instead link using a text search for
1464 the headline text."
1465 :group 'org-link-store
1466 :type '(choice
1467 (const :tag "Create ID to make link" t)
1468 (const :tag "Create if storing link interactively"
1469 create-if-interactive)
1470 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1471 create-if-interactive-and-no-custom-id)
1472 (const :tag "Only use existing" use-existing)
1473 (const :tag "Do not use ID to create link" nil)))
1475 (defcustom org-context-in-file-links t
1476 "Non-nil means file links from `org-store-link' contain context.
1477 A search string will be added to the file name with :: as separator and
1478 used to find the context when the link is activated by the command
1479 `org-open-at-point'. When this option is t, the entire active region
1480 will be placed in the search string of the file link. If set to a
1481 positive integer, only the first n lines of context will be stored.
1483 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1484 negates this setting for the duration of the command."
1485 :group 'org-link-store
1486 :type '(choice boolean integer))
1488 (defcustom org-keep-stored-link-after-insertion nil
1489 "Non-nil means keep link in list for entire session.
1491 The command `org-store-link' adds a link pointing to the current
1492 location to an internal list. These links accumulate during a session.
1493 The command `org-insert-link' can be used to insert links into any
1494 Org-mode file (offering completion for all stored links). When this
1495 option is nil, every link which has been inserted once using \\[org-insert-link]
1496 will be removed from the list, to make completing the unused links
1497 more efficient."
1498 :group 'org-link-store
1499 :type 'boolean)
1501 (defgroup org-link-follow nil
1502 "Options concerning following links in Org-mode."
1503 :tag "Org Follow Link"
1504 :group 'org-link)
1506 (defcustom org-link-translation-function nil
1507 "Function to translate links with different syntax to Org syntax.
1508 This can be used to translate links created for example by the Planner
1509 or emacs-wiki packages to Org syntax.
1510 The function must accept two parameters, a TYPE containing the link
1511 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1512 which is everything after the link protocol. It should return a cons
1513 with possibly modified values of type and path.
1514 Org contains a function for this, so if you set this variable to
1515 `org-translate-link-from-planner', you should be able follow many
1516 links created by planner."
1517 :group 'org-link-follow
1518 :type 'function)
1520 (defcustom org-follow-link-hook nil
1521 "Hook that is run after a link has been followed."
1522 :group 'org-link-follow
1523 :type 'hook)
1525 (defcustom org-tab-follows-link nil
1526 "Non-nil means on links TAB will follow the link.
1527 Needs to be set before org.el is loaded.
1528 This really should not be used, it does not make sense, and the
1529 implementation is bad."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-return-follows-link nil
1534 "Non-nil means on links RET will follow the link."
1535 :group 'org-link-follow
1536 :type 'boolean)
1538 (defcustom org-mouse-1-follows-link
1539 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1540 "Non-nil means mouse-1 on a link will follow the link.
1541 A longer mouse click will still set point. Does not work on XEmacs.
1542 Needs to be set before org.el is loaded."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-mark-ring-length 4
1547 "Number of different positions to be recorded in the ring.
1548 Changing this requires a restart of Emacs to work correctly."
1549 :group 'org-link-follow
1550 :type 'integer)
1552 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1553 "Non-nil means internal links in Org files must exactly match a headline.
1554 When nil, the link search tries to match a phrase with all words
1555 in the search text."
1556 :group 'org-link-follow
1557 :version "24.1"
1558 :type '(choice
1559 (const :tag "Use fuzzy text search" nil)
1560 (const :tag "Match only exact headline" t)
1561 (const :tag "Match exact headline or query to create it"
1562 query-to-create)))
1564 (defcustom org-link-frame-setup
1565 '((vm . vm-visit-folder-other-frame)
1566 (vm-imap . vm-visit-imap-folder-other-frame)
1567 (gnus . org-gnus-no-new-news)
1568 (file . find-file-other-window)
1569 (wl . wl-other-frame))
1570 "Setup the frame configuration for following links.
1571 When following a link with Emacs, it may often be useful to display
1572 this link in another window or frame. This variable can be used to
1573 set this up for the different types of links.
1574 For VM, use any of
1575 `vm-visit-folder'
1576 `vm-visit-folder-other-window'
1577 `vm-visit-folder-other-frame'
1578 For Gnus, use any of
1579 `gnus'
1580 `gnus-other-frame'
1581 `org-gnus-no-new-news'
1582 For FILE, use any of
1583 `find-file'
1584 `find-file-other-window'
1585 `find-file-other-frame'
1586 For Wanderlust use any of
1587 `wl'
1588 `wl-other-frame'
1589 For the calendar, use the variable `calendar-setup'.
1590 For BBDB, it is currently only possible to display the matches in
1591 another window."
1592 :group 'org-link-follow
1593 :type '(list
1594 (cons (const vm)
1595 (choice
1596 (const vm-visit-folder)
1597 (const vm-visit-folder-other-window)
1598 (const vm-visit-folder-other-frame)))
1599 (cons (const gnus)
1600 (choice
1601 (const gnus)
1602 (const gnus-other-frame)
1603 (const org-gnus-no-new-news)))
1604 (cons (const file)
1605 (choice
1606 (const find-file)
1607 (const find-file-other-window)
1608 (const find-file-other-frame)))
1609 (cons (const wl)
1610 (choice
1611 (const wl)
1612 (const wl-other-frame)))))
1614 (defcustom org-display-internal-link-with-indirect-buffer nil
1615 "Non-nil means use indirect buffer to display infile links.
1616 Activating internal links (from one location in a file to another location
1617 in the same file) normally just jumps to the location. When the link is
1618 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1619 is displayed in
1620 another window. When this option is set, the other window actually displays
1621 an indirect buffer clone of the current buffer, to avoid any visibility
1622 changes to the current buffer."
1623 :group 'org-link-follow
1624 :type 'boolean)
1626 (defcustom org-open-non-existing-files nil
1627 "Non-nil means `org-open-file' will open non-existing files.
1628 When nil, an error will be generated.
1629 This variable applies only to external applications because they
1630 might choke on non-existing files. If the link is to a file that
1631 will be opened in Emacs, the variable is ignored."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-open-directory-means-index-dot-org nil
1636 "Non-nil means a link to a directory really means to index.org.
1637 When nil, following a directory link will run dired or open a finder/explorer
1638 window on that directory."
1639 :group 'org-link-follow
1640 :type 'boolean)
1642 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1643 "Function and arguments to call for following mailto links.
1644 This is a list with the first element being a Lisp function, and the
1645 remaining elements being arguments to the function. In string arguments,
1646 %a will be replaced by the address, and %s will be replaced by the subject
1647 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1648 :group 'org-link-follow
1649 :type '(choice
1650 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1651 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1652 (const :tag "message-mail" (message-mail "%a" "%s"))
1653 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1655 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1656 "Non-nil means ask for confirmation before executing shell links.
1657 Shell links can be dangerous: just think about a link
1659 [[shell:rm -rf ~/*][Google Search]]
1661 This link would show up in your Org-mode document as \"Google Search\",
1662 but really it would remove your entire home directory.
1663 Therefore we advise against setting this variable to nil.
1664 Just change it to `y-or-n-p' if you want to confirm with a
1665 single keystroke rather than having to type \"yes\"."
1666 :group 'org-link-follow
1667 :type '(choice
1668 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1669 (const :tag "with y-or-n (faster)" y-or-n-p)
1670 (const :tag "no confirmation (dangerous)" nil)))
1671 (put 'org-confirm-shell-link-function
1672 'safe-local-variable
1673 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1675 (defcustom org-confirm-shell-link-not-regexp ""
1676 "A regexp to skip confirmation for shell links."
1677 :group 'org-link-follow
1678 :version "24.1"
1679 :type 'regexp)
1681 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1682 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1683 Elisp links can be dangerous: just think about a link
1685 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1687 This link would show up in your Org-mode document as \"Google Search\",
1688 but really it would remove your entire home directory.
1689 Therefore we advise against setting this variable to nil.
1690 Just change it to `y-or-n-p' if you want to confirm with a
1691 single keystroke rather than having to type \"yes\"."
1692 :group 'org-link-follow
1693 :type '(choice
1694 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1695 (const :tag "with y-or-n (faster)" y-or-n-p)
1696 (const :tag "no confirmation (dangerous)" nil)))
1697 (put 'org-confirm-shell-link-function
1698 'safe-local-variable
1699 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1701 (defcustom org-confirm-elisp-link-not-regexp ""
1702 "A regexp to skip confirmation for Elisp links."
1703 :group 'org-link-follow
1704 :version "24.1"
1705 :type 'regexp)
1707 (defconst org-file-apps-defaults-gnu
1708 '((remote . emacs)
1709 (system . mailcap)
1710 (t . mailcap))
1711 "Default file applications on a UNIX or GNU/Linux system.
1712 See `org-file-apps'.")
1714 (defconst org-file-apps-defaults-macosx
1715 '((remote . emacs)
1716 (t . "open %s")
1717 (system . "open %s")
1718 ("ps.gz" . "gv %s")
1719 ("eps.gz" . "gv %s")
1720 ("dvi" . "xdvi %s")
1721 ("fig" . "xfig %s"))
1722 "Default file applications on a MacOS X system.
1723 The system \"open\" is known as a default, but we use X11 applications
1724 for some files for which the OS does not have a good default.
1725 See `org-file-apps'.")
1727 (defconst org-file-apps-defaults-windowsnt
1728 (list
1729 '(remote . emacs)
1730 (cons t
1731 (list (if (featurep 'xemacs)
1732 'mswindows-shell-execute
1733 'w32-shell-execute)
1734 "open" 'file))
1735 (cons 'system
1736 (list (if (featurep 'xemacs)
1737 'mswindows-shell-execute
1738 'w32-shell-execute)
1739 "open" 'file)))
1740 "Default file applications on a Windows NT system.
1741 The system \"open\" is used for most files.
1742 See `org-file-apps'.")
1744 (defcustom org-file-apps
1746 (auto-mode . emacs)
1747 ("\\.mm\\'" . default)
1748 ("\\.x?html?\\'" . default)
1749 ("\\.pdf\\'" . default)
1751 "External applications for opening `file:path' items in a document.
1752 Org-mode uses system defaults for different file types, but
1753 you can use this variable to set the application for a given file
1754 extension. The entries in this list are cons cells where the car identifies
1755 files and the cdr the corresponding command. Possible values for the
1756 file identifier are
1757 \"string\" A string as a file identifier can be interpreted in different
1758 ways, depending on its contents:
1760 - Alphanumeric characters only:
1761 Match links with this file extension.
1762 Example: (\"pdf\" . \"evince %s\")
1763 to open PDFs with evince.
1765 - Regular expression: Match links where the
1766 filename matches the regexp. If you want to
1767 use groups here, use shy groups.
1769 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1770 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1771 to open *.html and *.xhtml with firefox.
1773 - Regular expression which contains (non-shy) groups:
1774 Match links where the whole link, including \"::\", and
1775 anything after that, matches the regexp.
1776 In a custom command string, %1, %2, etc. are replaced with
1777 the parts of the link that were matched by the groups.
1778 For backwards compatibility, if a command string is given
1779 that does not use any of the group matches, this case is
1780 handled identically to the second one (i.e. match against
1781 file name only).
1782 In a custom lisp form, you can access the group matches with
1783 (match-string n link).
1785 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1786 to open [[file:document.pdf::5]] with evince at page 5.
1788 `directory' Matches a directory
1789 `remote' Matches a remote file, accessible through tramp or efs.
1790 Remote files most likely should be visited through Emacs
1791 because external applications cannot handle such paths.
1792 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1793 so all files Emacs knows how to handle. Using this with
1794 command `emacs' will open most files in Emacs. Beware that this
1795 will also open html files inside Emacs, unless you add
1796 (\"html\" . default) to the list as well.
1797 t Default for files not matched by any of the other options.
1798 `system' The system command to open files, like `open' on Windows
1799 and Mac OS X, and mailcap under GNU/Linux. This is the command
1800 that will be selected if you call `C-c C-o' with a double
1801 \\[universal-argument] \\[universal-argument] prefix.
1803 Possible values for the command are:
1804 `emacs' The file will be visited by the current Emacs process.
1805 `default' Use the default application for this file type, which is the
1806 association for t in the list, most likely in the system-specific
1807 part.
1808 This can be used to overrule an unwanted setting in the
1809 system-specific variable.
1810 `system' Use the system command for opening files, like \"open\".
1811 This command is specified by the entry whose car is `system'.
1812 Most likely, the system-specific version of this variable
1813 does define this command, but you can overrule/replace it
1814 here.
1815 string A command to be executed by a shell; %s will be replaced
1816 by the path to the file.
1817 sexp A Lisp form which will be evaluated. The file path will
1818 be available in the Lisp variable `file'.
1819 For more examples, see the system specific constants
1820 `org-file-apps-defaults-macosx'
1821 `org-file-apps-defaults-windowsnt'
1822 `org-file-apps-defaults-gnu'."
1823 :group 'org-link-follow
1824 :type '(repeat
1825 (cons (choice :value ""
1826 (string :tag "Extension")
1827 (const :tag "System command to open files" system)
1828 (const :tag "Default for unrecognized files" t)
1829 (const :tag "Remote file" remote)
1830 (const :tag "Links to a directory" directory)
1831 (const :tag "Any files that have Emacs modes"
1832 auto-mode))
1833 (choice :value ""
1834 (const :tag "Visit with Emacs" emacs)
1835 (const :tag "Use default" default)
1836 (const :tag "Use the system command" system)
1837 (string :tag "Command")
1838 (sexp :tag "Lisp form")))))
1842 (defgroup org-refile nil
1843 "Options concerning refiling entries in Org-mode."
1844 :tag "Org Refile"
1845 :group 'org)
1847 (defcustom org-directory "~/org"
1848 "Directory with org files.
1849 This is just a default location to look for Org files. There is no need
1850 at all to put your files into this directory. It is only used in the
1851 following situations:
1853 1. When a remember template specifies a target file that is not an
1854 absolute path. The path will then be interpreted relative to
1855 `org-directory'
1856 2. When a remember note is filed away in an interactive way (when exiting the
1857 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1858 with `org-directory' as the default path."
1859 :group 'org-refile
1860 :group 'org-remember
1861 :type 'directory)
1863 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1864 "Default target for storing notes.
1865 Used as a fall back file for org-remember.el and org-capture.el, for
1866 templates that do not specify a target file."
1867 :group 'org-refile
1868 :group 'org-remember
1869 :type '(choice
1870 (const :tag "Default from remember-data-file" nil)
1871 file))
1873 (defcustom org-goto-interface 'outline
1874 "The default interface to be used for `org-goto'.
1875 Allowed values are:
1876 outline The interface shows an outline of the relevant file
1877 and the correct heading is found by moving through
1878 the outline or by searching with incremental search.
1879 outline-path-completion Headlines in the current buffer are offered via
1880 completion. This is the interface also used by
1881 the refile command."
1882 :group 'org-refile
1883 :type '(choice
1884 (const :tag "Outline" outline)
1885 (const :tag "Outline-path-completion" outline-path-completion)))
1887 (defcustom org-goto-max-level 5
1888 "Maximum target level when running `org-goto' with refile interface."
1889 :group 'org-refile
1890 :type 'integer)
1892 (defcustom org-reverse-note-order nil
1893 "Non-nil means store new notes at the beginning of a file or entry.
1894 When nil, new notes will be filed to the end of a file or entry.
1895 This can also be a list with cons cells of regular expressions that
1896 are matched against file names, and values."
1897 :group 'org-remember
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax
2101 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2102 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords - in this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called with
2188 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2189 in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have actually
2195 been assigned by the user, i.e. if keywords in the configuration are followed
2196 by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Each function gets as its single argument a property list, see
2240 `org-trigger-hook' for more information about this list.
2242 If any of the functions in this hook returns nil, the state change
2243 is blocked.")
2245 (defvar org-trigger-hook nil
2246 "Hook for functions that are triggered by a state change.
2248 Each function gets as its single argument a property list with at least
2249 the following elements:
2251 (:type type-of-change :position pos-at-entry-start
2252 :from old-state :to new-state)
2254 Depending on the type, more properties may be present.
2256 This mechanism is currently implemented for:
2258 TODO state changes
2259 ------------------
2260 :type todo-state-change
2261 :from previous state (keyword as a string), or nil, or a symbol
2262 'todo' or 'done', to indicate the general type of state.
2263 :to new state, like in :from")
2265 (defcustom org-enforce-todo-dependencies nil
2266 "Non-nil means undone TODO entries will block switching the parent to DONE.
2267 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2268 be blocked if any prior sibling is not yet done.
2269 Finally, if the parent is blocked because of ordered siblings of its own,
2270 the child will also be blocked.
2271 This variable needs to be set before org.el is loaded, and you need to
2272 restart Emacs after a change to make the change effective. The only way
2273 to change is while Emacs is running is through the customize interface."
2274 :set (lambda (var val)
2275 (set var val)
2276 (if val
2277 (add-hook 'org-blocker-hook
2278 'org-block-todo-from-children-or-siblings-or-parent)
2279 (remove-hook 'org-blocker-hook
2280 'org-block-todo-from-children-or-siblings-or-parent)))
2281 :group 'org-todo
2282 :type 'boolean)
2284 (defcustom org-enforce-todo-checkbox-dependencies nil
2285 "Non-nil means unchecked boxes will block switching the parent to DONE.
2286 When this is nil, checkboxes have no influence on switching TODO states.
2287 When non-nil, you first need to check off all check boxes before the TODO
2288 entry can be switched to DONE.
2289 This variable needs to be set before org.el is loaded, and you need to
2290 restart Emacs after a change to make the change effective. The only way
2291 to change is while Emacs is running is through the customize interface."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-checkboxes)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-checkboxes)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-treat-insert-todo-heading-as-state-change nil
2303 "Non-nil means inserting a TODO heading is treated as state change.
2304 So when the command \\[org-insert-todo-heading] is used, state change
2305 logging will apply if appropriate. When nil, the new TODO item will
2306 be inserted directly, and no logging will take place."
2307 :group 'org-todo
2308 :type 'boolean)
2310 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2311 "Non-nil means switching TODO states with S-cursor counts as state change.
2312 This is the default behavior. However, setting this to nil allows a
2313 convenient way to select a TODO state and bypass any logging associated
2314 with that."
2315 :group 'org-todo
2316 :type 'boolean)
2318 (defcustom org-todo-state-tags-triggers nil
2319 "Tag changes that should be triggered by TODO state changes.
2320 This is a list. Each entry is
2322 (state-change (tag . flag) .......)
2324 State-change can be a string with a state, and empty string to indicate the
2325 state that has no TODO keyword, or it can be one of the symbols `todo'
2326 or `done', meaning any not-done or done state, respectively."
2327 :group 'org-todo
2328 :group 'org-tags
2329 :type '(repeat
2330 (cons (choice :tag "When changing to"
2331 (const :tag "Not-done state" todo)
2332 (const :tag "Done state" done)
2333 (string :tag "State"))
2334 (repeat
2335 (cons :tag "Tag action"
2336 (string :tag "Tag")
2337 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2339 (defcustom org-log-done nil
2340 "Information to record when a task moves to the DONE state.
2342 Possible values are:
2344 nil Don't add anything, just change the keyword
2345 time Add a time stamp to the task
2346 note Prompt for a note and add it with template `org-log-note-headings'
2348 This option can also be set with on a per-file-basis with
2350 #+STARTUP: nologdone
2351 #+STARTUP: logdone
2352 #+STARTUP: lognotedone
2354 You can have local logging settings for a subtree by setting the LOGGING
2355 property to one or more of these keywords."
2356 :group 'org-todo
2357 :group 'org-progress
2358 :type '(choice
2359 (const :tag "No logging" nil)
2360 (const :tag "Record CLOSED timestamp" time)
2361 (const :tag "Record CLOSED timestamp with note." note)))
2363 ;; Normalize old uses of org-log-done.
2364 (cond
2365 ((eq org-log-done t) (setq org-log-done 'time))
2366 ((and (listp org-log-done) (memq 'done org-log-done))
2367 (setq org-log-done 'note)))
2369 (defcustom org-log-reschedule nil
2370 "Information to record when the scheduling date of a tasks is modified.
2372 Possible values are:
2374 nil Don't add anything, just change the date
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologreschedule
2381 #+STARTUP: logreschedule
2382 #+STARTUP: lognotereschedule"
2383 :group 'org-todo
2384 :group 'org-progress
2385 :type '(choice
2386 (const :tag "No logging" nil)
2387 (const :tag "Record timestamp" time)
2388 (const :tag "Record timestamp with note." note)))
2390 (defcustom org-log-redeadline nil
2391 "Information to record when the deadline date of a tasks is modified.
2393 Possible values are:
2395 nil Don't add anything, just change the date
2396 time Add a time stamp to the task
2397 note Prompt for a note and add it with template `org-log-note-headings'
2399 This option can also be set with on a per-file-basis with
2401 #+STARTUP: nologredeadline
2402 #+STARTUP: logredeadline
2403 #+STARTUP: lognoteredeadline
2405 You can have local logging settings for a subtree by setting the LOGGING
2406 property to one or more of these keywords."
2407 :group 'org-todo
2408 :group 'org-progress
2409 :type '(choice
2410 (const :tag "No logging" nil)
2411 (const :tag "Record timestamp" time)
2412 (const :tag "Record timestamp with note." note)))
2414 (defcustom org-log-note-clock-out nil
2415 "Non-nil means record a note when clocking out of an item.
2416 This can also be configured on a per-file basis by adding one of
2417 the following lines anywhere in the buffer:
2419 #+STARTUP: lognoteclock-out
2420 #+STARTUP: nolognoteclock-out"
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type 'boolean)
2425 (defcustom org-log-done-with-time t
2426 "Non-nil means the CLOSED time stamp will contain date and time.
2427 When nil, only the date will be recorded."
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-note-headings
2432 '((done . "CLOSING NOTE %t")
2433 (state . "State %-12s from %-12S %t")
2434 (note . "Note taken on %t")
2435 (reschedule . "Rescheduled from %S on %t")
2436 (delschedule . "Not scheduled, was %S on %t")
2437 (redeadline . "New deadline from %S on %t")
2438 (deldeadline . "Removed deadline, was %S on %t")
2439 (refile . "Refiled on %t")
2440 (clock-out . ""))
2441 "Headings for notes added to entries.
2442 The value is an alist, with the car being a symbol indicating the note
2443 context, and the cdr is the heading to be used. The heading may also be the
2444 empty string.
2445 %t in the heading will be replaced by a time stamp.
2446 %T will be an active time stamp instead the default inactive one
2447 %d will be replaced by a short-format time stamp.
2448 %D will be replaced by an active short-format time stamp.
2449 %s will be replaced by the new TODO state, in double quotes.
2450 %S will be replaced by the old TODO state, in double quotes.
2451 %u will be replaced by the user name.
2452 %U will be replaced by the full user name.
2454 In fact, it is not a good idea to change the `state' entry, because
2455 agenda log mode depends on the format of these entries."
2456 :group 'org-todo
2457 :group 'org-progress
2458 :type '(list :greedy t
2459 (cons (const :tag "Heading when closing an item" done) string)
2460 (cons (const :tag
2461 "Heading when changing todo state (todo sequence only)"
2462 state) string)
2463 (cons (const :tag "Heading when just taking a note" note) string)
2464 (cons (const :tag "Heading when clocking out" clock-out) string)
2465 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2466 (cons (const :tag "Heading when rescheduling" reschedule) string)
2467 (cons (const :tag "Heading when changing deadline" redeadline) string)
2468 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2469 (cons (const :tag "Heading when refiling" refile) string)))
2471 (unless (assq 'note org-log-note-headings)
2472 (push '(note . "%t") org-log-note-headings))
2474 (defcustom org-log-into-drawer nil
2475 "Non-nil means insert state change notes and time stamps into a drawer.
2476 When nil, state changes notes will be inserted after the headline and
2477 any scheduling and clock lines, but not inside a drawer.
2479 The value of this variable should be the name of the drawer to use.
2480 LOGBOOK is proposed as the default drawer for this purpose, you can
2481 also set this to a string to define the drawer of your choice.
2483 A value of t is also allowed, representing \"LOGBOOK\".
2485 If this variable is set, `org-log-state-notes-insert-after-drawers'
2486 will be ignored.
2488 You can set the property LOG_INTO_DRAWER to overrule this setting for
2489 a subtree."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "Not into a drawer" nil)
2494 (const :tag "LOGBOOK" t)
2495 (string :tag "Other")))
2497 (if (fboundp 'defvaralias)
2498 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2500 (defun org-log-into-drawer ()
2501 "Return the value of `org-log-into-drawer', but let properties overrule.
2502 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2503 used instead of the default value."
2504 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2505 (cond
2506 ((or (not p) (equal p "nil")) org-log-into-drawer)
2507 ((equal p "t") "LOGBOOK")
2508 (t p))))
2510 (defcustom org-log-state-notes-insert-after-drawers nil
2511 "Non-nil means insert state change notes after any drawers in entry.
2512 Only the drawers that *immediately* follow the headline and the
2513 deadline/scheduled line are skipped.
2514 When nil, insert notes right after the heading and perhaps the line
2515 with deadline/scheduling if present.
2517 This variable will have no effect if `org-log-into-drawer' is
2518 set."
2519 :group 'org-todo
2520 :group 'org-progress
2521 :type 'boolean)
2523 (defcustom org-log-states-order-reversed t
2524 "Non-nil means the latest state note will be directly after heading.
2525 When nil, the state change notes will be ordered according to time."
2526 :group 'org-todo
2527 :group 'org-progress
2528 :type 'boolean)
2530 (defcustom org-todo-repeat-to-state nil
2531 "The TODO state to which a repeater should return the repeating task.
2532 By default this is the first task in a TODO sequence, or the previous state
2533 in a TODO_TYP set. But you can specify another task here.
2534 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2535 :group 'org-todo
2536 :version "24.1"
2537 :type '(choice (const :tag "Head of sequence" nil)
2538 (string :tag "Specific state")))
2540 (defcustom org-log-repeat 'time
2541 "Non-nil means record moving through the DONE state when triggering repeat.
2542 An auto-repeating task is immediately switched back to TODO when
2543 marked DONE. If you are not logging state changes (by adding \"@\"
2544 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2545 record a closing note, there will be no record of the task moving
2546 through DONE. This variable forces taking a note anyway.
2548 nil Don't force a record
2549 time Record a time stamp
2550 note Record a note
2552 This option can also be set with on a per-file-basis with
2554 #+STARTUP: logrepeat
2555 #+STARTUP: lognoterepeat
2556 #+STARTUP: nologrepeat
2558 You can have local logging settings for a subtree by setting the LOGGING
2559 property to one or more of these keywords."
2560 :group 'org-todo
2561 :group 'org-progress
2562 :type '(choice
2563 (const :tag "Don't force a record" nil)
2564 (const :tag "Force recording the DONE state" time)
2565 (const :tag "Force recording a note with the DONE state" note)))
2568 (defgroup org-priorities nil
2569 "Priorities in Org-mode."
2570 :tag "Org Priorities"
2571 :group 'org-todo)
2573 (defcustom org-enable-priority-commands t
2574 "Non-nil means priority commands are active.
2575 When nil, these commands will be disabled, so that you never accidentally
2576 set a priority."
2577 :group 'org-priorities
2578 :type 'boolean)
2580 (defcustom org-highest-priority ?A
2581 "The highest priority of TODO items. A character like ?A, ?B etc.
2582 Must have a smaller ASCII number than `org-lowest-priority'."
2583 :group 'org-priorities
2584 :type 'character)
2586 (defcustom org-lowest-priority ?C
2587 "The lowest priority of TODO items. A character like ?A, ?B etc.
2588 Must have a larger ASCII number than `org-highest-priority'."
2589 :group 'org-priorities
2590 :type 'character)
2592 (defcustom org-default-priority ?B
2593 "The default priority of TODO items.
2594 This is the priority an item gets if no explicit priority is given.
2595 When starting to cycle on an empty priority the first step in the cycle
2596 depends on `org-priority-start-cycle-with-default'. The resulting first
2597 step priority must not exceed the range from `org-highest-priority' to
2598 `org-lowest-priority' which means that `org-default-priority' has to be
2599 in this range exclusive or inclusive the range boundaries. Else the
2600 first step refuses to set the default and the second will fall back
2601 to (depending on the command used) the highest or lowest priority."
2602 :group 'org-priorities
2603 :type 'character)
2605 (defcustom org-priority-start-cycle-with-default t
2606 "Non-nil means start with default priority when starting to cycle.
2607 When this is nil, the first step in the cycle will be (depending on the
2608 command used) one higher or lower than the default priority.
2609 See also `org-default-priority'."
2610 :group 'org-priorities
2611 :type 'boolean)
2613 (defcustom org-get-priority-function nil
2614 "Function to extract the priority from a string.
2615 The string is normally the headline. If this is nil Org computes the
2616 priority from the priority cookie like [#A] in the headline. It returns
2617 an integer, increasing by 1000 for each priority level.
2618 The user can set a different function here, which should take a string
2619 as an argument and return the numeric priority."
2620 :group 'org-priorities
2621 :version "24.1"
2622 :type 'function)
2624 (defgroup org-time nil
2625 "Options concerning time stamps and deadlines in Org-mode."
2626 :tag "Org Time"
2627 :group 'org)
2629 (defcustom org-insert-labeled-timestamps-at-point nil
2630 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2631 When nil, these labeled time stamps are forces into the second line of an
2632 entry, just after the headline. When scheduling from the global TODO list,
2633 the time stamp will always be forced into the second line."
2634 :group 'org-time
2635 :type 'boolean)
2637 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2638 "Formats for `format-time-string' which are used for time stamps.
2639 It is not recommended to change this constant.")
2641 (defcustom org-time-stamp-rounding-minutes '(0 5)
2642 "Number of minutes to round time stamps to.
2643 These are two values, the first applies when first creating a time stamp.
2644 The second applies when changing it with the commands `S-up' and `S-down'.
2645 When changing the time stamp, this means that it will change in steps
2646 of N minutes, as given by the second value.
2648 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2649 numbers should be factors of 60, so for example 5, 10, 15.
2651 When this is larger than 1, you can still force an exact time stamp by using
2652 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2653 and by using a prefix arg to `S-up/down' to specify the exact number
2654 of minutes to shift."
2655 :group 'org-time
2656 :get #'(lambda (var) ; Make sure both elements are there
2657 (if (integerp (default-value var))
2658 (list (default-value var) 5)
2659 (default-value var)))
2660 :type '(list
2661 (integer :tag "when inserting times")
2662 (integer :tag "when modifying times")))
2664 ;; Normalize old customizations of this variable.
2665 (when (integerp org-time-stamp-rounding-minutes)
2666 (setq org-time-stamp-rounding-minutes
2667 (list org-time-stamp-rounding-minutes
2668 org-time-stamp-rounding-minutes)))
2670 (defcustom org-display-custom-times nil
2671 "Non-nil means overlay custom formats over all time stamps.
2672 The formats are defined through the variable `org-time-stamp-custom-formats'.
2673 To turn this on on a per-file basis, insert anywhere in the file:
2674 #+STARTUP: customtime"
2675 :group 'org-time
2676 :set 'set-default
2677 :type 'sexp)
2678 (make-variable-buffer-local 'org-display-custom-times)
2680 (defcustom org-time-stamp-custom-formats
2681 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2682 "Custom formats for time stamps. See `format-time-string' for the syntax.
2683 These are overlaid over the default ISO format if the variable
2684 `org-display-custom-times' is set. Time like %H:%M should be at the
2685 end of the second format. The custom formats are also honored by export
2686 commands, if custom time display is turned on at the time of export."
2687 :group 'org-time
2688 :type 'sexp)
2690 (defun org-time-stamp-format (&optional long inactive)
2691 "Get the right format for a time string."
2692 (let ((f (if long (cdr org-time-stamp-formats)
2693 (car org-time-stamp-formats))))
2694 (if inactive
2695 (concat "[" (substring f 1 -1) "]")
2696 f)))
2698 (defcustom org-time-clocksum-format "%d:%02d"
2699 "The format string used when creating CLOCKSUM lines.
2700 This is also used when org-mode generates a time duration."
2701 :group 'org-time
2702 :type 'string)
2704 (defcustom org-time-clocksum-use-fractional nil
2705 "If non-nil, \\[org-clock-display] uses fractional times.
2706 org-mode generates a time duration."
2707 :group 'org-time
2708 :type 'boolean)
2710 (defcustom org-time-clocksum-fractional-format "%.2f"
2711 "The format string used when creating CLOCKSUM lines, or when
2712 org-mode generates a time duration."
2713 :group 'org-time
2714 :type 'string)
2716 (defcustom org-deadline-warning-days 14
2717 "No. of days before expiration during which a deadline becomes active.
2718 This variable governs the display in sparse trees and in the agenda.
2719 When 0 or negative, it means use this number (the absolute value of it)
2720 even if a deadline has a different individual lead time specified.
2722 Custom commands can set this variable in the options section."
2723 :group 'org-time
2724 :group 'org-agenda-daily/weekly
2725 :type 'integer)
2727 (defcustom org-read-date-prefer-future t
2728 "Non-nil means assume future for incomplete date input from user.
2729 This affects the following situations:
2730 1. The user gives a month but not a year.
2731 For example, if it is April and you enter \"feb 2\", this will be read
2732 as Feb 2, *next* year. \"May 5\", however, will be this year.
2733 2. The user gives a day, but no month.
2734 For example, if today is the 15th, and you enter \"3\", Org-mode will
2735 read this as the third of *next* month. However, if you enter \"17\",
2736 it will be considered as *this* month.
2738 If you set this variable to the symbol `time', then also the following
2739 will work:
2741 3. If the user gives a time, but no day. If the time is before now,
2742 to will be interpreted as tomorrow.
2744 Currently none of this works for ISO week specifications.
2746 When this option is nil, the current day, month and year will always be
2747 used as defaults.
2749 See also `org-agenda-jump-prefer-future'."
2750 :group 'org-time
2751 :type '(choice
2752 (const :tag "Never" nil)
2753 (const :tag "Check month and day" t)
2754 (const :tag "Check month, day, and time" time)))
2756 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2757 "Should the agenda jump command prefer the future for incomplete dates?
2758 The default is to do the same as configured in `org-read-date-prefer-future'.
2759 But you can also set a deviating value here.
2760 This may t or nil, or the symbol `org-read-date-prefer-future'."
2761 :group 'org-agenda
2762 :group 'org-time
2763 :version "24.1"
2764 :type '(choice
2765 (const :tag "Use org-read-date-prefer-future"
2766 org-read-date-prefer-future)
2767 (const :tag "Never" nil)
2768 (const :tag "Always" t)))
2770 (defcustom org-read-date-force-compatible-dates t
2771 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2773 Depending on the system Emacs is running on, certain dates cannot
2774 be represented with the type used internally to represent time.
2775 Dates between 1970-1-1 and 2038-1-1 can always be represented
2776 correctly. Some systems allow for earlier dates, some for later,
2777 some for both. One way to find out it to insert any date into an
2778 Org buffer, putting the cursor on the year and hitting S-up and
2779 S-down to test the range.
2781 When this variable is set to t, the date/time prompt will not let
2782 you specify dates outside the 1970-2037 range, so it is certain that
2783 these dates will work in whatever version of Emacs you are
2784 running, and also that you can move a file from one Emacs implementation
2785 to another. WHenever Org is forcing the year for you, it will display
2786 a message and beep.
2788 When this variable is nil, Org will check if the date is
2789 representable in the specific Emacs implementation you are using.
2790 If not, it will force a year, usually the current year, and beep
2791 to remind you. Currently this setting is not recommended because
2792 the likelihood that you will open your Org files in an Emacs that
2793 has limited date range is not negligible.
2795 A workaround for this problem is to use diary sexp dates for time
2796 stamps outside of this range."
2797 :group 'org-time
2798 :version "24.1"
2799 :type 'boolean)
2801 (defcustom org-read-date-display-live t
2802 "Non-nil means display current interpretation of date prompt live.
2803 This display will be in an overlay, in the minibuffer."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defcustom org-read-date-popup-calendar t
2808 "Non-nil means pop up a calendar when prompting for a date.
2809 In the calendar, the date can be selected with mouse-1. However, the
2810 minibuffer will also be active, and you can simply enter the date as well.
2811 When nil, only the minibuffer will be available."
2812 :group 'org-time
2813 :type 'boolean)
2814 (if (fboundp 'defvaralias)
2815 (defvaralias 'org-popup-calendar-for-date-prompt
2816 'org-read-date-popup-calendar))
2818 (defcustom org-read-date-minibuffer-setup-hook nil
2819 "Hook to be used to set up keys for the date/time interface.
2820 Add key definitions to `minibuffer-local-map', which will be a temporary
2821 copy."
2822 :group 'org-time
2823 :type 'hook)
2825 (defcustom org-extend-today-until 0
2826 "The hour when your day really ends. Must be an integer.
2827 This has influence for the following applications:
2828 - When switching the agenda to \"today\". It it is still earlier than
2829 the time given here, the day recognized as TODAY is actually yesterday.
2830 - When a date is read from the user and it is still before the time given
2831 here, the current date and time will be assumed to be yesterday, 23:59.
2832 Also, timestamps inserted in remember templates follow this rule.
2834 IMPORTANT: This is a feature whose implementation is and likely will
2835 remain incomplete. Really, it is only here because past midnight seems to
2836 be the favorite working time of John Wiegley :-)"
2837 :group 'org-time
2838 :type 'integer)
2840 (defcustom org-use-effective-time nil
2841 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2842 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2843 \"effective time\" of any timestamps between midnight and 8am will be
2844 23:59 of the previous day."
2845 :group 'boolean
2846 :version "24.1"
2847 :type 'integer)
2849 (defcustom org-edit-timestamp-down-means-later nil
2850 "Non-nil means S-down will increase the time in a time stamp.
2851 When nil, S-up will increase."
2852 :group 'org-time
2853 :type 'boolean)
2855 (defcustom org-calendar-follow-timestamp-change t
2856 "Non-nil means make the calendar window follow timestamp changes.
2857 When a timestamp is modified and the calendar window is visible, it will be
2858 moved to the new date."
2859 :group 'org-time
2860 :type 'boolean)
2862 (defgroup org-tags nil
2863 "Options concerning tags in Org-mode."
2864 :tag "Org Tags"
2865 :group 'org)
2867 (defcustom org-tag-alist nil
2868 "List of tags allowed in Org-mode files.
2869 When this list is nil, Org-mode will base TAG input on what is already in the
2870 buffer.
2871 The value of this variable is an alist, the car of each entry must be a
2872 keyword as a string, the cdr may be a character that is used to select
2873 that tag through the fast-tag-selection interface.
2874 See the manual for details."
2875 :group 'org-tags
2876 :type '(repeat
2877 (choice
2878 (cons (string :tag "Tag name")
2879 (character :tag "Access char"))
2880 (list :tag "Start radio group"
2881 (const :startgroup)
2882 (option (string :tag "Group description")))
2883 (list :tag "End radio group"
2884 (const :endgroup)
2885 (option (string :tag "Group description")))
2886 (const :tag "New line" (:newline)))))
2888 (defcustom org-tag-persistent-alist nil
2889 "List of tags that will always appear in all Org-mode files.
2890 This is in addition to any in buffer settings or customizations
2891 of `org-tag-alist'.
2892 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2893 The value of this variable is an alist, the car of each entry must be a
2894 keyword as a string, the cdr may be a character that is used to select
2895 that tag through the fast-tag-selection interface.
2896 See the manual for details.
2897 To disable these tags on a per-file basis, insert anywhere in the file:
2898 #+STARTUP: noptag"
2899 :group 'org-tags
2900 :type '(repeat
2901 (choice
2902 (cons (string :tag "Tag name")
2903 (character :tag "Access char"))
2904 (const :tag "Start radio group" (:startgroup))
2905 (const :tag "End radio group" (:endgroup))
2906 (const :tag "New line" (:newline)))))
2908 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2909 "If non-nil, always offer completion for all tags of all agenda files.
2910 Instead of customizing this variable directly, you might want to
2911 set it locally for capture buffers, because there no list of
2912 tags in that file can be created dynamically (there are none).
2914 (add-hook 'org-capture-mode-hook
2915 (lambda ()
2916 (set (make-local-variable
2917 'org-complete-tags-always-offer-all-agenda-tags)
2918 t)))"
2919 :group 'org-tags
2920 :version "24.1"
2921 :type 'boolean)
2923 (defvar org-file-tags nil
2924 "List of tags that can be inherited by all entries in the file.
2925 The tags will be inherited if the variable `org-use-tag-inheritance'
2926 says they should be.
2927 This variable is populated from #+FILETAGS lines.")
2929 (defcustom org-use-fast-tag-selection 'auto
2930 "Non-nil means use fast tag selection scheme.
2931 This is a special interface to select and deselect tags with single keys.
2932 When nil, fast selection is never used.
2933 When the symbol `auto', fast selection is used if and only if selection
2934 characters for tags have been configured, either through the variable
2935 `org-tag-alist' or through a #+TAGS line in the buffer.
2936 When t, fast selection is always used and selection keys are assigned
2937 automatically if necessary."
2938 :group 'org-tags
2939 :type '(choice
2940 (const :tag "Always" t)
2941 (const :tag "Never" nil)
2942 (const :tag "When selection characters are configured" 'auto)))
2944 (defcustom org-fast-tag-selection-single-key nil
2945 "Non-nil means fast tag selection exits after first change.
2946 When nil, you have to press RET to exit it.
2947 During fast tag selection, you can toggle this flag with `C-c'.
2948 This variable can also have the value `expert'. In this case, the window
2949 displaying the tags menu is not even shown, until you press C-c again."
2950 :group 'org-tags
2951 :type '(choice
2952 (const :tag "No" nil)
2953 (const :tag "Yes" t)
2954 (const :tag "Expert" expert)))
2956 (defvar org-fast-tag-selection-include-todo nil
2957 "Non-nil means fast tags selection interface will also offer TODO states.
2958 This is an undocumented feature, you should not rely on it.")
2960 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2961 "The column to which tags should be indented in a headline.
2962 If this number is positive, it specifies the column. If it is negative,
2963 it means that the tags should be flushright to that column. For example,
2964 -80 works well for a normal 80 character screen.
2965 When 0, place tags directly after headline text, with only one space in
2966 between."
2967 :group 'org-tags
2968 :type 'integer)
2970 (defcustom org-auto-align-tags t
2971 "Non-nil keeps tags aligned when modifying headlines.
2972 Some operations (i.e. demoting) change the length of a headline and
2973 therefore shift the tags around. With this option turned on, after
2974 each such operation the tags are again aligned to `org-tags-column'."
2975 :group 'org-tags
2976 :type 'boolean)
2978 (defcustom org-use-tag-inheritance t
2979 "Non-nil means tags in levels apply also for sublevels.
2980 When nil, only the tags directly given in a specific line apply there.
2981 This may also be a list of tags that should be inherited, or a regexp that
2982 matches tags that should be inherited. Additional control is possible
2983 with the variable `org-tags-exclude-from-inheritance' which gives an
2984 explicit list of tags to be excluded from inheritance., even if the value of
2985 `org-use-tag-inheritance' would select it for inheritance.
2987 If this option is t, a match early-on in a tree can lead to a large
2988 number of matches in the subtree when constructing the agenda or creating
2989 a sparse tree. If you only want to see the first match in a tree during
2990 a search, check out the variable `org-tags-match-list-sublevels'."
2991 :group 'org-tags
2992 :type '(choice
2993 (const :tag "Not" nil)
2994 (const :tag "Always" t)
2995 (repeat :tag "Specific tags" (string :tag "Tag"))
2996 (regexp :tag "Tags matched by regexp")))
2998 (defcustom org-tags-exclude-from-inheritance nil
2999 "List of tags that should never be inherited.
3000 This is a way to exclude a few tags from inheritance. For way to do
3001 the opposite, to actively allow inheritance for selected tags,
3002 see the variable `org-use-tag-inheritance'."
3003 :group 'org-tags
3004 :type '(repeat (string :tag "Tag")))
3006 (defun org-tag-inherit-p (tag)
3007 "Check if TAG is one that should be inherited."
3008 (cond
3009 ((member tag org-tags-exclude-from-inheritance) nil)
3010 ((eq org-use-tag-inheritance t) t)
3011 ((not org-use-tag-inheritance) nil)
3012 ((stringp org-use-tag-inheritance)
3013 (string-match org-use-tag-inheritance tag))
3014 ((listp org-use-tag-inheritance)
3015 (member tag org-use-tag-inheritance))
3016 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3018 (defcustom org-tags-match-list-sublevels t
3019 "Non-nil means list also sublevels of headlines matching a search.
3020 This variable applies to tags/property searches, and also to stuck
3021 projects because this search is based on a tags match as well.
3023 When set to the symbol `indented', sublevels are indented with
3024 leading dots.
3026 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3027 the sublevels of a headline matching a tag search often also match
3028 the same search. Listing all of them can create very long lists.
3029 Setting this variable to nil causes subtrees of a match to be skipped.
3031 This variable is semi-obsolete and probably should always be true. It
3032 is better to limit inheritance to certain tags using the variables
3033 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3034 :group 'org-tags
3035 :type '(choice
3036 (const :tag "No, don't list them" nil)
3037 (const :tag "Yes, do list them" t)
3038 (const :tag "List them, indented with leading dots" indented)))
3040 (defcustom org-tags-sort-function nil
3041 "When set, tags are sorted using this function as a comparator."
3042 :group 'org-tags
3043 :type '(choice
3044 (const :tag "No sorting" nil)
3045 (const :tag "Alphabetical" string<)
3046 (const :tag "Reverse alphabetical" string>)
3047 (function :tag "Custom function" nil)))
3049 (defvar org-tags-history nil
3050 "History of minibuffer reads for tags.")
3051 (defvar org-last-tags-completion-table nil
3052 "The last used completion table for tags.")
3053 (defvar org-after-tags-change-hook nil
3054 "Hook that is run after the tags in a line have changed.")
3056 (defgroup org-properties nil
3057 "Options concerning properties in Org-mode."
3058 :tag "Org Properties"
3059 :group 'org)
3061 (defcustom org-property-format "%-10s %s"
3062 "How property key/value pairs should be formatted by `indent-line'.
3063 When `indent-line' hits a property definition, it will format the line
3064 according to this format, mainly to make sure that the values are
3065 lined-up with respect to each other."
3066 :group 'org-properties
3067 :type 'string)
3069 (defcustom org-properties-postprocess-alist nil
3070 "Alist of properties and functions to adjust inserted values.
3071 Elements of this alist must be of the form
3073 ([string] [function])
3075 where [string] must be a property name and [function] must be a
3076 lambda expression: this lambda expression must take one argument,
3077 the value to adjust, and return the new value as a string.
3079 For example, this element will allow the property \"Remaining\"
3080 to be updated wrt the relation between the \"Effort\" property
3081 and the clock summary:
3083 ((\"Remaining\" (lambda(value)
3084 (let ((clocksum (org-clock-sum-current-item))
3085 (effort (org-duration-string-to-minutes
3086 (org-entry-get (point) \"Effort\"))))
3087 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3088 :group 'org-properties
3089 :version "24.1"
3090 :type 'alist)
3092 (defcustom org-use-property-inheritance nil
3093 "Non-nil means properties apply also for sublevels.
3095 This setting is chiefly used during property searches. Turning it on can
3096 cause significant overhead when doing a search, which is why it is not
3097 on by default.
3099 When nil, only the properties directly given in the current entry count.
3100 When t, every property is inherited. The value may also be a list of
3101 properties that should have inheritance, or a regular expression matching
3102 properties that should be inherited.
3104 However, note that some special properties use inheritance under special
3105 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3106 and the properties ending in \"_ALL\" when they are used as descriptor
3107 for valid values of a property.
3109 Note for programmers:
3110 When querying an entry with `org-entry-get', you can control if inheritance
3111 should be used. By default, `org-entry-get' looks only at the local
3112 properties. You can request inheritance by setting the inherit argument
3113 to t (to force inheritance) or to `selective' (to respect the setting
3114 in this variable)."
3115 :group 'org-properties
3116 :type '(choice
3117 (const :tag "Not" nil)
3118 (const :tag "Always" t)
3119 (repeat :tag "Specific properties" (string :tag "Property"))
3120 (regexp :tag "Properties matched by regexp")))
3122 (defun org-property-inherit-p (property)
3123 "Check if PROPERTY is one that should be inherited."
3124 (cond
3125 ((eq org-use-property-inheritance t) t)
3126 ((not org-use-property-inheritance) nil)
3127 ((stringp org-use-property-inheritance)
3128 (string-match org-use-property-inheritance property))
3129 ((listp org-use-property-inheritance)
3130 (member property org-use-property-inheritance))
3131 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3133 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3134 "The default column format, if no other format has been defined.
3135 This variable can be set on the per-file basis by inserting a line
3137 #+COLUMNS: %25ITEM ....."
3138 :group 'org-properties
3139 :type 'string)
3141 (defcustom org-columns-ellipses ".."
3142 "The ellipses to be used when a field in column view is truncated.
3143 When this is the empty string, as many characters as possible are shown,
3144 but then there will be no visual indication that the field has been truncated.
3145 When this is a string of length N, the last N characters of a truncated
3146 field are replaced by this string. If the column is narrower than the
3147 ellipses string, only part of the ellipses string will be shown."
3148 :group 'org-properties
3149 :type 'string)
3151 (defcustom org-columns-modify-value-for-display-function nil
3152 "Function that modifies values for display in column view.
3153 For example, it can be used to cut out a certain part from a time stamp.
3154 The function must take 2 arguments:
3156 column-title The title of the column (*not* the property name)
3157 value The value that should be modified.
3159 The function should return the value that should be displayed,
3160 or nil if the normal value should be used."
3161 :group 'org-properties
3162 :type 'function)
3164 (defcustom org-effort-property "Effort"
3165 "The property that is being used to keep track of effort estimates.
3166 Effort estimates given in this property need to have the format H:MM."
3167 :group 'org-properties
3168 :group 'org-progress
3169 :type '(string :tag "Property"))
3171 (defconst org-global-properties-fixed
3172 '(("VISIBILITY_ALL" . "folded children content all")
3173 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3174 "List of property/value pairs that can be inherited by any entry.
3176 These are fixed values, for the preset properties. The user variable
3177 that can be used to add to this list is `org-global-properties'.
3179 The entries in this list are cons cells where the car is a property
3180 name and cdr is a string with the value. If the value represents
3181 multiple items like an \"_ALL\" property, separate the items by
3182 spaces.")
3184 (defcustom org-global-properties nil
3185 "List of property/value pairs that can be inherited by any entry.
3187 This list will be combined with the constant `org-global-properties-fixed'.
3189 The entries in this list are cons cells where the car is a property
3190 name and cdr is a string with the value.
3192 You can set buffer-local values for the same purpose in the variable
3193 `org-file-properties' this by adding lines like
3195 #+PROPERTY: NAME VALUE"
3196 :group 'org-properties
3197 :type '(repeat
3198 (cons (string :tag "Property")
3199 (string :tag "Value"))))
3201 (defvar org-file-properties nil
3202 "List of property/value pairs that can be inherited by any entry.
3203 Valid for the current buffer.
3204 This variable is populated from #+PROPERTY lines.")
3205 (make-variable-buffer-local 'org-file-properties)
3207 (defgroup org-agenda nil
3208 "Options concerning agenda views in Org-mode."
3209 :tag "Org Agenda"
3210 :group 'org)
3212 (defvar org-category nil
3213 "Variable used by org files to set a category for agenda display.
3214 Such files should use a file variable to set it, for example
3216 # -*- mode: org; org-category: \"ELisp\"
3218 or contain a special line
3220 #+CATEGORY: ELisp
3222 If the file does not specify a category, then file's base name
3223 is used instead.")
3224 (make-variable-buffer-local 'org-category)
3225 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3227 (defcustom org-agenda-files nil
3228 "The files to be used for agenda display.
3229 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3230 \\[org-remove-file]. You can also use customize to edit the list.
3232 If an entry is a directory, all files in that directory that are matched by
3233 `org-agenda-file-regexp' will be part of the file list.
3235 If the value of the variable is not a list but a single file name, then
3236 the list of agenda files is actually stored and maintained in that file, one
3237 agenda file per line. In this file paths can be given relative to
3238 `org-directory'. Tilde expansion and environment variable substitution
3239 are also made."
3240 :group 'org-agenda
3241 :type '(choice
3242 (repeat :tag "List of files and directories" file)
3243 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3245 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3246 "Regular expression to match files for `org-agenda-files'.
3247 If any element in the list in that variable contains a directory instead
3248 of a normal file, all files in that directory that are matched by this
3249 regular expression will be included."
3250 :group 'org-agenda
3251 :type 'regexp)
3253 (defcustom org-agenda-text-search-extra-files nil
3254 "List of extra files to be searched by text search commands.
3255 These files will be search in addition to the agenda files by the
3256 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3257 Note that these files will only be searched for text search commands,
3258 not for the other agenda views like todo lists, tag searches or the weekly
3259 agenda. This variable is intended to list notes and possibly archive files
3260 that should also be searched by these two commands.
3261 In fact, if the first element in the list is the symbol `agenda-archives',
3262 than all archive files of all agenda files will be added to the search
3263 scope."
3264 :group 'org-agenda
3265 :type '(set :greedy t
3266 (const :tag "Agenda Archives" agenda-archives)
3267 (repeat :inline t (file))))
3269 (if (fboundp 'defvaralias)
3270 (defvaralias 'org-agenda-multi-occur-extra-files
3271 'org-agenda-text-search-extra-files))
3273 (defcustom org-agenda-skip-unavailable-files nil
3274 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3275 A nil value means to remove them, after a query, from the list."
3276 :group 'org-agenda
3277 :type 'boolean)
3279 (defcustom org-calendar-to-agenda-key [?c]
3280 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3281 The command `org-calendar-goto-agenda' will be bound to this key. The
3282 default is the character `c' because then `c' can be used to switch back and
3283 forth between agenda and calendar."
3284 :group 'org-agenda
3285 :type 'sexp)
3287 (defcustom org-calendar-agenda-action-key [?k]
3288 "The key to be installed in `calendar-mode-map' for agenda-action.
3289 The command `org-agenda-action' will be bound to this key. The
3290 default is the character `k' because we use the same key in the agenda."
3291 :group 'org-agenda
3292 :type 'sexp)
3294 (defcustom org-calendar-insert-diary-entry-key [?i]
3295 "The key to be installed in `calendar-mode-map' for adding diary entries.
3296 This option is irrelevant until `org-agenda-diary-file' has been configured
3297 to point to an Org-mode file. When that is the case, the command
3298 `org-agenda-diary-entry' will be bound to the key given here, by default
3299 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3300 if you want to continue doing this, you need to change this to a different
3301 key."
3302 :group 'org-agenda
3303 :type 'sexp)
3305 (defcustom org-agenda-diary-file 'diary-file
3306 "File to which to add new entries with the `i' key in agenda and calendar.
3307 When this is the symbol `diary-file', the functionality in the Emacs
3308 calendar will be used to add entries to the `diary-file'. But when this
3309 points to a file, `org-agenda-diary-entry' will be used instead."
3310 :group 'org-agenda
3311 :type '(choice
3312 (const :tag "The standard Emacs diary file" diary-file)
3313 (file :tag "Special Org file diary entries")))
3315 (eval-after-load "calendar"
3316 '(progn
3317 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3318 'org-calendar-goto-agenda)
3319 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3320 'org-agenda-action)
3321 (add-hook 'calendar-mode-hook
3322 (lambda ()
3323 (unless (eq org-agenda-diary-file 'diary-file)
3324 (define-key calendar-mode-map
3325 org-calendar-insert-diary-entry-key
3326 'org-agenda-diary-entry))))))
3328 (defgroup org-latex nil
3329 "Options for embedding LaTeX code into Org-mode."
3330 :tag "Org LaTeX"
3331 :group 'org)
3333 (defcustom org-format-latex-options
3334 '(:foreground default :background default :scale 1.0
3335 :html-foreground "Black" :html-background "Transparent"
3336 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3337 "Options for creating images from LaTeX fragments.
3338 This is a property list with the following properties:
3339 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3340 `default' means use the foreground of the default face.
3341 :background the background color, or \"Transparent\".
3342 `default' means use the background of the default face.
3343 :scale a scaling factor for the size of the images, to get more pixels
3344 :html-foreground, :html-background, :html-scale
3345 the same numbers for HTML export.
3346 :matchers a list indicating which matchers should be used to
3347 find LaTeX fragments. Valid members of this list are:
3348 \"begin\" find environments
3349 \"$1\" find single characters surrounded by $.$
3350 \"$\" find math expressions surrounded by $...$
3351 \"$$\" find math expressions surrounded by $$....$$
3352 \"\\(\" find math expressions surrounded by \\(...\\)
3353 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3354 :group 'org-latex
3355 :type 'plist)
3357 (defcustom org-format-latex-signal-error t
3358 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3359 When nil, just push out a message."
3360 :group 'org-latex
3361 :version "24.1"
3362 :type 'boolean)
3364 (defcustom org-latex-to-mathml-jar-file nil
3365 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3366 Use this to specify additional executable file say a jar file.
3368 When using MathToWeb as the converter, specify the full-path to
3369 your mathtoweb.jar file."
3370 :group 'org-latex
3371 :version "24.1"
3372 :type '(choice
3373 (const :tag "None" nil)
3374 (file :tag "JAR file" :must-match t)))
3376 (defcustom org-latex-to-mathml-convert-command nil
3377 "Command to convert LaTeX fragments to MathML.
3378 Replace format-specifiers in the command as noted below and use
3379 `shell-command' to convert LaTeX to MathML.
3380 %j: Executable file in fully expanded form as specified by
3381 `org-latex-to-mathml-jar-file'.
3382 %I: Input LaTeX file in fully expanded form
3383 %o: Output MathML file
3384 This command is used by `org-create-math-formula'.
3386 When using MathToWeb as the converter, set this to
3387 \"java -jar %j -unicode -force -df %o %I\"."
3388 :group 'org-latex
3389 :version "24.1"
3390 :type '(choice
3391 (const :tag "None" nil)
3392 (string :tag "\nShell command")))
3394 (defun org-format-latex-mathml-available-p ()
3395 "Return t if `org-latex-to-mathml-convert-command' is usable."
3396 (save-match-data
3397 (when (and (boundp 'org-latex-to-mathml-convert-command)
3398 org-latex-to-mathml-convert-command)
3399 (let ((executable (car (split-string
3400 org-latex-to-mathml-convert-command))))
3401 (when (executable-find executable)
3402 (if (string-match
3403 "%j" org-latex-to-mathml-convert-command)
3404 (file-readable-p org-latex-to-mathml-jar-file)
3405 t))))))
3407 (defcustom org-format-latex-header "\\documentclass{article}
3408 \\usepackage[usenames]{color}
3409 \\usepackage{amsmath}
3410 \\usepackage[mathscr]{eucal}
3411 \\pagestyle{empty} % do not remove
3412 \[PACKAGES]
3413 \[DEFAULT-PACKAGES]
3414 % The settings below are copied from fullpage.sty
3415 \\setlength{\\textwidth}{\\paperwidth}
3416 \\addtolength{\\textwidth}{-3cm}
3417 \\setlength{\\oddsidemargin}{1.5cm}
3418 \\addtolength{\\oddsidemargin}{-2.54cm}
3419 \\setlength{\\evensidemargin}{\\oddsidemargin}
3420 \\setlength{\\textheight}{\\paperheight}
3421 \\addtolength{\\textheight}{-\\headheight}
3422 \\addtolength{\\textheight}{-\\headsep}
3423 \\addtolength{\\textheight}{-\\footskip}
3424 \\addtolength{\\textheight}{-3cm}
3425 \\setlength{\\topmargin}{1.5cm}
3426 \\addtolength{\\topmargin}{-2.54cm}"
3427 "The document header used for processing LaTeX fragments.
3428 It is imperative that this header make sure that no page number
3429 appears on the page. The package defined in the variables
3430 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3431 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3432 will be appended."
3433 :group 'org-latex
3434 :type 'string)
3436 (defvar org-format-latex-header-extra nil)
3438 (defun org-set-packages-alist (var val)
3439 "Set the packages alist and make sure it has 3 elements per entry."
3440 (set var (mapcar (lambda (x)
3441 (if (and (consp x) (= (length x) 2))
3442 (list (car x) (nth 1 x) t)
3444 val)))
3446 (defun org-get-packages-alist (var)
3448 "Get the packages alist and make sure it has 3 elements per entry."
3449 (mapcar (lambda (x)
3450 (if (and (consp x) (= (length x) 2))
3451 (list (car x) (nth 1 x) t)
3453 (default-value var)))
3455 ;; The following variables are defined here because is it also used
3456 ;; when formatting latex fragments. Originally it was part of the
3457 ;; LaTeX exporter, which is why the name includes "export".
3458 (defcustom org-export-latex-default-packages-alist
3459 '(("AUTO" "inputenc" t)
3460 ("T1" "fontenc" t)
3461 ("" "fixltx2e" nil)
3462 ("" "graphicx" t)
3463 ("" "longtable" nil)
3464 ("" "float" nil)
3465 ("" "wrapfig" nil)
3466 ("" "soul" t)
3467 ("" "textcomp" t)
3468 ("" "marvosym" t)
3469 ("" "wasysym" t)
3470 ("" "latexsym" t)
3471 ("" "amssymb" t)
3472 ("" "hyperref" nil)
3473 "\\tolerance=1000"
3475 "Alist of default packages to be inserted in the header.
3476 Change this only if one of the packages here causes an incompatibility
3477 with another package you are using.
3478 The packages in this list are needed by one part or another of Org-mode
3479 to function properly.
3481 - inputenc, fontenc: for basic font and character selection
3482 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3483 for interpreting the entities in `org-entities'. You can skip some of these
3484 packages if you don't use any of the symbols in it.
3485 - graphicx: for including images
3486 - float, wrapfig: for figure placement
3487 - longtable: for long tables
3488 - hyperref: for cross references
3490 Therefore you should not modify this variable unless you know what you
3491 are doing. The one reason to change it anyway is that you might be loading
3492 some other package that conflicts with one of the default packages.
3493 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3494 If SNIPPET-FLAG is t, the package also needs to be included when
3495 compiling LaTeX snippets into images for inclusion into HTML."
3496 :group 'org-export-latex
3497 :set 'org-set-packages-alist
3498 :get 'org-get-packages-alist
3499 :version "24.1"
3500 :type '(repeat
3501 (choice
3502 (list :tag "options/package pair"
3503 (string :tag "options")
3504 (string :tag "package")
3505 (boolean :tag "Snippet"))
3506 (string :tag "A line of LaTeX"))))
3508 (defcustom org-export-latex-packages-alist nil
3509 "Alist of packages to be inserted in every LaTeX header.
3510 These will be inserted after `org-export-latex-default-packages-alist'.
3511 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3512 SNIPPET-FLAG, when t, indicates that this package is also needed when
3513 turning LaTeX snippets into images for inclusion into HTML.
3514 Make sure that you only list packages here which:
3515 - you want in every file
3516 - do not conflict with the default packages in
3517 `org-export-latex-default-packages-alist'
3518 - do not conflict with the setup in `org-format-latex-header'."
3519 :group 'org-export-latex
3520 :set 'org-set-packages-alist
3521 :get 'org-get-packages-alist
3522 :type '(repeat
3523 (choice
3524 (list :tag "options/package pair"
3525 (string :tag "options")
3526 (string :tag "package")
3527 (boolean :tag "Snippet"))
3528 (string :tag "A line of LaTeX"))))
3531 (defgroup org-appearance nil
3532 "Settings for Org-mode appearance."
3533 :tag "Org Appearance"
3534 :group 'org)
3536 (defcustom org-level-color-stars-only nil
3537 "Non-nil means fontify only the stars in each headline.
3538 When nil, the entire headline is fontified.
3539 Changing it requires restart of `font-lock-mode' to become effective
3540 also in regions already fontified."
3541 :group 'org-appearance
3542 :type 'boolean)
3544 (defcustom org-hide-leading-stars nil
3545 "Non-nil means hide the first N-1 stars in a headline.
3546 This works by using the face `org-hide' for these stars. This
3547 face is white for a light background, and black for a dark
3548 background. You may have to customize the face `org-hide' to
3549 make this work.
3550 Changing it requires restart of `font-lock-mode' to become effective
3551 also in regions already fontified.
3552 You may also set this on a per-file basis by adding one of the following
3553 lines to the buffer:
3555 #+STARTUP: hidestars
3556 #+STARTUP: showstars"
3557 :group 'org-appearance
3558 :type 'boolean)
3560 (defcustom org-hidden-keywords nil
3561 "List of symbols corresponding to keywords to be hidden the org buffer.
3562 For example, a value '(title) for this list will make the document's title
3563 appear in the buffer without the initial #+TITLE: keyword."
3564 :group 'org-appearance
3565 :version "24.1"
3566 :type '(set (const :tag "#+AUTHOR" author)
3567 (const :tag "#+DATE" date)
3568 (const :tag "#+EMAIL" email)
3569 (const :tag "#+TITLE" title)))
3571 (defcustom org-fontify-done-headline nil
3572 "Non-nil means change the face of a headline if it is marked DONE.
3573 Normally, only the TODO/DONE keyword indicates the state of a headline.
3574 When this is non-nil, the headline after the keyword is set to the
3575 `org-headline-done' as an additional indication."
3576 :group 'org-appearance
3577 :type 'boolean)
3579 (defcustom org-fontify-emphasized-text t
3580 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3581 Changing this variable requires a restart of Emacs to take effect."
3582 :group 'org-appearance
3583 :type 'boolean)
3585 (defcustom org-fontify-whole-heading-line nil
3586 "Non-nil means fontify the whole line for headings.
3587 This is useful when setting a background color for the
3588 org-level-* faces."
3589 :group 'org-appearance
3590 :type 'boolean)
3592 (defcustom org-highlight-latex-fragments-and-specials nil
3593 "Non-nil means fontify what is treated specially by the exporters."
3594 :group 'org-appearance
3595 :type 'boolean)
3597 (defcustom org-hide-emphasis-markers nil
3598 "Non-nil mean font-lock should hide the emphasis marker characters."
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-pretty-entities nil
3603 "Non-nil means show entities as UTF8 characters.
3604 When nil, the \\name form remains in the buffer."
3605 :group 'org-appearance
3606 :version "24.1"
3607 :type 'boolean)
3609 (defcustom org-pretty-entities-include-sub-superscripts t
3610 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3611 :group 'org-appearance
3612 :version "24.1"
3613 :type 'boolean)
3615 (defvar org-emph-re nil
3616 "Regular expression for matching emphasis.
3617 After a match, the match groups contain these elements:
3618 0 The match of the full regular expression, including the characters
3619 before and after the proper match
3620 1 The character before the proper match, or empty at beginning of line
3621 2 The proper match, including the leading and trailing markers
3622 3 The leading marker like * or /, indicating the type of highlighting
3623 4 The text between the emphasis markers, not including the markers
3624 5 The character after the match, empty at the end of a line")
3625 (defvar org-verbatim-re nil
3626 "Regular expression for matching verbatim text.")
3627 (defvar org-emphasis-regexp-components) ; defined just below
3628 (defvar org-emphasis-alist) ; defined just below
3629 (defun org-set-emph-re (var val)
3630 "Set variable and compute the emphasis regular expression."
3631 (set var val)
3632 (when (and (boundp 'org-emphasis-alist)
3633 (boundp 'org-emphasis-regexp-components)
3634 org-emphasis-alist org-emphasis-regexp-components)
3635 (let* ((e org-emphasis-regexp-components)
3636 (pre (car e))
3637 (post (nth 1 e))
3638 (border (nth 2 e))
3639 (body (nth 3 e))
3640 (nl (nth 4 e))
3641 (body1 (concat body "*?"))
3642 (markers (mapconcat 'car org-emphasis-alist ""))
3643 (vmarkers (mapconcat
3644 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3645 org-emphasis-alist "")))
3646 ;; make sure special characters appear at the right position in the class
3647 (if (string-match "\\^" markers)
3648 (setq markers (concat (replace-match "" t t markers) "^")))
3649 (if (string-match "-" markers)
3650 (setq markers (concat (replace-match "" t t markers) "-")))
3651 (if (string-match "\\^" vmarkers)
3652 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3653 (if (string-match "-" vmarkers)
3654 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3655 (if (> nl 0)
3656 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3657 (int-to-string nl) "\\}")))
3658 ;; Make the regexp
3659 (setq org-emph-re
3660 (concat "\\([" pre "]\\|^\\)"
3661 "\\("
3662 "\\([" markers "]\\)"
3663 "\\("
3664 "[^" border "]\\|"
3665 "[^" border "]"
3666 body1
3667 "[^" border "]"
3668 "\\)"
3669 "\\3\\)"
3670 "\\([" post "]\\|$\\)"))
3671 (setq org-verbatim-re
3672 (concat "\\([" pre "]\\|^\\)"
3673 "\\("
3674 "\\([" vmarkers "]\\)"
3675 "\\("
3676 "[^" border "]\\|"
3677 "[^" border "]"
3678 body1
3679 "[^" border "]"
3680 "\\)"
3681 "\\3\\)"
3682 "\\([" post "]\\|$\\)")))))
3684 (defcustom org-emphasis-regexp-components
3685 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3686 "Components used to build the regular expression for emphasis.
3687 This is a list with five entries. Terminology: In an emphasis string
3688 like \" *strong word* \", we call the initial space PREMATCH, the final
3689 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3690 and \"trong wor\" is the body. The different components in this variable
3691 specify what is allowed/forbidden in each part:
3693 pre Chars allowed as prematch. Beginning of line will be allowed too.
3694 post Chars allowed as postmatch. End of line will be allowed too.
3695 border The chars *forbidden* as border characters.
3696 body-regexp A regexp like \".\" to match a body character. Don't use
3697 non-shy groups here, and don't allow newline here.
3698 newline The maximum number of newlines allowed in an emphasis exp.
3700 Use customize to modify this, or restart Emacs after changing it."
3701 :group 'org-appearance
3702 :set 'org-set-emph-re
3703 :type '(list
3704 (sexp :tag "Allowed chars in pre ")
3705 (sexp :tag "Allowed chars in post ")
3706 (sexp :tag "Forbidden chars in border ")
3707 (sexp :tag "Regexp for body ")
3708 (integer :tag "number of newlines allowed")
3709 (option (boolean :tag "Please ignore this button"))))
3711 (defcustom org-emphasis-alist
3712 `(("*" bold "<b>" "</b>")
3713 ("/" italic "<i>" "</i>")
3714 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3715 ("=" org-code "<code>" "</code>" verbatim)
3716 ("~" org-verbatim "<code>" "</code>" verbatim)
3717 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3718 "<del>" "</del>")
3720 "Special syntax for emphasized text.
3721 Text starting and ending with a special character will be emphasized, for
3722 example *bold*, _underlined_ and /italic/. This variable sets the marker
3723 characters, the face to be used by font-lock for highlighting in Org-mode
3724 Emacs buffers, and the HTML tags to be used for this.
3725 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3726 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3727 Use customize to modify this, or restart Emacs after changing it."
3728 :group 'org-appearance
3729 :set 'org-set-emph-re
3730 :type '(repeat
3731 (list
3732 (string :tag "Marker character")
3733 (choice
3734 (face :tag "Font-lock-face")
3735 (plist :tag "Face property list"))
3736 (string :tag "HTML start tag")
3737 (string :tag "HTML end tag")
3738 (option (const verbatim)))))
3740 (defvar org-protecting-blocks
3741 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3742 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3743 This is needed for font-lock setup.")
3745 ;;; Miscellaneous options
3747 (defgroup org-completion nil
3748 "Completion in Org-mode."
3749 :tag "Org Completion"
3750 :group 'org)
3752 (defcustom org-completion-use-ido nil
3753 "Non-nil means use ido completion wherever possible.
3754 Note that `ido-mode' must be active for this variable to be relevant.
3755 If you decide to turn this variable on, you might well want to turn off
3756 `org-outline-path-complete-in-steps'.
3757 See also `org-completion-use-iswitchb'."
3758 :group 'org-completion
3759 :type 'boolean)
3761 (defcustom org-completion-use-iswitchb nil
3762 "Non-nil means use iswitchb completion wherever possible.
3763 Note that `iswitchb-mode' must be active for this variable to be relevant.
3764 If you decide to turn this variable on, you might well want to turn off
3765 `org-outline-path-complete-in-steps'.
3766 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3767 :group 'org-completion
3768 :type 'boolean)
3770 (defcustom org-completion-fallback-command 'hippie-expand
3771 "The expansion command called by \\[pcomplete] in normal context.
3772 Normal means, no org-mode-specific context."
3773 :group 'org-completion
3774 :type 'function)
3776 ;;; Functions and variables from their packages
3777 ;; Declared here to avoid compiler warnings
3779 ;; XEmacs only
3780 (defvar outline-mode-menu-heading)
3781 (defvar outline-mode-menu-show)
3782 (defvar outline-mode-menu-hide)
3783 (defvar zmacs-regions) ; XEmacs regions
3785 ;; Emacs only
3786 (defvar mark-active)
3788 ;; Various packages
3789 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3790 (declare-function calendar-forward-day "cal-move" (arg))
3791 (declare-function calendar-goto-date "cal-move" (date))
3792 (declare-function calendar-goto-today "cal-move" ())
3793 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3794 (defvar calc-embedded-close-formula)
3795 (defvar calc-embedded-open-formula)
3796 (declare-function cdlatex-tab "ext:cdlatex" ())
3797 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3798 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3799 (defvar font-lock-unfontify-region-function)
3800 (declare-function iswitchb-read-buffer "iswitchb"
3801 (prompt &optional default require-match start matches-set))
3802 (defvar iswitchb-temp-buflist)
3803 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3804 (defvar org-agenda-tags-todo-honor-ignore-options)
3805 (declare-function org-agenda-skip "org-agenda" ())
3806 (declare-function
3807 org-agenda-format-item "org-agenda"
3808 (extra txt &optional category tags dotime noprefix remove-re habitp))
3809 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3810 (declare-function org-agenda-change-all-lines "org-agenda"
3811 (newhead hdmarker &optional fixface just-this))
3812 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3813 (declare-function org-agenda-maybe-redo "org-agenda" ())
3814 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3815 (beg end))
3816 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3817 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3818 "org-agenda" (&optional end))
3819 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3820 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3821 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3822 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3823 (declare-function org-indent-mode "org-indent" (&optional arg))
3824 (declare-function parse-time-string "parse-time" (string))
3825 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3826 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3827 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3828 (defvar remember-data-file)
3829 (defvar texmathp-why)
3830 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3831 (declare-function table--at-cell-p "table" (position &optional object at-column))
3833 (defvar w3m-current-url)
3834 (defvar w3m-current-title)
3836 (defvar org-latex-regexps)
3838 ;;; Autoload and prepare some org modules
3840 ;; Some table stuff that needs to be defined here, because it is used
3841 ;; by the functions setting up org-mode or checking for table context.
3843 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3844 "Detect an org-type or table-type table.")
3845 (defconst org-table-line-regexp "^[ \t]*|"
3846 "Detect an org-type table line.")
3847 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3848 "Detect an org-type table line.")
3849 (defconst org-table-hline-regexp "^[ \t]*|-"
3850 "Detect an org-type table hline.")
3851 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3852 "Detect a table-type table hline.")
3853 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3854 "Detect the first line outside a table when searching from within it.
3855 This works for both table types.")
3857 ;; Autoload the functions in org-table.el that are needed by functions here.
3859 (eval-and-compile
3860 (org-autoload "org-table"
3861 '(org-table-align org-table-begin org-table-blank-field
3862 org-table-convert org-table-convert-region org-table-copy-down
3863 org-table-copy-region org-table-create
3864 org-table-create-or-convert-from-region
3865 org-table-create-with-table.el org-table-current-dline
3866 org-table-cut-region org-table-delete-column org-table-edit-field
3867 org-table-edit-formulas org-table-end org-table-eval-formula
3868 org-table-export org-table-field-info
3869 org-table-get-stored-formulas org-table-goto-column
3870 org-table-hline-and-move org-table-import org-table-insert-column
3871 org-table-insert-hline org-table-insert-row org-table-iterate
3872 org-table-justify-field-maybe org-table-kill-row
3873 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3874 org-table-move-column org-table-move-column-left
3875 org-table-move-column-right org-table-move-row
3876 org-table-move-row-down org-table-move-row-up
3877 org-table-next-field org-table-next-row org-table-paste-rectangle
3878 org-table-previous-field org-table-recalculate
3879 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3880 org-table-toggle-coordinate-overlays
3881 org-table-toggle-formula-debugger org-table-wrap-region
3882 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3883 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3884 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3886 (defun org-at-table-p (&optional table-type)
3887 "Return t if the cursor is inside an org-type table.
3888 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3889 (if org-enable-table-editor
3890 (save-excursion
3891 (beginning-of-line 1)
3892 (looking-at (if table-type org-table-any-line-regexp
3893 org-table-line-regexp)))
3894 nil))
3895 (defsubst org-table-p () (org-at-table-p))
3897 (defun org-at-table.el-p ()
3898 "Return t if and only if we are at a table.el table."
3899 (and (org-at-table-p 'any)
3900 (save-excursion
3901 (goto-char (org-table-begin 'any))
3902 (looking-at org-table1-hline-regexp))))
3903 (defun org-table-recognize-table.el ()
3904 "If there is a table.el table nearby, recognize it and move into it."
3905 (if org-table-tab-recognizes-table.el
3906 (if (org-at-table.el-p)
3907 (progn
3908 (beginning-of-line 1)
3909 (if (looking-at org-table-dataline-regexp)
3911 (if (looking-at org-table1-hline-regexp)
3912 (progn
3913 (beginning-of-line 2)
3914 (if (looking-at org-table-any-border-regexp)
3915 (beginning-of-line -1)))))
3916 (if (re-search-forward "|" (org-table-end t) t)
3917 (progn
3918 (require 'table)
3919 (if (table--at-cell-p (point))
3921 (message "recognizing table.el table...")
3922 (table-recognize-table)
3923 (message "recognizing table.el table...done")))
3924 (error "This should not happen"))
3926 nil)
3927 nil))
3929 (defun org-at-table-hline-p ()
3930 "Return t if the cursor is inside a hline in a table."
3931 (if org-enable-table-editor
3932 (save-excursion
3933 (beginning-of-line 1)
3934 (looking-at org-table-hline-regexp))
3935 nil))
3937 (defvar org-table-clean-did-remove-column nil)
3939 (defun org-table-map-tables (function &optional quietly)
3940 "Apply FUNCTION to the start of all tables in the buffer."
3941 (save-excursion
3942 (save-restriction
3943 (widen)
3944 (goto-char (point-min))
3945 (while (re-search-forward org-table-any-line-regexp nil t)
3946 (unless quietly
3947 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3948 (beginning-of-line 1)
3949 (when (looking-at org-table-line-regexp)
3950 (save-excursion (funcall function))
3951 (or (looking-at org-table-line-regexp)
3952 (forward-char 1)))
3953 (re-search-forward org-table-any-border-regexp nil 1))))
3954 (unless quietly (message "Mapping tables: done")))
3956 ;; Declare and autoload functions from org-exp.el & Co
3958 (declare-function org-default-export-plist "org-exp")
3959 (declare-function org-infile-export-plist "org-exp")
3960 (declare-function org-get-current-options "org-exp")
3961 (eval-and-compile
3962 (org-autoload "org-exp"
3963 '(org-export org-export-visible
3964 org-insert-export-options-template
3965 org-table-clean-before-export))
3966 (org-autoload "org-ascii"
3967 '(org-export-as-ascii org-export-ascii-preprocess
3968 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3969 org-export-region-as-ascii))
3970 (org-autoload "org-latex"
3971 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3972 org-replace-region-by-latex org-export-region-as-latex
3973 org-export-as-latex org-export-as-pdf
3974 org-export-as-pdf-and-open))
3975 (org-autoload "org-html"
3976 '(org-export-as-html-and-open
3977 org-export-as-html-batch org-export-as-html-to-buffer
3978 org-replace-region-by-html org-export-region-as-html
3979 org-export-as-html))
3980 (org-autoload "org-docbook"
3981 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3982 org-replace-region-by-docbook org-export-region-as-docbook
3983 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3984 org-export-as-docbook))
3985 (org-autoload "org-icalendar"
3986 '(org-export-icalendar-this-file
3987 org-export-icalendar-all-agenda-files
3988 org-export-icalendar-combine-agenda-files))
3989 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3990 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3992 ;; Declare and autoload functions from org-agenda.el
3994 (eval-and-compile
3995 (org-autoload "org-agenda"
3996 '(org-agenda org-agenda-list org-search-view
3997 org-todo-list org-tags-view org-agenda-list-stuck-projects
3998 org-diary org-agenda-to-appt
3999 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4001 ;; Autoload org-remember
4003 (eval-and-compile
4004 (org-autoload "org-remember"
4005 '(org-remember-insinuate org-remember-annotation
4006 org-remember-apply-template org-remember org-remember-handler)))
4008 (eval-and-compile
4009 (org-autoload "org-capture"
4010 '(org-capture org-capture-insert-template-here
4011 org-capture-import-remember-templates)))
4013 ;; Autoload org-clock.el
4015 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4016 (beg end))
4017 (declare-function org-clock-update-mode-line "org-clock" ())
4018 (declare-function org-resolve-clocks "org-clock"
4019 (&optional also-non-dangling-p prompt last-valid))
4020 (defvar org-clock-start-time)
4021 (defvar org-clock-marker (make-marker)
4022 "Marker recording the last clock-in.")
4023 (defvar org-clock-hd-marker (make-marker)
4024 "Marker recording the last clock-in, but the headline position.")
4025 (defvar org-clock-heading ""
4026 "The heading of the current clock entry.")
4027 (defun org-clock-is-active ()
4028 "Return non-nil if clock is currently running.
4029 The return value is actually the clock marker."
4030 (marker-buffer org-clock-marker))
4032 (eval-and-compile
4033 (org-autoload
4034 "org-clock"
4035 '(org-clock-in org-clock-out org-clock-cancel
4036 org-clock-goto org-clock-sum org-clock-display
4037 org-clock-remove-overlays org-clock-report
4038 org-clocktable-shift org-dblock-write:clocktable
4039 org-get-clocktable org-resolve-clocks)))
4041 (defun org-clock-update-time-maybe ()
4042 "If this is a CLOCK line, update it and return t.
4043 Otherwise, return nil."
4044 (interactive)
4045 (save-excursion
4046 (beginning-of-line 1)
4047 (skip-chars-forward " \t")
4048 (when (looking-at org-clock-string)
4049 (let ((re (concat "[ \t]*" org-clock-string
4050 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4051 "\\([ \t]*=>.*\\)?\\)?"))
4052 ts te h m s neg)
4053 (cond
4054 ((not (looking-at re))
4055 nil)
4056 ((not (match-end 2))
4057 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4058 (> org-clock-marker (point))
4059 (<= org-clock-marker (point-at-eol)))
4060 ;; The clock is running here
4061 (setq org-clock-start-time
4062 (apply 'encode-time
4063 (org-parse-time-string (match-string 1))))
4064 (org-clock-update-mode-line)))
4066 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4067 (end-of-line 1)
4068 (setq ts (match-string 1)
4069 te (match-string 3))
4070 (setq s (- (org-float-time
4071 (apply 'encode-time (org-parse-time-string te)))
4072 (org-float-time
4073 (apply 'encode-time (org-parse-time-string ts))))
4074 neg (< s 0)
4075 s (abs s)
4076 h (floor (/ s 3600))
4077 s (- s (* 3600 h))
4078 m (floor (/ s 60))
4079 s (- s (* 60 s)))
4080 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4081 t))))))
4083 (defun org-check-running-clock ()
4084 "Check if the current buffer contains the running clock.
4085 If yes, offer to stop it and to save the buffer with the changes."
4086 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4087 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4088 (buffer-name))))
4089 (org-clock-out)
4090 (when (y-or-n-p "Save changed buffer?")
4091 (save-buffer))))
4093 (defun org-clocktable-try-shift (dir n)
4094 "Check if this line starts a clock table, if yes, shift the time block."
4095 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4096 (org-clocktable-shift dir n)))
4098 ;; Autoload org-timer.el
4100 (eval-and-compile
4101 (org-autoload
4102 "org-timer"
4103 '(org-timer-start org-timer org-timer-item
4104 org-timer-change-times-in-region
4105 org-timer-set-timer
4106 org-timer-reset-timers
4107 org-timer-show-remaining-time)))
4109 ;; Autoload org-feed.el
4111 (eval-and-compile
4112 (org-autoload
4113 "org-feed"
4114 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4117 ;; Autoload org-indent.el
4119 ;; Define the variable already here, to make sure we have it.
4120 (defvar org-indent-mode nil
4121 "Non-nil if Org-Indent mode is enabled.
4122 Use the command `org-indent-mode' to change this variable.")
4124 (eval-and-compile
4125 (org-autoload
4126 "org-indent"
4127 '(org-indent-mode)))
4129 ;; Autoload org-mobile.el
4131 (eval-and-compile
4132 (org-autoload
4133 "org-mobile"
4134 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4136 ;; Autoload archiving code
4137 ;; The stuff that is needed for cycling and tags has to be defined here.
4139 (defgroup org-archive nil
4140 "Options concerning archiving in Org-mode."
4141 :tag "Org Archive"
4142 :group 'org-structure)
4144 (defcustom org-archive-location "%s_archive::"
4145 "The location where subtrees should be archived.
4147 The value of this variable is a string, consisting of two parts,
4148 separated by a double-colon. The first part is a filename and
4149 the second part is a headline.
4151 When the filename is omitted, archiving happens in the same file.
4152 %s in the filename will be replaced by the current file
4153 name (without the directory part). Archiving to a different file
4154 is useful to keep archived entries from contributing to the
4155 Org-mode Agenda.
4157 The archived entries will be filed as subtrees of the specified
4158 headline. When the headline is omitted, the subtrees are simply
4159 filed away at the end of the file, as top-level entries. Also in
4160 the heading you can use %s to represent the file name, this can be
4161 useful when using the same archive for a number of different files.
4163 Here are a few examples:
4164 \"%s_archive::\"
4165 If the current file is Projects.org, archive in file
4166 Projects.org_archive, as top-level trees. This is the default.
4168 \"::* Archived Tasks\"
4169 Archive in the current file, under the top-level headline
4170 \"* Archived Tasks\".
4172 \"~/org/archive.org::\"
4173 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4175 \"~/org/archive.org::* From %s\"
4176 Archive in file ~/org/archive.org (absolute path), under headlines
4177 \"From FILENAME\" where file name is the current file name.
4179 \"basement::** Finished Tasks\"
4180 Archive in file ./basement (relative path), as level 3 trees
4181 below the level 2 heading \"** Finished Tasks\".
4183 You may set this option on a per-file basis by adding to the buffer a
4184 line like
4186 #+ARCHIVE: basement::** Finished Tasks
4188 You may also define it locally for a subtree by setting an ARCHIVE property
4189 in the entry. If such a property is found in an entry, or anywhere up
4190 the hierarchy, it will be used."
4191 :group 'org-archive
4192 :type 'string)
4194 (defcustom org-archive-tag "ARCHIVE"
4195 "The tag that marks a subtree as archived.
4196 An archived subtree does not open during visibility cycling, and does
4197 not contribute to the agenda listings.
4198 After changing this, font-lock must be restarted in the relevant buffers to
4199 get the proper fontification."
4200 :group 'org-archive
4201 :group 'org-keywords
4202 :type 'string)
4204 (defcustom org-agenda-skip-archived-trees t
4205 "Non-nil means the agenda will skip any items located in archived trees.
4206 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4207 variable is no longer recommended, you should leave it at the value t.
4208 Instead, use the key `v' to cycle the archives-mode in the agenda."
4209 :group 'org-archive
4210 :group 'org-agenda-skip
4211 :type 'boolean)
4213 (defcustom org-columns-skip-archived-trees t
4214 "Non-nil means ignore archived trees when creating column view."
4215 :group 'org-archive
4216 :group 'org-properties
4217 :type 'boolean)
4219 (defcustom org-cycle-open-archived-trees nil
4220 "Non-nil means `org-cycle' will open archived trees.
4221 An archived tree is a tree marked with the tag ARCHIVE.
4222 When nil, archived trees will stay folded. You can still open them with
4223 normal outline commands like `show-all', but not with the cycling commands."
4224 :group 'org-archive
4225 :group 'org-cycle
4226 :type 'boolean)
4228 (defcustom org-sparse-tree-open-archived-trees nil
4229 "Non-nil means sparse tree construction shows matches in archived trees.
4230 When nil, matches in these trees are highlighted, but the trees are kept in
4231 collapsed state."
4232 :group 'org-archive
4233 :group 'org-sparse-trees
4234 :type 'boolean)
4236 (defun org-cycle-hide-archived-subtrees (state)
4237 "Re-hide all archived subtrees after a visibility state change."
4238 (when (and (not org-cycle-open-archived-trees)
4239 (not (memq state '(overview folded))))
4240 (save-excursion
4241 (let* ((globalp (memq state '(contents all)))
4242 (beg (if globalp (point-min) (point)))
4243 (end (if globalp (point-max) (org-end-of-subtree t))))
4244 (org-hide-archived-subtrees beg end)
4245 (goto-char beg)
4246 (if (looking-at (concat ".*:" org-archive-tag ":"))
4247 (message "%s" (substitute-command-keys
4248 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4250 (defun org-force-cycle-archived ()
4251 "Cycle subtree even if it is archived."
4252 (interactive)
4253 (setq this-command 'org-cycle)
4254 (let ((org-cycle-open-archived-trees t))
4255 (call-interactively 'org-cycle)))
4257 (defun org-hide-archived-subtrees (beg end)
4258 "Re-hide all archived subtrees after a visibility state change."
4259 (save-excursion
4260 (let* ((re (concat ":" org-archive-tag ":")))
4261 (goto-char beg)
4262 (while (re-search-forward re end t)
4263 (when (org-at-heading-p)
4264 (org-flag-subtree t)
4265 (org-end-of-subtree t))))))
4267 (defun org-flag-subtree (flag)
4268 (save-excursion
4269 (org-back-to-heading t)
4270 (outline-end-of-heading)
4271 (outline-flag-region (point)
4272 (progn (org-end-of-subtree t) (point))
4273 flag)))
4275 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4277 (eval-and-compile
4278 (org-autoload "org-archive"
4279 '(org-add-archive-files org-archive-subtree
4280 org-archive-to-archive-sibling org-toggle-archive-tag
4281 org-archive-subtree-default
4282 org-archive-subtree-default-with-confirmation)))
4284 ;; Autoload Column View Code
4286 (declare-function org-columns-number-to-string "org-colview")
4287 (declare-function org-columns-get-format-and-top-level "org-colview")
4288 (declare-function org-columns-compute "org-colview")
4290 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4291 '(org-columns-number-to-string org-columns-get-format-and-top-level
4292 org-columns-compute org-agenda-columns org-columns-remove-overlays
4293 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4295 ;; Autoload ID code
4297 (declare-function org-id-store-link "org-id")
4298 (declare-function org-id-locations-load "org-id")
4299 (declare-function org-id-locations-save "org-id")
4300 (defvar org-id-track-globally)
4301 (org-autoload "org-id"
4302 '(org-id-get-create org-id-new org-id-copy org-id-get
4303 org-id-get-with-outline-path-completion
4304 org-id-get-with-outline-drilling org-id-store-link
4305 org-id-goto org-id-find org-id-store-link))
4307 ;; Autoload Plotting Code
4309 (org-autoload "org-plot"
4310 '(org-plot/gnuplot))
4312 ;;; Variables for pre-computed regular expressions, all buffer local
4314 (defvar org-drawer-regexp nil
4315 "Matches first line of a hidden block.")
4316 (make-variable-buffer-local 'org-drawer-regexp)
4317 (defvar org-todo-regexp nil
4318 "Matches any of the TODO state keywords.")
4319 (make-variable-buffer-local 'org-todo-regexp)
4320 (defvar org-not-done-regexp nil
4321 "Matches any of the TODO state keywords except the last one.")
4322 (make-variable-buffer-local 'org-not-done-regexp)
4323 (defvar org-not-done-heading-regexp nil
4324 "Matches a TODO headline that is not done.")
4325 (make-variable-buffer-local 'org-not-done-regexp)
4326 (defvar org-todo-line-regexp nil
4327 "Matches a headline and puts TODO state into group 2 if present.")
4328 (make-variable-buffer-local 'org-todo-line-regexp)
4329 (defvar org-complex-heading-regexp nil
4330 "Matches a headline and puts everything into groups:
4331 group 1: the stars
4332 group 2: The todo keyword, maybe
4333 group 3: Priority cookie
4334 group 4: True headline
4335 group 5: Tags")
4336 (make-variable-buffer-local 'org-complex-heading-regexp)
4337 (defvar org-complex-heading-regexp-format nil
4338 "Printf format to make regexp to match an exact headline.
4339 This regexp will match the headline of any node which has the
4340 exact headline text that is put into the format, but may have any
4341 TODO state, priority and tags.")
4342 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4343 (defvar org-todo-line-tags-regexp nil
4344 "Matches a headline and puts TODO state into group 2 if present.
4345 Also put tags into group 4 if tags are present.")
4346 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4347 (defvar org-ds-keyword-length 12
4348 "Maximum length of the Deadline and SCHEDULED keywords.")
4349 (make-variable-buffer-local 'org-ds-keyword-length)
4350 (defvar org-deadline-regexp nil
4351 "Matches the DEADLINE keyword.")
4352 (make-variable-buffer-local 'org-deadline-regexp)
4353 (defvar org-deadline-time-regexp nil
4354 "Matches the DEADLINE keyword together with a time stamp.")
4355 (make-variable-buffer-local 'org-deadline-time-regexp)
4356 (defvar org-deadline-line-regexp nil
4357 "Matches the DEADLINE keyword and the rest of the line.")
4358 (make-variable-buffer-local 'org-deadline-line-regexp)
4359 (defvar org-scheduled-regexp nil
4360 "Matches the SCHEDULED keyword.")
4361 (make-variable-buffer-local 'org-scheduled-regexp)
4362 (defvar org-scheduled-time-regexp nil
4363 "Matches the SCHEDULED keyword together with a time stamp.")
4364 (make-variable-buffer-local 'org-scheduled-time-regexp)
4365 (defvar org-closed-time-regexp nil
4366 "Matches the CLOSED keyword together with a time stamp.")
4367 (make-variable-buffer-local 'org-closed-time-regexp)
4369 (defvar org-keyword-time-regexp nil
4370 "Matches any of the 4 keywords, together with the time stamp.")
4371 (make-variable-buffer-local 'org-keyword-time-regexp)
4372 (defvar org-keyword-time-not-clock-regexp nil
4373 "Matches any of the 3 keywords, together with the time stamp.")
4374 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4375 (defvar org-maybe-keyword-time-regexp nil
4376 "Matches a timestamp, possibly preceded by a keyword.")
4377 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4378 (defvar org-planning-or-clock-line-re nil
4379 "Matches a line with planning or clock info.")
4380 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4381 (defvar org-all-time-keywords nil
4382 "List of time keywords.")
4383 (make-variable-buffer-local 'org-all-time-keywords)
4385 (defconst org-plain-time-of-day-regexp
4386 (concat
4387 "\\(\\<[012]?[0-9]"
4388 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4389 "\\(--?"
4390 "\\(\\<[012]?[0-9]"
4391 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4392 "\\)?")
4393 "Regular expression to match a plain time or time range.
4394 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4395 groups carry important information:
4396 0 the full match
4397 1 the first time, range or not
4398 8 the second time, if it is a range.")
4400 (defconst org-plain-time-extension-regexp
4401 (concat
4402 "\\(\\<[012]?[0-9]"
4403 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4404 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4405 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4406 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4407 groups carry important information:
4408 0 the full match
4409 7 hours of duration
4410 9 minutes of duration")
4412 (defconst org-stamp-time-of-day-regexp
4413 (concat
4414 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4415 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4416 "\\(--?"
4417 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4418 "Regular expression to match a timestamp time or time range.
4419 After a match, the following groups carry important information:
4420 0 the full match
4421 1 date plus weekday, for back referencing to make sure both times are on the same day
4422 2 the first time, range or not
4423 4 the second time, if it is a range.")
4425 (defconst org-startup-options
4426 '(("fold" org-startup-folded t)
4427 ("overview" org-startup-folded t)
4428 ("nofold" org-startup-folded nil)
4429 ("showall" org-startup-folded nil)
4430 ("showeverything" org-startup-folded showeverything)
4431 ("content" org-startup-folded content)
4432 ("indent" org-startup-indented t)
4433 ("noindent" org-startup-indented nil)
4434 ("hidestars" org-hide-leading-stars t)
4435 ("showstars" org-hide-leading-stars nil)
4436 ("odd" org-odd-levels-only t)
4437 ("oddeven" org-odd-levels-only nil)
4438 ("align" org-startup-align-all-tables t)
4439 ("noalign" org-startup-align-all-tables nil)
4440 ("inlineimages" org-startup-with-inline-images t)
4441 ("noinlineimages" org-startup-with-inline-images nil)
4442 ("customtime" org-display-custom-times t)
4443 ("logdone" org-log-done time)
4444 ("lognotedone" org-log-done note)
4445 ("nologdone" org-log-done nil)
4446 ("lognoteclock-out" org-log-note-clock-out t)
4447 ("nolognoteclock-out" org-log-note-clock-out nil)
4448 ("logrepeat" org-log-repeat state)
4449 ("lognoterepeat" org-log-repeat note)
4450 ("nologrepeat" org-log-repeat nil)
4451 ("logreschedule" org-log-reschedule time)
4452 ("lognotereschedule" org-log-reschedule note)
4453 ("nologreschedule" org-log-reschedule nil)
4454 ("logredeadline" org-log-redeadline time)
4455 ("lognoteredeadline" org-log-redeadline note)
4456 ("nologredeadline" org-log-redeadline nil)
4457 ("logrefile" org-log-refile time)
4458 ("lognoterefile" org-log-refile note)
4459 ("nologrefile" org-log-refile nil)
4460 ("fninline" org-footnote-define-inline t)
4461 ("nofninline" org-footnote-define-inline nil)
4462 ("fnlocal" org-footnote-section nil)
4463 ("fnauto" org-footnote-auto-label t)
4464 ("fnprompt" org-footnote-auto-label nil)
4465 ("fnconfirm" org-footnote-auto-label confirm)
4466 ("fnplain" org-footnote-auto-label plain)
4467 ("fnadjust" org-footnote-auto-adjust t)
4468 ("nofnadjust" org-footnote-auto-adjust nil)
4469 ("constcgs" constants-unit-system cgs)
4470 ("constSI" constants-unit-system SI)
4471 ("noptag" org-tag-persistent-alist nil)
4472 ("hideblocks" org-hide-block-startup t)
4473 ("nohideblocks" org-hide-block-startup nil)
4474 ("beamer" org-startup-with-beamer-mode t)
4475 ("entitiespretty" org-pretty-entities t)
4476 ("entitiesplain" org-pretty-entities nil))
4477 "Variable associated with STARTUP options for org-mode.
4478 Each element is a list of three items: The startup options as written
4479 in the #+STARTUP line, the corresponding variable, and the value to
4480 set this variable to if the option is found. An optional forth element PUSH
4481 means to push this value onto the list in the variable.")
4483 (defun org-update-property-plist (key val props)
4484 "Update PROPS with KEY and VAL."
4485 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4486 (key (if appending (substring key 0 (- (length key) 1)) key))
4487 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4488 (previous (cdr (assoc key props))))
4489 (if appending
4490 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4491 (cons (cons key val) remainder))))
4493 (defconst org-block-regexp
4494 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4495 "Regular expression for hiding blocks.")
4496 (defconst org-heading-keyword-regexp-format
4497 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4498 "Printf format for a regexp matching an headline with some keyword.
4499 This regexp will match the headline of any node which has the
4500 exact keyword that is put into the format. The keyword isn't in
4501 any group by default, but the stars and the body are.")
4502 (defconst org-heading-keyword-maybe-regexp-format
4503 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4504 "Printf format for a regexp matching an headline, possibly with some keyword.
4505 This regexp can match any headline with the specified keyword, or
4506 without a keyword. The keyword isn't in any group by default,
4507 but the stars and the body are.")
4509 (defun org-set-regexps-and-options ()
4510 "Precompute regular expressions for current buffer."
4511 (when (eq major-mode 'org-mode)
4512 (org-set-local 'org-todo-kwd-alist nil)
4513 (org-set-local 'org-todo-key-alist nil)
4514 (org-set-local 'org-todo-key-trigger nil)
4515 (org-set-local 'org-todo-keywords-1 nil)
4516 (org-set-local 'org-done-keywords nil)
4517 (org-set-local 'org-todo-heads nil)
4518 (org-set-local 'org-todo-sets nil)
4519 (org-set-local 'org-todo-log-states nil)
4520 (org-set-local 'org-file-properties nil)
4521 (org-set-local 'org-file-tags nil)
4522 (let ((re (org-make-options-regexp
4523 '("CATEGORY" "TODO" "COLUMNS"
4524 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4525 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4526 "OPTIONS")
4527 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4528 (splitre "[ \t]+")
4529 (scripts org-use-sub-superscripts)
4530 kwds kws0 kwsa key log value cat arch tags const links hw dws
4531 tail sep kws1 prio props ftags drawers beamer-p
4532 ext-setup-or-nil setup-contents (start 0))
4533 (save-excursion
4534 (save-restriction
4535 (widen)
4536 (goto-char (point-min))
4537 (while (or (and ext-setup-or-nil
4538 (string-match re ext-setup-or-nil start)
4539 (setq start (match-end 0)))
4540 (and (setq ext-setup-or-nil nil start 0)
4541 (re-search-forward re nil t)))
4542 (setq key (upcase (match-string 1 ext-setup-or-nil))
4543 value (org-match-string-no-properties 2 ext-setup-or-nil))
4544 (if (stringp value) (setq value (org-trim value)))
4545 (cond
4546 ((equal key "CATEGORY")
4547 (setq cat value))
4548 ((member key '("SEQ_TODO" "TODO"))
4549 (push (cons 'sequence (org-split-string value splitre)) kwds))
4550 ((equal key "TYP_TODO")
4551 (push (cons 'type (org-split-string value splitre)) kwds))
4552 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4553 ;; general TODO-like setup
4554 (push (cons (intern (downcase (match-string 1 key)))
4555 (org-split-string value splitre)) kwds))
4556 ((equal key "TAGS")
4557 (setq tags (append tags (if tags '("\\n") nil)
4558 (org-split-string value splitre))))
4559 ((equal key "COLUMNS")
4560 (org-set-local 'org-columns-default-format value))
4561 ((equal key "LINK")
4562 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4563 (push (cons (match-string 1 value)
4564 (org-trim (match-string 2 value)))
4565 links)))
4566 ((equal key "PRIORITIES")
4567 (setq prio (org-split-string value " +")))
4568 ((equal key "PROPERTY")
4569 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4570 (setq props (org-update-property-plist (match-string 1 value)
4571 (match-string 2 value)
4572 props))))
4573 ((equal key "FILETAGS")
4574 (when (string-match "\\S-" value)
4575 (setq ftags
4576 (append
4577 ftags
4578 (apply 'append
4579 (mapcar (lambda (x) (org-split-string x ":"))
4580 (org-split-string value)))))))
4581 ((equal key "DRAWERS")
4582 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4583 ((equal key "CONSTANTS")
4584 (setq const (append const (org-split-string value splitre))))
4585 ((equal key "STARTUP")
4586 (let ((opts (org-split-string value splitre))
4587 l var val)
4588 (while (setq l (pop opts))
4589 (when (setq l (assoc l org-startup-options))
4590 (setq var (nth 1 l) val (nth 2 l))
4591 (if (not (nth 3 l))
4592 (set (make-local-variable var) val)
4593 (if (not (listp (symbol-value var)))
4594 (set (make-local-variable var) nil))
4595 (set (make-local-variable var) (symbol-value var))
4596 (add-to-list var val))))))
4597 ((equal key "ARCHIVE")
4598 (setq arch value)
4599 (remove-text-properties 0 (length arch)
4600 '(face t fontified t) arch))
4601 ((equal key "LATEX_CLASS")
4602 (setq beamer-p (equal value "beamer")))
4603 ((equal key "OPTIONS")
4604 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4605 (setq scripts (read (match-string 2 value)))))
4606 ((equal key "SETUPFILE")
4607 (setq setup-contents (org-file-contents
4608 (expand-file-name
4609 (org-remove-double-quotes value))
4610 'noerror))
4611 (if (not ext-setup-or-nil)
4612 (setq ext-setup-or-nil setup-contents start 0)
4613 (setq ext-setup-or-nil
4614 (concat (substring ext-setup-or-nil 0 start)
4615 "\n" setup-contents "\n"
4616 (substring ext-setup-or-nil start)))))))
4617 ;; search for property blocks
4618 (goto-char (point-min))
4619 (while (re-search-forward org-block-regexp nil t)
4620 (when (equal "PROPERTY" (upcase (match-string 1)))
4621 (setq value (replace-regexp-in-string
4622 "[\n\r]" " " (match-string 4)))
4623 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4624 (setq props (org-update-property-plist (match-string 1 value)
4625 (match-string 2 value)
4626 props)))))))
4627 (org-set-local 'org-use-sub-superscripts scripts)
4628 (when cat
4629 (org-set-local 'org-category (intern cat))
4630 (push (cons "CATEGORY" cat) props))
4631 (when prio
4632 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4633 (setq prio (mapcar 'string-to-char prio))
4634 (org-set-local 'org-highest-priority (nth 0 prio))
4635 (org-set-local 'org-lowest-priority (nth 1 prio))
4636 (org-set-local 'org-default-priority (nth 2 prio)))
4637 (and props (org-set-local 'org-file-properties (nreverse props)))
4638 (and ftags (org-set-local 'org-file-tags
4639 (mapcar 'org-add-prop-inherited ftags)))
4640 (and drawers (org-set-local 'org-drawers drawers))
4641 (and arch (org-set-local 'org-archive-location arch))
4642 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4643 ;; Process the TODO keywords
4644 (unless kwds
4645 ;; Use the global values as if they had been given locally.
4646 (setq kwds (default-value 'org-todo-keywords))
4647 (if (stringp (car kwds))
4648 (setq kwds (list (cons org-todo-interpretation
4649 (default-value 'org-todo-keywords)))))
4650 (setq kwds (reverse kwds)))
4651 (setq kwds (nreverse kwds))
4652 (let (inter kws kw)
4653 (while (setq kws (pop kwds))
4654 (let ((kws (or
4655 (run-hook-with-args-until-success
4656 'org-todo-setup-filter-hook kws)
4657 kws)))
4658 (setq inter (pop kws) sep (member "|" kws)
4659 kws0 (delete "|" (copy-sequence kws))
4660 kwsa nil
4661 kws1 (mapcar
4662 (lambda (x)
4663 ;; 1 2
4664 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4665 (progn
4666 (setq kw (match-string 1 x)
4667 key (and (match-end 2) (match-string 2 x))
4668 log (org-extract-log-state-settings x))
4669 (push (cons kw (and key (string-to-char key))) kwsa)
4670 (and log (push log org-todo-log-states))
4672 (error "Invalid TODO keyword %s" x)))
4673 kws0)
4674 kwsa (if kwsa (append '((:startgroup))
4675 (nreverse kwsa)
4676 '((:endgroup))))
4677 hw (car kws1)
4678 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4679 tail (list inter hw (car dws) (org-last dws))))
4680 (add-to-list 'org-todo-heads hw 'append)
4681 (push kws1 org-todo-sets)
4682 (setq org-done-keywords (append org-done-keywords dws nil))
4683 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4684 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4685 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4686 (setq org-todo-sets (nreverse org-todo-sets)
4687 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4688 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4689 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4690 ;; Process the constants
4691 (when const
4692 (let (e cst)
4693 (while (setq e (pop const))
4694 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4695 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4696 (setq org-table-formula-constants-local cst)))
4698 ;; Process the tags.
4699 (when tags
4700 (let (e tgs)
4701 (while (setq e (pop tags))
4702 (cond
4703 ((equal e "{") (push '(:startgroup) tgs))
4704 ((equal e "}") (push '(:endgroup) tgs))
4705 ((equal e "\\n") (push '(:newline) tgs))
4706 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4707 (push (cons (match-string 1 e)
4708 (string-to-char (match-string 2 e)))
4709 tgs))
4710 (t (push (list e) tgs))))
4711 (org-set-local 'org-tag-alist nil)
4712 (while (setq e (pop tgs))
4713 (or (and (stringp (car e))
4714 (assoc (car e) org-tag-alist))
4715 (push e org-tag-alist)))))
4717 ;; Compute the regular expressions and other local variables.
4718 ;; Using `org-outline-regexp-bol' would complicate them much,
4719 ;; because of the fixed white space at the end of that string.
4720 (if (not org-done-keywords)
4721 (setq org-done-keywords (and org-todo-keywords-1
4722 (list (org-last org-todo-keywords-1)))))
4723 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4724 (length org-scheduled-string)
4725 (length org-clock-string)
4726 (length org-closed-string)))
4727 org-drawer-regexp
4728 (concat "^[ \t]*:\\("
4729 (mapconcat 'regexp-quote org-drawers "\\|")
4730 "\\):[ \t]*$")
4731 org-not-done-keywords
4732 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4733 org-todo-regexp
4734 (concat "\\("
4735 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4736 "\\)")
4737 org-not-done-regexp
4738 (concat "\\("
4739 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4740 "\\)")
4741 org-not-done-heading-regexp
4742 (format org-heading-keyword-regexp-format org-not-done-regexp)
4743 org-todo-line-regexp
4744 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4745 org-complex-heading-regexp
4746 (concat "^\\(\\*+\\)"
4747 "\\(?: +" org-todo-regexp "\\)?"
4748 "\\(?: +\\(\\[#.\\]\\)\\)?"
4749 "\\(?: +\\(.*?\\)\\)?"
4750 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4751 "[ \t]*$")
4752 org-complex-heading-regexp-format
4753 (concat "^\\(\\*+\\)"
4754 "\\(?: +" org-todo-regexp "\\)?"
4755 "\\(?: +\\(\\[#.\\]\\)\\)?"
4756 "\\(?: +"
4757 ;; Stats cookies can be stuck to body.
4758 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4759 "\\(%s\\)"
4760 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4761 "\\)"
4762 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4763 "[ \t]*$")
4764 org-todo-line-tags-regexp
4765 (concat "^\\(\\*+\\)"
4766 "\\(?: +" org-todo-regexp "\\)?"
4767 "\\(?: +\\(.*?\\)\\)?"
4768 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4769 "[ \t]*$")
4770 org-deadline-regexp (concat "\\<" org-deadline-string)
4771 org-deadline-time-regexp
4772 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4773 org-deadline-line-regexp
4774 (concat "\\<\\(" org-deadline-string "\\).*")
4775 org-scheduled-regexp
4776 (concat "\\<" org-scheduled-string)
4777 org-scheduled-time-regexp
4778 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4779 org-closed-time-regexp
4780 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4781 org-keyword-time-regexp
4782 (concat "\\<\\(" org-scheduled-string
4783 "\\|" org-deadline-string
4784 "\\|" org-closed-string
4785 "\\|" org-clock-string "\\)"
4786 " *[[<]\\([^]>]+\\)[]>]")
4787 org-keyword-time-not-clock-regexp
4788 (concat "\\<\\(" org-scheduled-string
4789 "\\|" org-deadline-string
4790 "\\|" org-closed-string
4791 "\\)"
4792 " *[[<]\\([^]>]+\\)[]>]")
4793 org-maybe-keyword-time-regexp
4794 (concat "\\(\\<\\(" org-scheduled-string
4795 "\\|" org-deadline-string
4796 "\\|" org-closed-string
4797 "\\|" org-clock-string "\\)\\)?"
4798 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4799 org-planning-or-clock-line-re
4800 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4801 "\\|" org-deadline-string
4802 "\\|" org-closed-string "\\|" org-clock-string
4803 "\\)\\>\\)")
4804 org-all-time-keywords
4805 (mapcar (lambda (w) (substring w 0 -1))
4806 (list org-scheduled-string org-deadline-string
4807 org-clock-string org-closed-string))
4809 (org-compute-latex-and-specials-regexp)
4810 (org-set-font-lock-defaults))))
4812 (defun org-file-contents (file &optional noerror)
4813 "Return the contents of FILE, as a string."
4814 (if (or (not file)
4815 (not (file-readable-p file)))
4816 (if noerror
4817 (progn
4818 (message "Cannot read file \"%s\"" file)
4819 (ding) (sit-for 2)
4821 (error "Cannot read file \"%s\"" file))
4822 (with-temp-buffer
4823 (insert-file-contents file)
4824 (buffer-string))))
4826 (defun org-extract-log-state-settings (x)
4827 "Extract the log state setting from a TODO keyword string.
4828 This will extract info from a string like \"WAIT(w@/!)\"."
4829 (let (kw key log1 log2)
4830 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4831 (setq kw (match-string 1 x)
4832 key (and (match-end 2) (match-string 2 x))
4833 log1 (and (match-end 3) (match-string 3 x))
4834 log2 (and (match-end 4) (match-string 4 x)))
4835 (and (or log1 log2)
4836 (list kw
4837 (and log1 (if (equal log1 "!") 'time 'note))
4838 (and log2 (if (equal log2 "!") 'time 'note)))))))
4840 (defun org-remove-keyword-keys (list)
4841 "Remove a pair of parenthesis at the end of each string in LIST."
4842 (mapcar (lambda (x)
4843 (if (string-match "(.*)$" x)
4844 (substring x 0 (match-beginning 0))
4846 list))
4848 (defun org-assign-fast-keys (alist)
4849 "Assign fast keys to a keyword-key alist.
4850 Respect keys that are already there."
4851 (let (new e (alt ?0))
4852 (while (setq e (pop alist))
4853 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4854 (cdr e)) ;; Key already assigned.
4855 (push e new)
4856 (let ((clist (string-to-list (downcase (car e))))
4857 (used (append new alist)))
4858 (when (= (car clist) ?@)
4859 (pop clist))
4860 (while (and clist (rassoc (car clist) used))
4861 (pop clist))
4862 (unless clist
4863 (while (rassoc alt used)
4864 (incf alt)))
4865 (push (cons (car e) (or (car clist) alt)) new))))
4866 (nreverse new)))
4868 ;;; Some variables used in various places
4870 (defvar org-window-configuration nil
4871 "Used in various places to store a window configuration.")
4872 (defvar org-selected-window nil
4873 "Used in various places to store a window configuration.")
4874 (defvar org-finish-function nil
4875 "Function to be called when `C-c C-c' is used.
4876 This is for getting out of special buffers like remember.")
4879 ;; FIXME: Occasionally check by commenting these, to make sure
4880 ;; no other functions uses these, forgetting to let-bind them.
4881 (defvar entry)
4882 (defvar last-state)
4883 (defvar date)
4885 ;; Defined somewhere in this file, but used before definition.
4886 (defvar org-entities) ;; defined in org-entities.el
4887 (defvar org-struct-menu)
4888 (defvar org-org-menu)
4889 (defvar org-tbl-menu)
4891 ;;;; Define the Org-mode
4893 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4894 (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"))
4897 ;; We use a before-change function to check if a table might need
4898 ;; an update.
4899 (defvar org-table-may-need-update t
4900 "Indicates that a table might need an update.
4901 This variable is set by `org-before-change-function'.
4902 `org-table-align' sets it back to nil.")
4903 (defun org-before-change-function (beg end)
4904 "Every change indicates that a table might need an update."
4905 (setq org-table-may-need-update t))
4906 (defvar org-mode-map)
4907 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4908 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4909 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4910 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4911 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4912 (defvar org-table-buffer-is-an nil)
4914 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4915 ;; some places -- e.g. see the macro org-with-limited-levels.
4917 ;; In Org buffers, the value of `outline-regexp' is that of
4918 ;; `org-outline-regexp'. The only function still directly relying on
4919 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4920 ;; job when `orgstruct-mode' is active.
4921 (defvar org-outline-regexp "\\*+ "
4922 "Regexp to match Org headlines.")
4923 (defconst org-outline-regexp-bol "^\\*+ "
4924 "Regexp to match Org headlines.
4925 This is similar to `org-outline-regexp' but additionally makes
4926 sure that we are at the beginning of the line.")
4928 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4929 "Matches an headline, putting stars and text into groups.
4930 Stars are put in group 1 and the trimmed body in group 2.")
4932 ;;;###autoload
4933 (define-derived-mode org-mode outline-mode "Org"
4934 "Outline-based notes management and organizer, alias
4935 \"Carsten's outline-mode for keeping track of everything.\"
4937 Org-mode develops organizational tasks around a NOTES file which
4938 contains information about projects as plain text. Org-mode is
4939 implemented on top of outline-mode, which is ideal to keep the content
4940 of large files well structured. It supports ToDo items, deadlines and
4941 time stamps, which magically appear in the diary listing of the Emacs
4942 calendar. Tables are easily created with a built-in table editor.
4943 Plain text URL-like links connect to websites, emails (VM), Usenet
4944 messages (Gnus), BBDB entries, and any files related to the project.
4945 For printing and sharing of notes, an Org-mode file (or a part of it)
4946 can be exported as a structured ASCII or HTML file.
4948 The following commands are available:
4950 \\{org-mode-map}"
4952 ;; Get rid of Outline menus, they are not needed
4953 ;; Need to do this here because define-derived-mode sets up
4954 ;; the keymap so late. Still, it is a waste to call this each time
4955 ;; we switch another buffer into org-mode.
4956 (if (featurep 'xemacs)
4957 (when (boundp 'outline-mode-menu-heading)
4958 ;; Assume this is Greg's port, it uses easymenu
4959 (easy-menu-remove outline-mode-menu-heading)
4960 (easy-menu-remove outline-mode-menu-show)
4961 (easy-menu-remove outline-mode-menu-hide))
4962 (define-key org-mode-map [menu-bar headings] 'undefined)
4963 (define-key org-mode-map [menu-bar hide] 'undefined)
4964 (define-key org-mode-map [menu-bar show] 'undefined))
4966 (org-load-modules-maybe)
4967 (easy-menu-add org-org-menu)
4968 (easy-menu-add org-tbl-menu)
4969 (org-install-agenda-files-menu)
4970 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4971 (add-to-invisibility-spec '(org-cwidth))
4972 (add-to-invisibility-spec '(org-hide-block . t))
4973 (when (featurep 'xemacs)
4974 (org-set-local 'line-move-ignore-invisible t))
4975 (org-set-local 'outline-regexp org-outline-regexp)
4976 (org-set-local 'outline-level 'org-outline-level)
4977 (setq bidi-paragraph-direction 'left-to-right)
4978 (when (and org-ellipsis
4979 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4980 (fboundp 'make-glyph-code))
4981 (unless org-display-table
4982 (setq org-display-table (make-display-table)))
4983 (set-display-table-slot
4984 org-display-table 4
4985 (vconcat (mapcar
4986 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4987 org-ellipsis)))
4988 (if (stringp org-ellipsis) org-ellipsis "..."))))
4989 (setq buffer-display-table org-display-table))
4990 (org-set-regexps-and-options)
4991 (when (and org-tag-faces (not org-tags-special-faces-re))
4992 ;; tag faces set outside customize.... force initialization.
4993 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4994 ;; Calc embedded
4995 (org-set-local 'calc-embedded-open-mode "# ")
4996 (modify-syntax-entry ?@ "w")
4997 (if org-startup-truncated (setq truncate-lines t))
4998 (org-set-local 'font-lock-unfontify-region-function
4999 'org-unfontify-region)
5000 ;; Activate before-change-function
5001 (org-set-local 'org-table-may-need-update t)
5002 (org-add-hook 'before-change-functions 'org-before-change-function nil
5003 'local)
5004 ;; Check for running clock before killing a buffer
5005 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5006 ;; Paragraphs and auto-filling
5007 (org-set-autofill-regexps)
5008 (setq indent-line-function 'org-indent-line-function)
5009 (org-update-radio-target-regexp)
5010 ;; Beginning/end of defun
5011 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5012 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5013 ;; Next error for sparse trees
5014 (org-set-local 'next-error-function 'org-occur-next-match)
5015 ;; Make sure dependence stuff works reliably, even for users who set it
5016 ;; too late :-(
5017 (if org-enforce-todo-dependencies
5018 (add-hook 'org-blocker-hook
5019 'org-block-todo-from-children-or-siblings-or-parent)
5020 (remove-hook 'org-blocker-hook
5021 'org-block-todo-from-children-or-siblings-or-parent))
5022 (if org-enforce-todo-checkbox-dependencies
5023 (add-hook 'org-blocker-hook
5024 'org-block-todo-from-checkboxes)
5025 (remove-hook 'org-blocker-hook
5026 'org-block-todo-from-checkboxes))
5028 ;; Comment characters
5029 (org-set-local 'comment-start "#")
5030 (org-set-local 'comment-padding " ")
5032 ;; Align options lines
5033 (org-set-local
5034 'align-mode-rules-list
5035 '((org-in-buffer-settings
5036 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5037 (modes . '(org-mode)))))
5039 ;; Imenu
5040 (org-set-local 'imenu-create-index-function
5041 'org-imenu-get-tree)
5043 ;; Make isearch reveal context
5044 (if (or (featurep 'xemacs)
5045 (not (boundp 'outline-isearch-open-invisible-function)))
5046 ;; Emacs 21 and XEmacs make use of the hook
5047 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5048 ;; Emacs 22 deals with this through a special variable
5049 (org-set-local 'outline-isearch-open-invisible-function
5050 (lambda (&rest ignore) (org-show-context 'isearch))))
5052 ;; Turn on org-beamer-mode?
5053 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5055 ;; Setup the pcomplete hooks
5056 (set (make-local-variable 'pcomplete-command-completion-function)
5057 'org-pcomplete-initial)
5058 (set (make-local-variable 'pcomplete-command-name-function)
5059 'org-command-at-point)
5060 (set (make-local-variable 'pcomplete-default-completion-function)
5061 'ignore)
5062 (set (make-local-variable 'pcomplete-parse-arguments-function)
5063 'org-parse-arguments)
5064 (set (make-local-variable 'pcomplete-termination-string) "")
5065 (set (make-local-variable 'face-remapping-alist)
5066 '((default org-default)))
5068 ;; If empty file that did not turn on org-mode automatically, make it to.
5069 (if (and org-insert-mode-line-in-empty-file
5070 (org-called-interactively-p 'any)
5071 (= (point-min) (point-max)))
5072 (insert "# -*- mode: org -*-\n\n"))
5073 (unless org-inhibit-startup
5074 (when org-startup-align-all-tables
5075 (let ((bmp (buffer-modified-p)))
5076 (org-table-map-tables 'org-table-align 'quietly)
5077 (set-buffer-modified-p bmp)))
5078 (when org-startup-with-inline-images
5079 (org-display-inline-images))
5080 (when org-startup-indented
5081 (require 'org-indent)
5082 (org-indent-mode 1))
5083 (unless org-inhibit-startup-visibility-stuff
5084 (org-set-startup-visibility))))
5086 (when (fboundp 'abbrev-table-put)
5087 (abbrev-table-put org-mode-abbrev-table
5088 :parents (list text-mode-abbrev-table)))
5090 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5092 (defun org-current-time ()
5093 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5094 (if (> (car org-time-stamp-rounding-minutes) 1)
5095 (let ((r (car org-time-stamp-rounding-minutes))
5096 (time (decode-time)))
5097 (apply 'encode-time
5098 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5099 (nthcdr 2 time))))
5100 (current-time)))
5102 (defun org-today ()
5103 "Return today date, considering `org-extend-today-until'."
5104 (time-to-days
5105 (time-subtract (current-time)
5106 (list 0 (* 3600 org-extend-today-until) 0))))
5108 ;;;; Font-Lock stuff, including the activators
5110 (defvar org-mouse-map (make-sparse-keymap))
5111 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5112 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5113 (when org-mouse-1-follows-link
5114 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5115 (when org-tab-follows-link
5116 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5117 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5119 (require 'font-lock)
5121 (defconst org-non-link-chars "]\t\n\r<>")
5122 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5123 "shell" "elisp" "doi" "message"))
5124 (defvar org-link-types-re nil
5125 "Matches a link that has a url-like prefix like \"http:\"")
5126 (defvar org-link-re-with-space nil
5127 "Matches a link with spaces, optional angular brackets around it.")
5128 (defvar org-link-re-with-space2 nil
5129 "Matches a link with spaces, optional angular brackets around it.")
5130 (defvar org-link-re-with-space3 nil
5131 "Matches a link with spaces, only for internal part in bracket links.")
5132 (defvar org-angle-link-re nil
5133 "Matches link with angular brackets, spaces are allowed.")
5134 (defvar org-plain-link-re nil
5135 "Matches plain link, without spaces.")
5136 (defvar org-bracket-link-regexp nil
5137 "Matches a link in double brackets.")
5138 (defvar org-bracket-link-analytic-regexp nil
5139 "Regular expression used to analyze links.
5140 Here is what the match groups contain after a match:
5141 1: http:
5142 2: http
5143 3: path
5144 4: [desc]
5145 5: desc")
5146 (defvar org-bracket-link-analytic-regexp++ nil
5147 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5148 (defvar org-any-link-re nil
5149 "Regular expression matching any link.")
5151 (defcustom org-match-sexp-depth 3
5152 "Number of stacked braces for sub/superscript matching.
5153 This has to be set before loading org.el to be effective."
5154 :group 'org-export-translation ; ??????????????????????????/
5155 :type 'integer)
5157 (defun org-create-multibrace-regexp (left right n)
5158 "Create a regular expression which will match a balanced sexp.
5159 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5160 as single character strings.
5161 The regexp returned will match the entire expression including the
5162 delimiters. It will also define a single group which contains the
5163 match except for the outermost delimiters. The maximum depth of
5164 stacked delimiters is N. Escaping delimiters is not possible."
5165 (let* ((nothing (concat "[^" left right "]*?"))
5166 (or "\\|")
5167 (re nothing)
5168 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5169 (while (> n 1)
5170 (setq n (1- n)
5171 re (concat re or next)
5172 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5173 (concat left "\\(" re "\\)" right)))
5175 (defvar org-match-substring-regexp
5176 (concat
5177 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5178 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5179 "\\|"
5180 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5181 "\\|"
5182 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5183 "The regular expression matching a sub- or superscript.")
5185 (defvar org-match-substring-with-braces-regexp
5186 (concat
5187 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5188 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5189 "\\)")
5190 "The regular expression matching a sub- or superscript, forcing braces.")
5192 (defun org-make-link-regexps ()
5193 "Update the link regular expressions.
5194 This should be called after the variable `org-link-types' has changed."
5195 (setq org-link-types-re
5196 (concat
5197 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5198 org-link-re-with-space
5199 (concat
5200 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5201 "\\([^" org-non-link-chars " ]"
5202 "[^" org-non-link-chars "]*"
5203 "[^" org-non-link-chars " ]\\)>?")
5204 org-link-re-with-space2
5205 (concat
5206 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5207 "\\([^" org-non-link-chars " ]"
5208 "[^\t\n\r]*"
5209 "[^" org-non-link-chars " ]\\)>?")
5210 org-link-re-with-space3
5211 (concat
5212 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^\t\n\r]*\\)")
5215 org-angle-link-re
5216 (concat
5217 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5218 "\\([^" org-non-link-chars " ]"
5219 "[^" org-non-link-chars "]*"
5220 "\\)>")
5221 org-plain-link-re
5222 (concat
5223 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5224 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5225 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5226 org-bracket-link-regexp
5227 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5228 org-bracket-link-analytic-regexp
5229 (concat
5230 "\\[\\["
5231 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5232 "\\([^]]+\\)"
5233 "\\]"
5234 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5235 "\\]")
5236 org-bracket-link-analytic-regexp++
5237 (concat
5238 "\\[\\["
5239 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5240 "\\([^]]+\\)"
5241 "\\]"
5242 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5243 "\\]")
5244 org-any-link-re
5245 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5246 org-angle-link-re "\\)\\|\\("
5247 org-plain-link-re "\\)")))
5249 (org-make-link-regexps)
5251 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5252 "Regular expression for fast time stamp matching.")
5253 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5254 "Regular expression for fast time stamp matching.")
5255 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5256 "Regular expression matching time strings for analysis.
5257 This one does not require the space after the date, so it can be used
5258 on a string that terminates immediately after the date.")
5259 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5260 "Regular expression matching time strings for analysis.")
5261 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5262 "Regular expression matching time stamps, with groups.")
5263 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5264 "Regular expression matching time stamps (also [..]), with groups.")
5265 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5266 "Regular expression matching a time stamp range.")
5267 (defconst org-tr-regexp-both
5268 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5269 "Regular expression matching a time stamp range.")
5270 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5271 org-ts-regexp "\\)?")
5272 "Regular expression matching a time stamp or time stamp range.")
5273 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5274 org-ts-regexp-both "\\)?")
5275 "Regular expression matching a time stamp or time stamp range.
5276 The time stamps may be either active or inactive.")
5278 (defvar org-emph-face nil)
5280 (defun org-do-emphasis-faces (limit)
5281 "Run through the buffer and add overlays to emphasized strings."
5282 (let (rtn a)
5283 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5284 (if (not (= (char-after (match-beginning 3))
5285 (char-after (match-beginning 4))))
5286 (progn
5287 (setq rtn t)
5288 (setq a (assoc (match-string 3) org-emphasis-alist))
5289 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5290 'face
5291 (nth 1 a))
5292 (and (nth 4 a)
5293 (org-remove-flyspell-overlays-in
5294 (match-beginning 0) (match-end 0)))
5295 (add-text-properties (match-beginning 2) (match-end 2)
5296 '(font-lock-multiline t org-emphasis t))
5297 (when org-hide-emphasis-markers
5298 (add-text-properties (match-end 4) (match-beginning 5)
5299 '(invisible org-link))
5300 (add-text-properties (match-beginning 3) (match-end 3)
5301 '(invisible org-link)))))
5302 (backward-char 1))
5303 rtn))
5305 (defun org-emphasize (&optional char)
5306 "Insert or change an emphasis, i.e. a font like bold or italic.
5307 If there is an active region, change that region to a new emphasis.
5308 If there is no region, just insert the marker characters and position
5309 the cursor between them.
5310 CHAR should be either the marker character, or the first character of the
5311 HTML tag associated with that emphasis. If CHAR is a space, the means
5312 to remove the emphasis of the selected region.
5313 If char is not given (for example in an interactive call) it
5314 will be prompted for."
5315 (interactive)
5316 (let ((eal org-emphasis-alist) e det
5317 (erc org-emphasis-regexp-components)
5318 (prompt "")
5319 (string "") beg end move tag c s)
5320 (if (org-region-active-p)
5321 (setq beg (region-beginning) end (region-end)
5322 string (buffer-substring beg end))
5323 (setq move t))
5325 (while (setq e (pop eal))
5326 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5327 c (aref tag 0))
5328 (push (cons c (string-to-char (car e))) det)
5329 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5330 (substring tag 1)))))
5331 (setq det (nreverse det))
5332 (unless char
5333 (message "%s" (concat "Emphasis marker or tag:" prompt))
5334 (setq char (read-char-exclusive)))
5335 (setq char (or (cdr (assoc char det)) char))
5336 (if (equal char ?\ )
5337 (setq s "" move nil)
5338 (unless (assoc (char-to-string char) org-emphasis-alist)
5339 (error "No such emphasis marker: \"%c\"" char))
5340 (setq s (char-to-string char)))
5341 (while (and (> (length string) 1)
5342 (equal (substring string 0 1) (substring string -1))
5343 (assoc (substring string 0 1) org-emphasis-alist))
5344 (setq string (substring string 1 -1)))
5345 (setq string (concat s string s))
5346 (if beg (delete-region beg end))
5347 (unless (or (bolp)
5348 (string-match (concat "[" (nth 0 erc) "\n]")
5349 (char-to-string (char-before (point)))))
5350 (insert " "))
5351 (unless (or (eobp)
5352 (string-match (concat "[" (nth 1 erc) "\n]")
5353 (char-to-string (char-after (point)))))
5354 (insert " ") (backward-char 1))
5355 (insert string)
5356 (and move (backward-char 1))))
5358 (defconst org-nonsticky-props
5359 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5361 (defsubst org-rear-nonsticky-at (pos)
5362 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5364 (defun org-activate-plain-links (limit)
5365 "Run through the buffer and add overlays to links."
5366 (catch 'exit
5367 (let (f)
5368 (if (re-search-forward org-plain-link-re limit t)
5369 (progn
5370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5371 (setq f (get-text-property (match-beginning 0) 'face))
5372 (if (or (eq f 'org-tag)
5373 (and (listp f) (memq 'org-tag f)))
5375 (add-text-properties (match-beginning 0) (match-end 0)
5376 (list 'mouse-face 'highlight
5377 'face 'org-link
5378 'keymap org-mouse-map))
5379 (org-rear-nonsticky-at (match-end 0)))
5380 t)))))
5382 (defun org-activate-code (limit)
5383 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5384 (progn
5385 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5386 (remove-text-properties (match-beginning 0) (match-end 0)
5387 '(display t invisible t intangible t))
5388 t)))
5390 (defcustom org-src-fontify-natively nil
5391 "When non-nil, fontify code in code blocks."
5392 :type 'boolean
5393 :version "24.1"
5394 :group 'org-appearance
5395 :group 'org-babel)
5397 (defun org-fontify-meta-lines-and-blocks (limit)
5398 (condition-case nil
5399 (org-fontify-meta-lines-and-blocks-1 limit)
5400 (error (message "org-mode fontification error"))))
5402 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5403 "Fontify #+ lines and blocks, in the correct ways."
5404 (let ((case-fold-search t))
5405 (if (re-search-forward
5406 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5407 limit t)
5408 (let ((beg (match-beginning 0))
5409 (block-start (match-end 0))
5410 (block-end nil)
5411 (lang (match-string 7))
5412 (beg1 (line-beginning-position 2))
5413 (dc1 (downcase (match-string 2)))
5414 (dc3 (downcase (match-string 3)))
5415 end end1 quoting block-type ovl)
5416 (cond
5417 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5418 ;; a single line of backend-specific content
5419 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5420 (remove-text-properties (match-beginning 0) (match-end 0)
5421 '(display t invisible t intangible t))
5422 (add-text-properties (match-beginning 1) (match-end 3)
5423 '(font-lock-fontified t face org-meta-line))
5424 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5425 '(font-lock-fontified t face org-block))
5426 ; for backend-specific code
5428 ((and (match-end 4) (equal dc3 "begin"))
5429 ;; Truly a block
5430 (setq block-type (downcase (match-string 5))
5431 quoting (member block-type org-protecting-blocks))
5432 (when (re-search-forward
5433 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5434 nil t) ;; on purpose, we look further than LIMIT
5435 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5436 (setq block-end (match-beginning 0))
5437 (when quoting
5438 (remove-text-properties beg end
5439 '(display t invisible t intangible t)))
5440 (add-text-properties
5441 beg end
5442 '(font-lock-fontified t font-lock-multiline t))
5443 (add-text-properties beg beg1 '(face org-meta-line))
5444 (add-text-properties end1 (min (point-max) (1+ end))
5445 '(face org-meta-line)) ; for end_src
5446 (cond
5447 ((and lang (not (string= lang "")) org-src-fontify-natively)
5448 (org-src-font-lock-fontify-block lang block-start block-end)
5449 ;; remove old background overlays
5450 (mapc (lambda (ov)
5451 (if (eq (overlay-get ov 'face) 'org-block-background)
5452 (delete-overlay ov)))
5453 (overlays-at (/ (+ beg1 block-end) 2)))
5454 ;; add a background overlay
5455 (setq ovl (make-overlay beg1 block-end))
5456 (overlay-put ovl 'face 'org-block-background)
5457 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5458 (quoting
5459 (add-text-properties beg1 (min (point-max) (1+ end1))
5460 '(face org-block))) ; end of source block
5461 ((not org-fontify-quote-and-verse-blocks))
5462 ((string= block-type "quote")
5463 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5464 ((string= block-type "verse")
5465 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5466 (add-text-properties beg beg1 '(face org-block-begin-line))
5467 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5469 ((member dc1 '("title:" "author:" "email:" "date:"))
5470 (add-text-properties
5471 beg (match-end 3)
5472 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5473 '(font-lock-fontified t invisible t)
5474 '(font-lock-fontified t face org-document-info-keyword)))
5475 (add-text-properties
5476 (match-beginning 6) (match-end 6)
5477 (if (string-equal dc1 "title:")
5478 '(font-lock-fontified t face org-document-title)
5479 '(font-lock-fontified t face org-document-info))))
5480 ((not (member (char-after beg) '(?\ ?\t)))
5481 ;; just any other in-buffer setting, but not indented
5482 (add-text-properties
5483 beg (1+ (match-end 0))
5484 '(font-lock-fontified t face org-meta-line))
5486 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5487 "orgtbl:" "tblfm:" "tblname:" "results:"
5488 "call:" "header:" "headers:" "name:"))
5489 (and (match-end 4) (equal dc3 "attr")))
5490 (add-text-properties
5491 beg (match-end 0)
5492 '(font-lock-fontified t face org-meta-line))
5494 ((member dc3 '(" " ""))
5495 (add-text-properties
5496 beg (match-end 0)
5497 '(font-lock-fontified t face font-lock-comment-face)))
5498 (t nil))))))
5500 (defun org-strip-protective-commas (beg end)
5501 "Strip protective commas between BEG and END in the current buffer."
5502 (interactive "r")
5503 (save-excursion
5504 (save-match-data
5505 (goto-char beg)
5506 (let ((front-line (save-excursion
5507 (re-search-forward
5508 "[^[:space:]]" end t)
5509 (goto-char (match-beginning 0))
5510 (current-column))))
5511 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5512 (goto-char (match-beginning 1))
5513 (when (= (current-column) front-line)
5514 (replace-match "" nil nil nil 1)))))))
5516 (defun org-activate-angle-links (limit)
5517 "Run through the buffer and add overlays to links."
5518 (if (re-search-forward org-angle-link-re limit t)
5519 (progn
5520 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5521 (add-text-properties (match-beginning 0) (match-end 0)
5522 (list 'mouse-face 'highlight
5523 'keymap org-mouse-map))
5524 (org-rear-nonsticky-at (match-end 0))
5525 t)))
5527 (defun org-activate-footnote-links (limit)
5528 "Run through the buffer and add overlays to footnotes."
5529 (let ((fn (org-footnote-next-reference-or-definition limit)))
5530 (when fn
5531 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5532 (org-remove-flyspell-overlays-in beg end)
5533 (add-text-properties beg end
5534 (list 'mouse-face 'highlight
5535 'keymap org-mouse-map
5536 'help-echo
5537 (if (= (point-at-bol) beg)
5538 "Footnote definition"
5539 "Footnote reference")
5540 'font-lock-fontified t
5541 'font-lock-multiline t
5542 'face 'org-footnote))))))
5544 (defun org-activate-bracket-links (limit)
5545 "Run through the buffer and add overlays to bracketed links."
5546 (if (re-search-forward org-bracket-link-regexp limit t)
5547 (let* ((help (concat "LINK: "
5548 (org-match-string-no-properties 1)))
5549 ;; FIXME: above we should remove the escapes.
5550 ;; but that requires another match, protecting match data,
5551 ;; a lot of overhead for font-lock.
5552 (ip (org-maybe-intangible
5553 (list 'invisible 'org-link
5554 'keymap org-mouse-map 'mouse-face 'highlight
5555 'font-lock-multiline t 'help-echo help)))
5556 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5557 'font-lock-multiline t 'help-echo help)))
5558 ;; We need to remove the invisible property here. Table narrowing
5559 ;; may have made some of this invisible.
5560 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5561 (remove-text-properties (match-beginning 0) (match-end 0)
5562 '(invisible nil))
5563 (if (match-end 3)
5564 (progn
5565 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5566 (org-rear-nonsticky-at (match-beginning 3))
5567 (add-text-properties (match-beginning 3) (match-end 3) vp)
5568 (org-rear-nonsticky-at (match-end 3))
5569 (add-text-properties (match-end 3) (match-end 0) ip)
5570 (org-rear-nonsticky-at (match-end 0)))
5571 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5572 (org-rear-nonsticky-at (match-beginning 1))
5573 (add-text-properties (match-beginning 1) (match-end 1) vp)
5574 (org-rear-nonsticky-at (match-end 1))
5575 (add-text-properties (match-end 1) (match-end 0) ip)
5576 (org-rear-nonsticky-at (match-end 0)))
5577 t)))
5579 (defun org-activate-dates (limit)
5580 "Run through the buffer and add overlays to dates."
5581 (if (re-search-forward org-tsr-regexp-both limit t)
5582 (progn
5583 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5584 (add-text-properties (match-beginning 0) (match-end 0)
5585 (list 'mouse-face 'highlight
5586 'keymap org-mouse-map))
5587 (org-rear-nonsticky-at (match-end 0))
5588 (when org-display-custom-times
5589 (if (match-end 3)
5590 (org-display-custom-time (match-beginning 3) (match-end 3)))
5591 (org-display-custom-time (match-beginning 1) (match-end 1)))
5592 t)))
5594 (defvar org-target-link-regexp nil
5595 "Regular expression matching radio targets in plain text.")
5596 (make-variable-buffer-local 'org-target-link-regexp)
5597 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5598 "Regular expression matching a link target.")
5599 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5600 "Regular expression matching a radio target.")
5601 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5602 "Regular expression matching any target.")
5604 (defun org-activate-target-links (limit)
5605 "Run through the buffer and add overlays to target matches."
5606 (when org-target-link-regexp
5607 (let ((case-fold-search t))
5608 (if (re-search-forward org-target-link-regexp limit t)
5609 (progn
5610 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5611 (add-text-properties (match-beginning 0) (match-end 0)
5612 (list 'mouse-face 'highlight
5613 'keymap org-mouse-map
5614 'help-echo "Radio target link"
5615 'org-linked-text t))
5616 (org-rear-nonsticky-at (match-end 0))
5617 t)))))
5619 (defun org-update-radio-target-regexp ()
5620 "Find all radio targets in this file and update the regular expression."
5621 (interactive)
5622 (when (memq 'radio org-activate-links)
5623 (setq org-target-link-regexp
5624 (org-make-target-link-regexp (org-all-targets 'radio)))
5625 (org-restart-font-lock)))
5627 (defun org-hide-wide-columns (limit)
5628 (let (s e)
5629 (setq s (text-property-any (point) (or limit (point-max))
5630 'org-cwidth t))
5631 (when s
5632 (setq e (next-single-property-change s 'org-cwidth))
5633 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5634 (goto-char e)
5635 t)))
5637 (defvar org-latex-and-specials-regexp nil
5638 "Regular expression for highlighting export special stuff.")
5639 (defvar org-match-substring-regexp)
5640 (defvar org-match-substring-with-braces-regexp)
5642 ;; This should be with the exporter code, but we also use if for font-locking
5643 (defconst org-export-html-special-string-regexps
5644 '(("\\\\-" . "&shy;")
5645 ("---\\([^-]\\)" . "&mdash;\\1")
5646 ("--\\([^-]\\)" . "&ndash;\\1")
5647 ("\\.\\.\\." . "&hellip;"))
5648 "Regular expressions for special string conversion.")
5651 (defun org-compute-latex-and-specials-regexp ()
5652 "Compute regular expression for stuff treated specially by exporters."
5653 (if (not org-highlight-latex-fragments-and-specials)
5654 (org-set-local 'org-latex-and-specials-regexp nil)
5655 (require 'org-exp)
5656 (let*
5657 ((matchers (plist-get org-format-latex-options :matchers))
5658 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5659 org-latex-regexps)))
5660 (org-export-allow-BIND nil)
5661 (options (org-combine-plists (org-default-export-plist)
5662 (org-infile-export-plist)))
5663 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5664 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5665 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5666 (org-export-html-expand (plist-get options :expand-quoted-html))
5667 (org-export-with-special-strings (plist-get options :special-strings))
5668 (re-sub
5669 (cond
5670 ((equal org-export-with-sub-superscripts '{})
5671 (list org-match-substring-with-braces-regexp))
5672 (org-export-with-sub-superscripts
5673 (list org-match-substring-regexp))
5674 (t nil)))
5675 (re-latex
5676 (if org-export-with-LaTeX-fragments
5677 (mapcar (lambda (x) (nth 1 x)) latexs)))
5678 (re-macros
5679 (if org-export-with-TeX-macros
5680 (list (concat "\\\\"
5681 (regexp-opt
5682 (append
5684 (delq nil
5685 (mapcar 'car-safe
5686 (append org-entities-user
5687 org-entities)))
5688 (if (boundp 'org-latex-entities)
5689 (mapcar (lambda (x)
5690 (or (car-safe x) x))
5691 org-latex-entities)
5692 nil))
5693 'words))) ; FIXME
5695 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5696 (re-special (if org-export-with-special-strings
5697 (mapcar (lambda (x) (car x))
5698 org-export-html-special-string-regexps)))
5699 (re-rest
5700 (delq nil
5701 (list
5702 (if org-export-html-expand "@<[^>\n]+>")
5703 ))))
5704 (org-set-local
5705 'org-latex-and-specials-regexp
5706 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5707 re-rest) "\\|")))))
5709 (defun org-do-latex-and-special-faces (limit)
5710 "Run through the buffer and add overlays to links."
5711 (when org-latex-and-specials-regexp
5712 (let (rtn d)
5713 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5714 limit t))
5715 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5716 'face))
5717 '(org-code org-verbatim underline)))
5718 (progn
5719 (setq rtn t
5720 d (cond ((member (char-after (1+ (match-beginning 0)))
5721 '(?_ ?^)) 1)
5722 (t 0)))
5723 (font-lock-prepend-text-property
5724 (+ d (match-beginning 0)) (match-end 0)
5725 'face 'org-latex-and-export-specials)
5726 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5727 '(font-lock-multiline t)))))
5728 rtn)))
5730 (defun org-restart-font-lock ()
5731 "Restart `font-lock-mode', to force refontification."
5732 (when (and (boundp 'font-lock-mode) font-lock-mode)
5733 (font-lock-mode -1)
5734 (font-lock-mode 1)))
5736 (defun org-all-targets (&optional radio)
5737 "Return a list of all targets in this file.
5738 With optional argument RADIO, only find radio targets."
5739 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5740 rtn)
5741 (save-excursion
5742 (goto-char (point-min))
5743 (while (re-search-forward re nil t)
5744 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5745 rtn)))
5747 (defun org-make-target-link-regexp (targets)
5748 "Make regular expression matching all strings in TARGETS.
5749 The regular expression finds the targets also if there is a line break
5750 between words."
5751 (and targets
5752 (concat
5753 "\\<\\("
5754 (mapconcat
5755 (lambda (x)
5756 (setq x (regexp-quote x))
5757 (while (string-match " +" x)
5758 (setq x (replace-match "\\s-+" t t x)))
5760 targets
5761 "\\|")
5762 "\\)\\>")))
5764 (defun org-activate-tags (limit)
5765 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5766 (progn
5767 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5768 (add-text-properties (match-beginning 1) (match-end 1)
5769 (list 'mouse-face 'highlight
5770 'keymap org-mouse-map))
5771 (org-rear-nonsticky-at (match-end 1))
5772 t)))
5774 (defun org-outline-level ()
5775 "Compute the outline level of the heading at point.
5776 This function assumes that the cursor is at the beginning of a line matched
5777 by `outline-regexp'. Otherwise it returns garbage.
5778 If this is called at a normal headline, the level is the number of stars.
5779 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5780 (save-excursion
5781 (looking-at org-outline-regexp)
5782 (1- (- (match-end 0) (match-beginning 0)))))
5784 (defvar org-font-lock-keywords nil)
5786 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5787 "Regular expression matching a property line.")
5789 (defvar org-font-lock-hook nil
5790 "Functions to be called for special font lock stuff.")
5792 (defvar org-font-lock-set-keywords-hook nil
5793 "Functions that can manipulate `org-font-lock-extra-keywords'.
5794 This is called after `org-font-lock-extra-keywords' is defined, but before
5795 it is installed to be used by font lock. This can be useful if something
5796 needs to be inserted at a specific position in the font-lock sequence.")
5798 (defun org-font-lock-hook (limit)
5799 (run-hook-with-args 'org-font-lock-hook limit))
5801 (defun org-set-font-lock-defaults ()
5802 (let* ((em org-fontify-emphasized-text)
5803 (lk org-activate-links)
5804 (org-font-lock-extra-keywords
5805 (list
5806 ;; Call the hook
5807 '(org-font-lock-hook)
5808 ;; Headlines
5809 `(,(if org-fontify-whole-heading-line
5810 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5811 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5812 (1 (org-get-level-face 1))
5813 (2 (org-get-level-face 2))
5814 (3 (org-get-level-face 3)))
5815 ;; Table lines
5816 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5817 (1 'org-table t))
5818 ;; Table internals
5819 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5820 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5821 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5822 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5823 ;; Drawers
5824 (list org-drawer-regexp '(0 'org-special-keyword t))
5825 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5826 ;; Properties
5827 (list org-property-re
5828 '(1 'org-special-keyword t)
5829 '(3 'org-property-value t))
5830 ;; Links
5831 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5832 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5833 (if (memq 'plain lk) '(org-activate-plain-links))
5834 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5835 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5836 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5837 (if (memq 'footnote lk) '(org-activate-footnote-links))
5838 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5839 '(org-hide-wide-columns (0 nil append))
5840 ;; TODO keyword
5841 (list (format org-heading-keyword-regexp-format
5842 org-todo-regexp)
5843 '(2 (org-get-todo-face 2) t))
5844 ;; DONE
5845 (if org-fontify-done-headline
5846 (list (format org-heading-keyword-regexp-format
5847 (concat
5848 "\\(?:"
5849 (mapconcat 'regexp-quote org-done-keywords "\\|")
5850 "\\)"))
5851 '(2 'org-headline-done t))
5852 nil)
5853 ;; Priorities
5854 '(org-font-lock-add-priority-faces)
5855 ;; Tags
5856 '(org-font-lock-add-tag-faces)
5857 ;; Special keywords
5858 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5859 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5860 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5861 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5862 ;; Emphasis
5863 (if em
5864 (if (featurep 'xemacs)
5865 '(org-do-emphasis-faces (0 nil append))
5866 '(org-do-emphasis-faces)))
5867 ;; Checkboxes
5868 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5869 1 'org-checkbox prepend)
5870 (if (cdr (assq 'checkbox org-list-automatic-rules))
5871 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5872 (0 (org-get-checkbox-statistics-face) t)))
5873 ;; Description list items
5874 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5875 1 'bold prepend)
5876 ;; ARCHIVEd headings
5877 (list (concat
5878 org-outline-regexp-bol
5879 "\\(.*:" org-archive-tag ":.*\\)")
5880 '(1 'org-archived prepend))
5881 ;; Specials
5882 '(org-do-latex-and-special-faces)
5883 '(org-fontify-entities)
5884 '(org-raise-scripts)
5885 ;; Code
5886 '(org-activate-code (1 'org-code t))
5887 ;; COMMENT
5888 (list (format org-heading-keyword-regexp-format
5889 (concat "\\("
5890 org-comment-string "\\|" org-quote-string
5891 "\\)"))
5892 '(2 'org-special-keyword t))
5893 '("^#.*" (0 'font-lock-comment-face t))
5894 ;; Blocks and meta lines
5895 '(org-fontify-meta-lines-and-blocks)
5897 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5898 (run-hooks 'org-font-lock-set-keywords-hook)
5899 ;; Now set the full font-lock-keywords
5900 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5901 (org-set-local 'font-lock-defaults
5902 '(org-font-lock-keywords t nil nil backward-paragraph))
5903 (kill-local-variable 'font-lock-keywords) nil))
5905 (defun org-toggle-pretty-entities ()
5906 "Toggle the composition display of entities as UTF8 characters."
5907 (interactive)
5908 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5909 (org-restart-font-lock)
5910 (if org-pretty-entities
5911 (message "Entities are displayed as UTF8 characters")
5912 (save-restriction
5913 (widen)
5914 (org-decompose-region (point-min) (point-max))
5915 (message "Entities are displayed plain"))))
5917 (defun org-fontify-entities (limit)
5918 "Find an entity to fontify."
5919 (let (ee)
5920 (when org-pretty-entities
5921 (catch 'match
5922 (while (re-search-forward
5923 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5924 limit t)
5925 (if (and (not (org-in-indented-comment-line))
5926 (setq ee (org-entity-get (match-string 1)))
5927 (= (length (nth 6 ee)) 1))
5928 (progn
5929 (add-text-properties
5930 (match-beginning 0) (match-end 1)
5931 (list 'font-lock-fontified t))
5932 (compose-region (match-beginning 0) (match-end 1)
5933 (nth 6 ee) nil)
5934 (backward-char 1)
5935 (throw 'match t))))
5936 nil))))
5938 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5939 "Fontify string S like in Org-mode."
5940 (with-temp-buffer
5941 (insert s)
5942 (let ((org-odd-levels-only odd-levels))
5943 (org-mode)
5944 (font-lock-fontify-buffer)
5945 (buffer-string))))
5947 (defvar org-m nil)
5948 (defvar org-l nil)
5949 (defvar org-f nil)
5950 (defun org-get-level-face (n)
5951 "Get the right face for match N in font-lock matching of headlines."
5952 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5953 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5954 (if org-cycle-level-faces
5955 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5956 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5957 (cond
5958 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5959 ((eq n 2) org-f)
5960 (t (if org-level-color-stars-only nil org-f))))
5963 (defun org-get-todo-face (kwd)
5964 "Get the right face for a TODO keyword KWD.
5965 If KWD is a number, get the corresponding match group."
5966 (if (numberp kwd) (setq kwd (match-string kwd)))
5967 (or (org-face-from-face-or-color
5968 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5969 (and (member kwd org-done-keywords) 'org-done)
5970 'org-todo))
5972 (defun org-face-from-face-or-color (context inherit face-or-color)
5973 "Create a face list that inherits INHERIT, but sets the foreground color.
5974 When FACE-OR-COLOR is not a string, just return it."
5975 (if (stringp face-or-color)
5976 (list :inherit inherit
5977 (cdr (assoc context org-faces-easy-properties))
5978 face-or-color)
5979 face-or-color))
5981 (defun org-font-lock-add-tag-faces (limit)
5982 "Add the special tag faces."
5983 (when (and org-tag-faces org-tags-special-faces-re)
5984 (while (re-search-forward org-tags-special-faces-re limit t)
5985 (add-text-properties (match-beginning 1) (match-end 1)
5986 (list 'face (org-get-tag-face 1)
5987 'font-lock-fontified t))
5988 (backward-char 1))))
5990 (defun org-font-lock-add-priority-faces (limit)
5991 "Add the special priority faces."
5992 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5993 (add-text-properties
5994 (match-beginning 0) (match-end 0)
5995 (list 'face (or (org-face-from-face-or-color
5996 'priority 'org-special-keyword
5997 (cdr (assoc (char-after (match-beginning 1))
5998 org-priority-faces)))
5999 'org-special-keyword)
6000 'font-lock-fontified t))))
6002 (defun org-get-tag-face (kwd)
6003 "Get the right face for a TODO keyword KWD.
6004 If KWD is a number, get the corresponding match group."
6005 (if (numberp kwd) (setq kwd (match-string kwd)))
6006 (or (org-face-from-face-or-color
6007 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6008 'org-tag))
6010 (defun org-unfontify-region (beg end &optional maybe_loudly)
6011 "Remove fontification and activation overlays from links."
6012 (font-lock-default-unfontify-region beg end)
6013 (let* ((buffer-undo-list t)
6014 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6015 (inhibit-modification-hooks t)
6016 deactivate-mark buffer-file-name buffer-file-truename)
6017 (org-decompose-region beg end)
6018 (remove-text-properties beg end
6019 '(mouse-face t keymap t org-linked-text t
6020 invisible t intangible t
6021 org-no-flyspell t org-emphasis t))
6022 (org-remove-font-lock-display-properties beg end)))
6024 (defconst org-script-display '(((raise -0.3) (height 0.7))
6025 ((raise 0.3) (height 0.7))
6026 ((raise -0.5))
6027 ((raise 0.5)))
6028 "Display properties for showing superscripts and subscripts.")
6030 (defun org-remove-font-lock-display-properties (beg end)
6031 "Remove specific display properties that have been added by font lock.
6032 The will remove the raise properties that are used to show superscripts
6033 and subscripts."
6034 (let (next prop)
6035 (while (< beg end)
6036 (setq next (next-single-property-change beg 'display nil end)
6037 prop (get-text-property beg 'display))
6038 (if (member prop org-script-display)
6039 (put-text-property beg next 'display nil))
6040 (setq beg next))))
6042 (defun org-raise-scripts (limit)
6043 "Add raise properties to sub/superscripts."
6044 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6045 (if (re-search-forward
6046 (if (eq org-use-sub-superscripts t)
6047 org-match-substring-regexp
6048 org-match-substring-with-braces-regexp)
6049 limit t)
6050 (let* ((pos (point)) table-p comment-p
6051 (mpos (match-beginning 3))
6052 (emph-p (get-text-property mpos 'org-emphasis))
6053 (link-p (get-text-property mpos 'mouse-face))
6054 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6055 (goto-char (point-at-bol))
6056 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6057 comment-p (org-looking-at-p "[ \t]*#"))
6058 (goto-char pos)
6059 ;; FIXME: Should we go back one character here, for a_b^c
6060 ;; (goto-char (1- pos)) ;????????????????????
6061 (if (or comment-p emph-p link-p keyw-p)
6063 (put-text-property (match-beginning 3) (match-end 0)
6064 'display
6065 (if (equal (char-after (match-beginning 2)) ?^)
6066 (nth (if table-p 3 1) org-script-display)
6067 (nth (if table-p 2 0) org-script-display)))
6068 (add-text-properties (match-beginning 2) (match-end 2)
6069 (list 'invisible t
6070 'org-dwidth t 'org-dwidth-n 1))
6071 (if (and (eq (char-after (match-beginning 3)) ?{)
6072 (eq (char-before (match-end 3)) ?}))
6073 (progn
6074 (add-text-properties
6075 (match-beginning 3) (1+ (match-beginning 3))
6076 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6077 (add-text-properties
6078 (1- (match-end 3)) (match-end 3)
6079 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6080 t)))))
6082 ;;;; Visibility cycling, including org-goto and indirect buffer
6084 ;;; Cycling
6086 (defvar org-cycle-global-status nil)
6087 (make-variable-buffer-local 'org-cycle-global-status)
6088 (defvar org-cycle-subtree-status nil)
6089 (make-variable-buffer-local 'org-cycle-subtree-status)
6091 ;;;###autoload
6093 (defvar org-inlinetask-min-level)
6095 (defun org-cycle (&optional arg)
6096 "TAB-action and visibility cycling for Org-mode.
6098 This is the command invoked in Org-mode by the TAB key. Its main purpose
6099 is outline visibility cycling, but it also invokes other actions
6100 in special contexts.
6102 - When this function is called with a prefix argument, rotate the entire
6103 buffer through 3 states (global cycling)
6104 1. OVERVIEW: Show only top-level headlines.
6105 2. CONTENTS: Show all headlines of all levels, but no body text.
6106 3. SHOW ALL: Show everything.
6107 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6108 determined by the variable `org-startup-folded', and by any VISIBILITY
6109 properties in the buffer.
6110 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6111 including any drawers.
6113 - When inside a table, re-align the table and move to the next field.
6115 - When point is at the beginning of a headline, rotate the subtree started
6116 by this line through 3 different states (local cycling)
6117 1. FOLDED: Only the main headline is shown.
6118 2. CHILDREN: The main headline and the direct children are shown.
6119 From this state, you can move to one of the children
6120 and zoom in further.
6121 3. SUBTREE: Show the entire subtree, including body text.
6122 If there is no subtree, switch directly from CHILDREN to FOLDED.
6124 - When point is at the beginning of an empty headline and the variable
6125 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6126 of the headline by demoting and promoting it to likely levels. This
6127 speeds up creation document structure by pressing TAB once or several
6128 times right after creating a new headline.
6130 - When there is a numeric prefix, go up to a heading with level ARG, do
6131 a `show-subtree' and return to the previous cursor position. If ARG
6132 is negative, go up that many levels.
6134 - When point is not at the beginning of a headline, execute the global
6135 binding for TAB, which is re-indenting the line. See the option
6136 `org-cycle-emulate-tab' for details.
6138 - Special case: if point is at the beginning of the buffer and there is
6139 no headline in line 1, this function will act as if called with prefix arg
6140 (C-u TAB, same as S-TAB) also when called without prefix arg.
6141 But only if also the variable `org-cycle-global-at-bob' is t."
6142 (interactive "P")
6143 (org-load-modules-maybe)
6144 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6145 (and org-cycle-level-after-item/entry-creation
6146 (or (org-cycle-level)
6147 (org-cycle-item-indentation))))
6148 (let* ((limit-level
6149 (or org-cycle-max-level
6150 (and (boundp 'org-inlinetask-min-level)
6151 org-inlinetask-min-level
6152 (1- org-inlinetask-min-level))))
6153 (nstars (and limit-level
6154 (if org-odd-levels-only
6155 (and limit-level (1- (* limit-level 2)))
6156 limit-level)))
6157 (org-outline-regexp
6158 (if (not (eq major-mode 'org-mode))
6159 outline-regexp
6160 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6161 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6162 (not (looking-at org-outline-regexp))))
6163 (org-cycle-hook
6164 (if bob-special
6165 (delq 'org-optimize-window-after-visibility-change
6166 (copy-sequence org-cycle-hook))
6167 org-cycle-hook))
6168 (pos (point)))
6170 (if (or bob-special (equal arg '(4)))
6171 ;; special case: use global cycling
6172 (setq arg t))
6174 (cond
6176 ((equal arg '(16))
6177 (setq last-command 'dummy)
6178 (org-set-startup-visibility)
6179 (message "Startup visibility, plus VISIBILITY properties"))
6181 ((equal arg '(64))
6182 (show-all)
6183 (message "Entire buffer visible, including drawers"))
6185 ;; Table: enter it or move to the next field.
6186 ((org-at-table-p 'any)
6187 (if (org-at-table.el-p)
6188 (message "Use C-c ' to edit table.el tables")
6189 (if arg (org-table-edit-field t)
6190 (org-table-justify-field-maybe)
6191 (call-interactively 'org-table-next-field))))
6193 ((run-hook-with-args-until-success
6194 'org-tab-after-check-for-table-hook))
6196 ;; Global cycling: delegate to `org-cycle-internal-global'.
6197 ((eq arg t) (org-cycle-internal-global))
6199 ;; Drawers: delegate to `org-flag-drawer'.
6200 ((and org-drawers org-drawer-regexp
6201 (save-excursion
6202 (beginning-of-line 1)
6203 (looking-at org-drawer-regexp)))
6204 (org-flag-drawer ; toggle block visibility
6205 (not (get-char-property (match-end 0) 'invisible))))
6207 ;; Show-subtree, ARG levels up from here.
6208 ((integerp arg)
6209 (save-excursion
6210 (org-back-to-heading)
6211 (outline-up-heading (if (< arg 0) (- arg)
6212 (- (funcall outline-level) arg)))
6213 (org-show-subtree)))
6215 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6216 ((and (featurep 'org-inlinetask)
6217 (org-inlinetask-at-task-p)
6218 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6219 (org-inlinetask-toggle-visibility))
6221 ((org-try-cdlatex-tab))
6223 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6224 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6225 (save-excursion (beginning-of-line 1)
6226 (looking-at org-outline-regexp)))
6227 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6228 (org-cycle-internal-local))
6230 ;; From there: TAB emulation and template completion.
6231 (buffer-read-only (org-back-to-heading))
6233 ((run-hook-with-args-until-success
6234 'org-tab-after-check-for-cycling-hook))
6236 ((org-try-structure-completion))
6238 ((run-hook-with-args-until-success
6239 'org-tab-before-tab-emulation-hook))
6241 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6242 (or (not (bolp))
6243 (not (looking-at org-outline-regexp))))
6244 (call-interactively (global-key-binding "\t")))
6246 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6247 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6248 (or (and (eq org-cycle-emulate-tab 'white)
6249 (= (match-end 0) (point-at-eol)))
6250 (and (eq org-cycle-emulate-tab 'whitestart)
6251 (>= (match-end 0) pos))))
6253 (eq org-cycle-emulate-tab t))
6254 (call-interactively (global-key-binding "\t")))
6256 (t (save-excursion
6257 (org-back-to-heading)
6258 (org-cycle)))))))
6260 (defun org-cycle-internal-global ()
6261 "Do the global cycling action."
6262 ;; Hack to avoid display of messages for .org attachments in Gnus
6263 (let ((ga (string-match "\\*fontification" (buffer-name))))
6264 (cond
6265 ((and (eq last-command this-command)
6266 (eq org-cycle-global-status 'overview))
6267 ;; We just created the overview - now do table of contents
6268 ;; This can be slow in very large buffers, so indicate action
6269 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6270 (unless ga (message "CONTENTS..."))
6271 (org-content)
6272 (unless ga (message "CONTENTS...done"))
6273 (setq org-cycle-global-status 'contents)
6274 (run-hook-with-args 'org-cycle-hook 'contents))
6276 ((and (eq last-command this-command)
6277 (eq org-cycle-global-status 'contents))
6278 ;; We just showed the table of contents - now show everything
6279 (run-hook-with-args 'org-pre-cycle-hook 'all)
6280 (show-all)
6281 (unless ga (message "SHOW ALL"))
6282 (setq org-cycle-global-status 'all)
6283 (run-hook-with-args 'org-cycle-hook 'all))
6286 ;; Default action: go to overview
6287 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6288 (org-overview)
6289 (unless ga (message "OVERVIEW"))
6290 (setq org-cycle-global-status 'overview)
6291 (run-hook-with-args 'org-cycle-hook 'overview)))))
6293 (defun org-cycle-internal-local ()
6294 "Do the local cycling action."
6295 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6296 ;; First, determine end of headline (EOH), end of subtree or item
6297 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6298 (save-excursion
6299 (if (org-at-item-p)
6300 (progn
6301 (beginning-of-line)
6302 (setq struct (org-list-struct))
6303 (setq eoh (point-at-eol))
6304 (setq eos (org-list-get-item-end-before-blank (point) struct))
6305 (setq has-children (org-list-has-child-p (point) struct)))
6306 (org-back-to-heading)
6307 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6308 (setq eos (save-excursion
6309 (org-end-of-subtree t)
6310 (unless (eobp)
6311 (skip-chars-forward " \t\n"))
6312 (if (eobp) (point) (1- (point)))))
6313 (setq has-children
6314 (or (save-excursion
6315 (let ((level (funcall outline-level)))
6316 (outline-next-heading)
6317 (and (org-at-heading-p t)
6318 (> (funcall outline-level) level))))
6319 (save-excursion
6320 (org-list-search-forward (org-item-beginning-re) eos t)))))
6321 ;; Determine end invisible part of buffer (EOL)
6322 (beginning-of-line 2)
6323 ;; XEmacs doesn't have `next-single-char-property-change'
6324 (if (featurep 'xemacs)
6325 (while (and (not (eobp)) ;; this is like `next-line'
6326 (get-char-property (1- (point)) 'invisible))
6327 (beginning-of-line 2))
6328 (while (and (not (eobp)) ;; this is like `next-line'
6329 (get-char-property (1- (point)) 'invisible))
6330 (goto-char (next-single-char-property-change (point) 'invisible))
6331 (and (eolp) (beginning-of-line 2))))
6332 (setq eol (point)))
6333 ;; Find out what to do next and set `this-command'
6334 (cond
6335 ((= eos eoh)
6336 ;; Nothing is hidden behind this heading
6337 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6338 (message "EMPTY ENTRY")
6339 (setq org-cycle-subtree-status nil)
6340 (save-excursion
6341 (goto-char eos)
6342 (outline-next-heading)
6343 (if (outline-invisible-p) (org-flag-heading nil))))
6344 ((and (or (>= eol eos)
6345 (not (string-match "\\S-" (buffer-substring eol eos))))
6346 (or has-children
6347 (not (setq children-skipped
6348 org-cycle-skip-children-state-if-no-children))))
6349 ;; Entire subtree is hidden in one line: children view
6350 (run-hook-with-args 'org-pre-cycle-hook 'children)
6351 (if (org-at-item-p)
6352 (org-list-set-item-visibility (point-at-bol) struct 'children)
6353 (org-show-entry)
6354 (org-with-limited-levels (show-children))
6355 (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6356 (org-cycle-hide-drawers 'subtree))
6357 ;; Fold every list in subtree to top-level items.
6358 (when (eq org-cycle-include-plain-lists 'integrate)
6359 (save-excursion
6360 (org-back-to-heading)
6361 (while (org-list-search-forward (org-item-beginning-re) eos t)
6362 (beginning-of-line 1)
6363 (let* ((struct (org-list-struct))
6364 (prevs (org-list-prevs-alist struct))
6365 (end (org-list-get-bottom-point struct)))
6366 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6367 (org-list-get-all-items (point) struct prevs))
6368 (goto-char end))))))
6369 (message "CHILDREN")
6370 (save-excursion
6371 (goto-char eos)
6372 (outline-next-heading)
6373 (if (outline-invisible-p) (org-flag-heading nil)))
6374 (setq org-cycle-subtree-status 'children)
6375 (run-hook-with-args 'org-cycle-hook 'children))
6376 ((or children-skipped
6377 (and (eq last-command this-command)
6378 (eq org-cycle-subtree-status 'children)))
6379 ;; We just showed the children, or no children are there,
6380 ;; now show everything.
6381 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6382 (outline-flag-region eoh eos nil)
6383 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6384 (setq org-cycle-subtree-status 'subtree)
6385 (run-hook-with-args 'org-cycle-hook 'subtree))
6387 ;; Default action: hide the subtree.
6388 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6389 (outline-flag-region eoh eos t)
6390 (message "FOLDED")
6391 (setq org-cycle-subtree-status 'folded)
6392 (run-hook-with-args 'org-cycle-hook 'folded)))))
6394 ;;;###autoload
6395 (defun org-global-cycle (&optional arg)
6396 "Cycle the global visibility. For details see `org-cycle'.
6397 With \\[universal-argument] prefix arg, switch to startup visibility.
6398 With a numeric prefix, show all headlines up to that level."
6399 (interactive "P")
6400 (let ((org-cycle-include-plain-lists
6401 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6402 (cond
6403 ((integerp arg)
6404 (show-all)
6405 (hide-sublevels arg)
6406 (setq org-cycle-global-status 'contents))
6407 ((equal arg '(4))
6408 (org-set-startup-visibility)
6409 (message "Startup visibility, plus VISIBILITY properties."))
6411 (org-cycle '(4))))))
6413 (defun org-set-startup-visibility ()
6414 "Set the visibility required by startup options and properties."
6415 (cond
6416 ((eq org-startup-folded t)
6417 (org-cycle '(4)))
6418 ((eq org-startup-folded 'content)
6419 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6420 (org-cycle '(4)) (org-cycle '(4)))))
6421 (unless (eq org-startup-folded 'showeverything)
6422 (if org-hide-block-startup (org-hide-block-all))
6423 (org-set-visibility-according-to-property 'no-cleanup)
6424 (org-cycle-hide-archived-subtrees 'all)
6425 (org-cycle-hide-drawers 'all)
6426 (org-cycle-show-empty-lines t)))
6428 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6429 "Switch subtree visibilities according to :VISIBILITY: property."
6430 (interactive)
6431 (let (org-show-entry-below state)
6432 (save-excursion
6433 (goto-char (point-min))
6434 (while (re-search-forward
6435 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6436 nil t)
6437 (setq state (match-string 1))
6438 (save-excursion
6439 (org-back-to-heading t)
6440 (hide-subtree)
6441 (org-reveal)
6442 (cond
6443 ((equal state '("fold" "folded"))
6444 (hide-subtree))
6445 ((equal state "children")
6446 (org-show-hidden-entry)
6447 (show-children))
6448 ((equal state "content")
6449 (save-excursion
6450 (save-restriction
6451 (org-narrow-to-subtree)
6452 (org-content))))
6453 ((member state '("all" "showall"))
6454 (show-subtree)))))
6455 (unless no-cleanup
6456 (org-cycle-hide-archived-subtrees 'all)
6457 (org-cycle-hide-drawers 'all)
6458 (org-cycle-show-empty-lines 'all)))))
6460 ;; This function uses outline-regexp instead of the more fundamental
6461 ;; org-outline-regexp so that org-cycle-global works outside of Org
6462 ;; buffers, where outline-regexp is needed.
6463 (defun org-overview ()
6464 "Switch to overview mode, showing only top-level headlines.
6465 Really, this shows all headlines with level equal or greater than the level
6466 of the first headline in the buffer. This is important, because if the
6467 first headline is not level one, then (hide-sublevels 1) gives confusing
6468 results."
6469 (interactive)
6470 (let ((level (save-excursion
6471 (goto-char (point-min))
6472 (if (re-search-forward (concat "^" outline-regexp) nil t)
6473 (progn
6474 (goto-char (match-beginning 0))
6475 (funcall outline-level))))))
6476 (and level (hide-sublevels level))))
6478 (defun org-content (&optional arg)
6479 "Show all headlines in the buffer, like a table of contents.
6480 With numerical argument N, show content up to level N."
6481 (interactive "P")
6482 (save-excursion
6483 ;; Visit all headings and show their offspring
6484 (and (integerp arg) (org-overview))
6485 (goto-char (point-max))
6486 (catch 'exit
6487 (while (and (progn (condition-case nil
6488 (outline-previous-visible-heading 1)
6489 (error (goto-char (point-min))))
6491 (looking-at org-outline-regexp))
6492 (if (integerp arg)
6493 (show-children (1- arg))
6494 (show-branches))
6495 (if (bobp) (throw 'exit nil))))))
6498 (defun org-optimize-window-after-visibility-change (state)
6499 "Adjust the window after a change in outline visibility.
6500 This function is the default value of the hook `org-cycle-hook'."
6501 (when (get-buffer-window (current-buffer))
6502 (cond
6503 ((eq state 'content) nil)
6504 ((eq state 'all) nil)
6505 ((eq state 'folded) nil)
6506 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6507 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6509 (defun org-remove-empty-overlays-at (pos)
6510 "Remove outline overlays that do not contain non-white stuff."
6511 (mapc
6512 (lambda (o)
6513 (and (eq 'outline (overlay-get o 'invisible))
6514 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6515 (overlay-end o))))
6516 (delete-overlay o)))
6517 (overlays-at pos)))
6519 (defun org-clean-visibility-after-subtree-move ()
6520 "Fix visibility issues after moving a subtree."
6521 ;; First, find a reasonable region to look at:
6522 ;; Start two siblings above, end three below
6523 (let* ((beg (save-excursion
6524 (and (org-get-last-sibling)
6525 (org-get-last-sibling))
6526 (point)))
6527 (end (save-excursion
6528 (and (org-get-next-sibling)
6529 (org-get-next-sibling)
6530 (org-get-next-sibling))
6531 (if (org-at-heading-p)
6532 (point-at-eol)
6533 (point))))
6534 (level (looking-at "\\*+"))
6535 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6536 (save-excursion
6537 (save-restriction
6538 (narrow-to-region beg end)
6539 (when re
6540 ;; Properly fold already folded siblings
6541 (goto-char (point-min))
6542 (while (re-search-forward re nil t)
6543 (if (and (not (outline-invisible-p))
6544 (save-excursion
6545 (goto-char (point-at-eol)) (outline-invisible-p)))
6546 (hide-entry))))
6547 (org-cycle-show-empty-lines 'overview)
6548 (org-cycle-hide-drawers 'overview)))))
6550 (defun org-cycle-show-empty-lines (state)
6551 "Show empty lines above all visible headlines.
6552 The region to be covered depends on STATE when called through
6553 `org-cycle-hook'. Lisp program can use t for STATE to get the
6554 entire buffer covered. Note that an empty line is only shown if there
6555 are at least `org-cycle-separator-lines' empty lines before the headline."
6556 (when (not (= org-cycle-separator-lines 0))
6557 (save-excursion
6558 (let* ((n (abs org-cycle-separator-lines))
6559 (re (cond
6560 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6561 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6562 (t (let ((ns (number-to-string (- n 2))))
6563 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6564 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6565 beg end b e)
6566 (cond
6567 ((memq state '(overview contents t))
6568 (setq beg (point-min) end (point-max)))
6569 ((memq state '(children folded))
6570 (setq beg (point) end (progn (org-end-of-subtree t t)
6571 (beginning-of-line 2)
6572 (point)))))
6573 (when beg
6574 (goto-char beg)
6575 (while (re-search-forward re end t)
6576 (unless (get-char-property (match-end 1) 'invisible)
6577 (setq e (match-end 1))
6578 (if (< org-cycle-separator-lines 0)
6579 (setq b (save-excursion
6580 (goto-char (match-beginning 0))
6581 (org-back-over-empty-lines)
6582 (if (save-excursion
6583 (goto-char (max (point-min) (1- (point))))
6584 (org-at-heading-p))
6585 (1- (point))
6586 (point))))
6587 (setq b (match-beginning 1)))
6588 (outline-flag-region b e nil)))))))
6589 ;; Never hide empty lines at the end of the file.
6590 (save-excursion
6591 (goto-char (point-max))
6592 (outline-previous-heading)
6593 (outline-end-of-heading)
6594 (if (and (looking-at "[ \t\n]+")
6595 (= (match-end 0) (point-max)))
6596 (outline-flag-region (point) (match-end 0) nil))))
6598 (defun org-show-empty-lines-in-parent ()
6599 "Move to the parent and re-show empty lines before visible headlines."
6600 (save-excursion
6601 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6602 (org-cycle-show-empty-lines context))))
6604 (defun org-files-list ()
6605 "Return `org-agenda-files' list, plus all open org-mode files.
6606 This is useful for operations that need to scan all of a user's
6607 open and agenda-wise Org files."
6608 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6609 (dolist (buf (buffer-list))
6610 (with-current-buffer buf
6611 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6612 (let ((file (expand-file-name (buffer-file-name))))
6613 (unless (member file files)
6614 (push file files))))))
6615 files))
6617 (defsubst org-entry-beginning-position ()
6618 "Return the beginning position of the current entry."
6619 (save-excursion (outline-back-to-heading t) (point)))
6621 (defsubst org-entry-end-position ()
6622 "Return the end position of the current entry."
6623 (save-excursion (outline-next-heading) (point)))
6625 (defun org-cycle-hide-drawers (state)
6626 "Re-hide all drawers after a visibility state change."
6627 (when (and (eq major-mode 'org-mode)
6628 (not (memq state '(overview folded contents))))
6629 (save-excursion
6630 (let* ((globalp (memq state '(contents all)))
6631 (beg (if globalp (point-min) (point)))
6632 (end (if globalp (point-max)
6633 (if (eq state 'children)
6634 (save-excursion (outline-next-heading) (point))
6635 (org-end-of-subtree t)))))
6636 (goto-char beg)
6637 (while (re-search-forward org-drawer-regexp end t)
6638 (org-flag-drawer t))))))
6640 (defun org-flag-drawer (flag)
6641 (save-excursion
6642 (beginning-of-line 1)
6643 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6644 (let ((b (match-end 0)))
6645 (if (re-search-forward
6646 "^[ \t]*:END:"
6647 (save-excursion (outline-next-heading) (point)) t)
6648 (outline-flag-region b (point-at-eol) flag)
6649 (error ":END: line missing at position %s" b))))))
6651 (defun org-subtree-end-visible-p ()
6652 "Is the end of the current subtree visible?"
6653 (pos-visible-in-window-p
6654 (save-excursion (org-end-of-subtree t) (point))))
6656 (defun org-first-headline-recenter (&optional N)
6657 "Move cursor to the first headline and recenter the headline.
6658 Optional argument N means put the headline into the Nth line of the window."
6659 (goto-char (point-min))
6660 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6661 (beginning-of-line)
6662 (recenter (prefix-numeric-value N))))
6664 ;;; Saving and restoring visibility
6666 (defun org-outline-overlay-data (&optional use-markers)
6667 "Return a list of the locations of all outline overlays.
6668 These are overlays with the `invisible' property value `outline'.
6669 The return value is a list of cons cells, with start and stop
6670 positions for each overlay.
6671 If USE-MARKERS is set, return the positions as markers."
6672 (let (beg end)
6673 (save-excursion
6674 (save-restriction
6675 (widen)
6676 (delq nil
6677 (mapcar (lambda (o)
6678 (when (eq (overlay-get o 'invisible) 'outline)
6679 (setq beg (overlay-start o)
6680 end (overlay-end o))
6681 (and beg end (> end beg)
6682 (if use-markers
6683 (cons (move-marker (make-marker) beg)
6684 (move-marker (make-marker) end))
6685 (cons beg end)))))
6686 (overlays-in (point-min) (point-max))))))))
6688 (defun org-set-outline-overlay-data (data)
6689 "Create visibility overlays for all positions in DATA.
6690 DATA should have been made by `org-outline-overlay-data'."
6691 (let (o)
6692 (save-excursion
6693 (save-restriction
6694 (widen)
6695 (show-all)
6696 (mapc (lambda (c)
6697 (outline-flag-region (car c) (cdr c) t))
6698 data)))))
6700 ;;; Folding of blocks
6702 (defvar org-hide-block-overlays nil
6703 "Overlays hiding blocks.")
6704 (make-variable-buffer-local 'org-hide-block-overlays)
6706 (defun org-block-map (function &optional start end)
6707 "Call FUNCTION at the head of all source blocks in the current buffer.
6708 Optional arguments START and END can be used to limit the range."
6709 (let ((start (or start (point-min)))
6710 (end (or end (point-max))))
6711 (save-excursion
6712 (goto-char start)
6713 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6714 (save-excursion
6715 (save-match-data
6716 (goto-char (match-beginning 0))
6717 (funcall function)))))))
6719 (defun org-hide-block-toggle-all ()
6720 "Toggle the visibility of all blocks in the current buffer."
6721 (org-block-map #'org-hide-block-toggle))
6723 (defun org-hide-block-all ()
6724 "Fold all blocks in the current buffer."
6725 (interactive)
6726 (org-show-block-all)
6727 (org-block-map #'org-hide-block-toggle-maybe))
6729 (defun org-show-block-all ()
6730 "Unfold all blocks in the current buffer."
6731 (interactive)
6732 (mapc 'delete-overlay org-hide-block-overlays)
6733 (setq org-hide-block-overlays nil))
6735 (defun org-hide-block-toggle-maybe ()
6736 "Toggle visibility of block at point."
6737 (interactive)
6738 (let ((case-fold-search t))
6739 (if (save-excursion
6740 (beginning-of-line 1)
6741 (looking-at org-block-regexp))
6742 (progn (org-hide-block-toggle)
6743 t) ;; to signal that we took action
6744 nil))) ;; to signal that we did not
6746 (defun org-hide-block-toggle (&optional force)
6747 "Toggle the visibility of the current block."
6748 (interactive)
6749 (save-excursion
6750 (beginning-of-line)
6751 (if (re-search-forward org-block-regexp nil t)
6752 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6753 (end (match-end 0)) ;; end of entire body
6755 (if (memq t (mapcar (lambda (overlay)
6756 (eq (overlay-get overlay 'invisible)
6757 'org-hide-block))
6758 (overlays-at start)))
6759 (if (or (not force) (eq force 'off))
6760 (mapc (lambda (ov)
6761 (when (member ov org-hide-block-overlays)
6762 (setq org-hide-block-overlays
6763 (delq ov org-hide-block-overlays)))
6764 (when (eq (overlay-get ov 'invisible)
6765 'org-hide-block)
6766 (delete-overlay ov)))
6767 (overlays-at start)))
6768 (setq ov (make-overlay start end))
6769 (overlay-put ov 'invisible 'org-hide-block)
6770 ;; make the block accessible to isearch
6771 (overlay-put
6772 ov 'isearch-open-invisible
6773 (lambda (ov)
6774 (when (member ov org-hide-block-overlays)
6775 (setq org-hide-block-overlays
6776 (delq ov org-hide-block-overlays)))
6777 (when (eq (overlay-get ov 'invisible)
6778 'org-hide-block)
6779 (delete-overlay ov))))
6780 (push ov org-hide-block-overlays)))
6781 (error "Not looking at a source block"))))
6783 ;; org-tab-after-check-for-cycling-hook
6784 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6785 ;; Remove overlays when changing major mode
6786 (add-hook 'org-mode-hook
6787 (lambda () (org-add-hook 'change-major-mode-hook
6788 'org-show-block-all 'append 'local)))
6790 ;;; Org-goto
6792 (defvar org-goto-window-configuration nil)
6793 (defvar org-goto-marker nil)
6794 (defvar org-goto-map
6795 (let ((map (make-sparse-keymap)))
6796 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6797 (while (setq cmd (pop cmds))
6798 (substitute-key-definition cmd cmd map global-map)))
6799 (suppress-keymap map)
6800 (org-defkey map "\C-m" 'org-goto-ret)
6801 (org-defkey map [(return)] 'org-goto-ret)
6802 (org-defkey map [(left)] 'org-goto-left)
6803 (org-defkey map [(right)] 'org-goto-right)
6804 (org-defkey map [(control ?g)] 'org-goto-quit)
6805 (org-defkey map "\C-i" 'org-cycle)
6806 (org-defkey map [(tab)] 'org-cycle)
6807 (org-defkey map [(down)] 'outline-next-visible-heading)
6808 (org-defkey map [(up)] 'outline-previous-visible-heading)
6809 (if org-goto-auto-isearch
6810 (if (fboundp 'define-key-after)
6811 (define-key-after map [t] 'org-goto-local-auto-isearch)
6812 nil)
6813 (org-defkey map "q" 'org-goto-quit)
6814 (org-defkey map "n" 'outline-next-visible-heading)
6815 (org-defkey map "p" 'outline-previous-visible-heading)
6816 (org-defkey map "f" 'outline-forward-same-level)
6817 (org-defkey map "b" 'outline-backward-same-level)
6818 (org-defkey map "u" 'outline-up-heading))
6819 (org-defkey map "/" 'org-occur)
6820 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6821 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6822 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6823 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6824 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6825 map))
6827 (defconst org-goto-help
6828 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6829 RET=jump to location [Q]uit and return to previous location
6830 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6832 (defvar org-goto-start-pos) ; dynamically scoped parameter
6834 ;; FIXME: Docstring does not mention both interfaces
6835 (defun org-goto (&optional alternative-interface)
6836 "Look up a different location in the current file, keeping current visibility.
6838 When you want look-up or go to a different location in a document, the
6839 fastest way is often to fold the entire buffer and then dive into the tree.
6840 This method has the disadvantage, that the previous location will be folded,
6841 which may not be what you want.
6843 This command works around this by showing a copy of the current buffer
6844 in an indirect buffer, in overview mode. You can dive into the tree in
6845 that copy, use org-occur and incremental search to find a location.
6846 When pressing RET or `Q', the command returns to the original buffer in
6847 which the visibility is still unchanged. After RET is will also jump to
6848 the location selected in the indirect buffer and expose the headline
6849 hierarchy above."
6850 (interactive "P")
6851 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6852 (org-refile-use-outline-path t)
6853 (org-refile-target-verify-function nil)
6854 (interface
6855 (if (not alternative-interface)
6856 org-goto-interface
6857 (if (eq org-goto-interface 'outline)
6858 'outline-path-completion
6859 'outline)))
6860 (org-goto-start-pos (point))
6861 (selected-point
6862 (if (eq interface 'outline)
6863 (car (org-get-location (current-buffer) org-goto-help))
6864 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6865 (org-refile-check-position pa)
6866 (nth 3 pa)))))
6867 (if selected-point
6868 (progn
6869 (org-mark-ring-push org-goto-start-pos)
6870 (goto-char selected-point)
6871 (if (or (outline-invisible-p) (org-invisible-p2))
6872 (org-show-context 'org-goto)))
6873 (message "Quit"))))
6875 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6876 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6877 (defvar org-goto-local-auto-isearch-map) ; defined below
6879 (defun org-get-location (buf help)
6880 "Let the user select a location in the Org-mode buffer BUF.
6881 This function uses a recursive edit. It returns the selected position
6882 or nil."
6883 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6884 (isearch-hide-immediately nil)
6885 (isearch-search-fun-function
6886 (lambda () 'org-goto-local-search-headings))
6887 (org-goto-selected-point org-goto-exit-command)
6888 (pop-up-frames nil)
6889 (special-display-buffer-names nil)
6890 (special-display-regexps nil)
6891 (special-display-function nil))
6892 (save-excursion
6893 (save-window-excursion
6894 (delete-other-windows)
6895 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6896 (org-pop-to-buffer-same-window
6897 (condition-case nil
6898 (make-indirect-buffer (current-buffer) "*org-goto*")
6899 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6900 (with-output-to-temp-buffer "*Help*"
6901 (princ help))
6902 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6903 (setq buffer-read-only nil)
6904 (let ((org-startup-truncated t)
6905 (org-startup-folded nil)
6906 (org-startup-align-all-tables nil))
6907 (org-mode)
6908 (org-overview))
6909 (setq buffer-read-only t)
6910 (if (and (boundp 'org-goto-start-pos)
6911 (integer-or-marker-p org-goto-start-pos))
6912 (let ((org-show-hierarchy-above t)
6913 (org-show-siblings t)
6914 (org-show-following-heading t))
6915 (goto-char org-goto-start-pos)
6916 (and (outline-invisible-p) (org-show-context)))
6917 (goto-char (point-min)))
6918 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6919 (message "Select location and press RET")
6920 (use-local-map org-goto-map)
6921 (recursive-edit)
6923 (kill-buffer "*org-goto*")
6924 (cons org-goto-selected-point org-goto-exit-command)))
6926 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6927 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6928 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6929 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6931 (defun org-goto-local-search-headings (string bound noerror)
6932 "Search and make sure that any matches are in headlines."
6933 (catch 'return
6934 (while (if isearch-forward
6935 (search-forward string bound noerror)
6936 (search-backward string bound noerror))
6937 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6938 (and (member :headline context)
6939 (not (member :tags context))))
6940 (throw 'return (point))))))
6942 (defun org-goto-local-auto-isearch ()
6943 "Start isearch."
6944 (interactive)
6945 (goto-char (point-min))
6946 (let ((keys (this-command-keys)))
6947 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6948 (isearch-mode t)
6949 (isearch-process-search-char (string-to-char keys)))))
6951 (defun org-goto-ret (&optional arg)
6952 "Finish `org-goto' by going to the new location."
6953 (interactive "P")
6954 (setq org-goto-selected-point (point)
6955 org-goto-exit-command 'return)
6956 (throw 'exit nil))
6958 (defun org-goto-left ()
6959 "Finish `org-goto' by going to the new location."
6960 (interactive)
6961 (if (org-at-heading-p)
6962 (progn
6963 (beginning-of-line 1)
6964 (setq org-goto-selected-point (point)
6965 org-goto-exit-command 'left)
6966 (throw 'exit nil))
6967 (error "Not on a heading")))
6969 (defun org-goto-right ()
6970 "Finish `org-goto' by going to the new location."
6971 (interactive)
6972 (if (org-at-heading-p)
6973 (progn
6974 (setq org-goto-selected-point (point)
6975 org-goto-exit-command 'right)
6976 (throw 'exit nil))
6977 (error "Not on a heading")))
6979 (defun org-goto-quit ()
6980 "Finish `org-goto' without cursor motion."
6981 (interactive)
6982 (setq org-goto-selected-point nil)
6983 (setq org-goto-exit-command 'quit)
6984 (throw 'exit nil))
6986 ;;; Indirect buffer display of subtrees
6988 (defvar org-indirect-dedicated-frame nil
6989 "This is the frame being used for indirect tree display.")
6990 (defvar org-last-indirect-buffer nil)
6992 (defun org-tree-to-indirect-buffer (&optional arg)
6993 "Create indirect buffer and narrow it to current subtree.
6994 With numerical prefix ARG, go up to this level and then take that tree.
6995 If ARG is negative, go up that many levels.
6996 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6997 indirect buffer previously made with this command, to avoid proliferation of
6998 indirect buffers. However, when you call the command with a \
6999 \\[universal-argument] prefix, or
7000 when `org-indirect-buffer-display' is `new-frame', the last buffer
7001 is kept so that you can work with several indirect buffers at the same time.
7002 If `org-indirect-buffer-display' is `dedicated-frame', the \
7003 \\[universal-argument] prefix also
7004 requests that a new frame be made for the new buffer, so that the dedicated
7005 frame is not changed."
7006 (interactive "P")
7007 (let ((cbuf (current-buffer))
7008 (cwin (selected-window))
7009 (pos (point))
7010 beg end level heading ibuf)
7011 (save-excursion
7012 (org-back-to-heading t)
7013 (when (numberp arg)
7014 (setq level (org-outline-level))
7015 (if (< arg 0) (setq arg (+ level arg)))
7016 (while (> (setq level (org-outline-level)) arg)
7017 (outline-up-heading 1 t)))
7018 (setq beg (point)
7019 heading (org-get-heading))
7020 (org-end-of-subtree t t)
7021 (if (org-at-heading-p) (backward-char 1))
7022 (setq end (point)))
7023 (if (and (buffer-live-p org-last-indirect-buffer)
7024 (not (eq org-indirect-buffer-display 'new-frame))
7025 (not arg))
7026 (kill-buffer org-last-indirect-buffer))
7027 (setq ibuf (org-get-indirect-buffer cbuf)
7028 org-last-indirect-buffer ibuf)
7029 (cond
7030 ((or (eq org-indirect-buffer-display 'new-frame)
7031 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7032 (select-frame (make-frame))
7033 (delete-other-windows)
7034 (org-pop-to-buffer-same-window ibuf)
7035 (org-set-frame-title heading))
7036 ((eq org-indirect-buffer-display 'dedicated-frame)
7037 (raise-frame
7038 (select-frame (or (and org-indirect-dedicated-frame
7039 (frame-live-p org-indirect-dedicated-frame)
7040 org-indirect-dedicated-frame)
7041 (setq org-indirect-dedicated-frame (make-frame)))))
7042 (delete-other-windows)
7043 (org-pop-to-buffer-same-window ibuf)
7044 (org-set-frame-title (concat "Indirect: " heading)))
7045 ((eq org-indirect-buffer-display 'current-window)
7046 (org-pop-to-buffer-same-window ibuf))
7047 ((eq org-indirect-buffer-display 'other-window)
7048 (pop-to-buffer ibuf))
7049 (t (error "Invalid value")))
7050 (if (featurep 'xemacs)
7051 (save-excursion (org-mode) (turn-on-font-lock)))
7052 (narrow-to-region beg end)
7053 (show-all)
7054 (goto-char pos)
7055 (run-hook-with-args 'org-cycle-hook 'all)
7056 (and (window-live-p cwin) (select-window cwin))))
7058 (defun org-get-indirect-buffer (&optional buffer)
7059 (setq buffer (or buffer (current-buffer)))
7060 (let ((n 1) (base (buffer-name buffer)) bname)
7061 (while (buffer-live-p
7062 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7063 (setq n (1+ n)))
7064 (condition-case nil
7065 (make-indirect-buffer buffer bname 'clone)
7066 (error (make-indirect-buffer buffer bname)))))
7068 (defun org-set-frame-title (title)
7069 "Set the title of the current frame to the string TITLE."
7070 ;; FIXME: how to name a single frame in XEmacs???
7071 (unless (featurep 'xemacs)
7072 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7074 ;;;; Structure editing
7076 ;;; Inserting headlines
7078 (defun org-previous-line-empty-p ()
7079 (save-excursion
7080 (and (not (bobp))
7081 (or (beginning-of-line 0) t)
7082 (save-match-data
7083 (looking-at "[ \t]*$")))))
7085 (defun org-insert-heading (&optional force-heading invisible-ok)
7086 "Insert a new heading or item with same depth at point.
7087 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7088 If point is at the beginning of a headline, insert a sibling before the
7089 current headline. If point is not at the beginning, split the line,
7090 create the new headline with the text in the current line after point
7091 \(but see also the variable `org-M-RET-may-split-line').
7093 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7094 This is important for non-interactive uses of the command."
7095 (interactive "P")
7096 (if (or (= (buffer-size) 0)
7097 (and (not (save-excursion
7098 (and (ignore-errors (org-back-to-heading invisible-ok))
7099 (org-at-heading-p))))
7100 (or force-heading (not (org-in-item-p)))))
7101 (progn
7102 (insert "\n* ")
7103 (run-hooks 'org-insert-heading-hook))
7104 (when (or force-heading (not (org-insert-item)))
7105 (let* ((empty-line-p nil)
7106 (level nil)
7107 (on-heading (org-at-heading-p))
7108 (head (save-excursion
7109 (condition-case nil
7110 (progn
7111 (org-back-to-heading invisible-ok)
7112 (when (and (not on-heading)
7113 (featurep 'org-inlinetask)
7114 (integerp org-inlinetask-min-level)
7115 (>= (length (match-string 0))
7116 org-inlinetask-min-level))
7117 ;; Find a heading level before the inline task
7118 (while (and (setq level (org-up-heading-safe))
7119 (>= level org-inlinetask-min-level)))
7120 (if (org-at-heading-p)
7121 (org-back-to-heading invisible-ok)
7122 (error "This should not happen")))
7123 (setq empty-line-p (org-previous-line-empty-p))
7124 (match-string 0))
7125 (error "*"))))
7126 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7127 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7128 pos hide-previous previous-pos)
7129 (cond
7130 ((and (org-at-heading-p) (bolp)
7131 (or (bobp)
7132 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7133 ;; insert before the current line
7134 (open-line (if blank 2 1)))
7135 ((and (bolp)
7136 (not org-insert-heading-respect-content)
7137 (or (bobp)
7138 (save-excursion
7139 (backward-char 1) (not (outline-invisible-p)))))
7140 ;; insert right here
7141 nil)
7143 ;; somewhere in the line
7144 (save-excursion
7145 (setq previous-pos (point-at-bol))
7146 (end-of-line)
7147 (setq hide-previous (outline-invisible-p)))
7148 (and org-insert-heading-respect-content (org-show-subtree))
7149 (let ((split
7150 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7151 (save-excursion
7152 (let ((p (point)))
7153 (goto-char (point-at-bol))
7154 (and (looking-at org-complex-heading-regexp)
7155 (match-beginning 4)
7156 (> p (match-beginning 4)))))))
7157 tags pos)
7158 (cond
7159 (org-insert-heading-respect-content
7160 (org-end-of-subtree nil t)
7161 (when (featurep 'org-inlinetask)
7162 (while (and (not (eobp))
7163 (looking-at "\\(\\*+\\)[ \t]+")
7164 (>= (length (match-string 1))
7165 org-inlinetask-min-level))
7166 (org-end-of-subtree nil t)))
7167 (or (bolp) (newline))
7168 (or (org-previous-line-empty-p)
7169 (and blank (newline)))
7170 (open-line 1))
7171 ((org-at-heading-p)
7172 (when hide-previous
7173 (show-children)
7174 (org-show-entry))
7175 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7176 (setq tags (and (match-end 2) (match-string 2)))
7177 (and (match-end 1)
7178 (delete-region (match-beginning 1) (match-end 1)))
7179 (setq pos (point-at-bol))
7180 (or split (end-of-line 1))
7181 (delete-horizontal-space)
7182 (if (string-match "\\`\\*+\\'"
7183 (buffer-substring (point-at-bol) (point)))
7184 (insert " "))
7185 (newline (if blank 2 1))
7186 (when tags
7187 (save-excursion
7188 (goto-char pos)
7189 (end-of-line 1)
7190 (insert " " tags)
7191 (org-set-tags nil 'align))))
7193 (or split (end-of-line 1))
7194 (newline (if blank 2 1)))))))
7195 (insert head) (just-one-space)
7196 (setq pos (point))
7197 (end-of-line 1)
7198 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7199 (when (and org-insert-heading-respect-content hide-previous)
7200 (save-excursion
7201 (goto-char previous-pos)
7202 (hide-subtree)))
7203 (run-hooks 'org-insert-heading-hook)))))
7205 (defun org-get-heading (&optional no-tags no-todo)
7206 "Return the heading of the current entry, without the stars.
7207 When NO-TAGS is non-nil, don't include tags.
7208 When NO-TODO is non-nil, don't include TODO keywords."
7209 (save-excursion
7210 (org-back-to-heading t)
7211 (cond
7212 ((and no-tags no-todo)
7213 (looking-at org-complex-heading-regexp)
7214 (match-string 4))
7215 (no-tags
7216 (looking-at (concat org-outline-regexp
7217 "\\(.*?\\)"
7218 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7219 (match-string 1))
7220 (no-todo
7221 (looking-at org-todo-line-regexp)
7222 (match-string 3))
7223 (t (looking-at org-heading-regexp)
7224 (match-string 2)))))
7226 (defun org-heading-components ()
7227 "Return the components of the current heading.
7228 This is a list with the following elements:
7229 - the level as an integer
7230 - the reduced level, different if `org-odd-levels-only' is set.
7231 - the TODO keyword, or nil
7232 - the priority character, like ?A, or nil if no priority is given
7233 - the headline text itself, or the tags string if no headline text
7234 - the tags string, or nil."
7235 (save-excursion
7236 (org-back-to-heading t)
7237 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7238 (list (length (match-string 1))
7239 (org-reduced-level (length (match-string 1)))
7240 (org-match-string-no-properties 2)
7241 (and (match-end 3) (aref (match-string 3) 2))
7242 (org-match-string-no-properties 4)
7243 (org-match-string-no-properties 5)))))
7245 (defun org-get-entry ()
7246 "Get the entry text, after heading, entire subtree."
7247 (save-excursion
7248 (org-back-to-heading t)
7249 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7251 (defun org-insert-heading-after-current ()
7252 "Insert a new heading with same level as current, after current subtree."
7253 (interactive)
7254 (org-back-to-heading)
7255 (org-insert-heading)
7256 (org-move-subtree-down)
7257 (end-of-line 1))
7259 (defun org-insert-heading-respect-content ()
7260 (interactive)
7261 (let ((org-insert-heading-respect-content t))
7262 (org-insert-heading t)))
7264 (defun org-insert-todo-heading-respect-content (&optional force-state)
7265 (interactive "P")
7266 (let ((org-insert-heading-respect-content t))
7267 (org-insert-todo-heading force-state t)))
7269 (defun org-insert-todo-heading (arg &optional force-heading)
7270 "Insert a new heading with the same level and TODO state as current heading.
7271 If the heading has no TODO state, or if the state is DONE, use the first
7272 state (TODO by default). Also with prefix arg, force first state."
7273 (interactive "P")
7274 (when (or force-heading (not (org-insert-item 'checkbox)))
7275 (org-insert-heading force-heading)
7276 (save-excursion
7277 (org-back-to-heading)
7278 (outline-previous-heading)
7279 (looking-at org-todo-line-regexp))
7280 (let*
7281 ((new-mark-x
7282 (if (or arg
7283 (not (match-beginning 2))
7284 (member (match-string 2) org-done-keywords))
7285 (car org-todo-keywords-1)
7286 (match-string 2)))
7287 (new-mark
7289 (run-hook-with-args-until-success
7290 'org-todo-get-default-hook new-mark-x nil)
7291 new-mark-x)))
7292 (beginning-of-line 1)
7293 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7294 (if org-treat-insert-todo-heading-as-state-change
7295 (org-todo new-mark)
7296 (insert new-mark " "))))
7297 (when org-provide-todo-statistics
7298 (org-update-parent-todo-statistics))))
7300 (defun org-insert-subheading (arg)
7301 "Insert a new subheading and demote it.
7302 Works for outline headings and for plain lists alike."
7303 (interactive "P")
7304 (org-insert-heading arg)
7305 (cond
7306 ((org-at-heading-p) (org-do-demote))
7307 ((org-at-item-p) (org-indent-item))))
7309 (defun org-insert-todo-subheading (arg)
7310 "Insert a new subheading with TODO keyword or checkbox and demote it.
7311 Works for outline headings and for plain lists alike."
7312 (interactive "P")
7313 (org-insert-todo-heading arg)
7314 (cond
7315 ((org-at-heading-p) (org-do-demote))
7316 ((org-at-item-p) (org-indent-item))))
7318 ;;; Promotion and Demotion
7320 (defvar org-after-demote-entry-hook nil
7321 "Hook run after an entry has been demoted.
7322 The cursor will be at the beginning of the entry.
7323 When a subtree is being demoted, the hook will be called for each node.")
7325 (defvar org-after-promote-entry-hook nil
7326 "Hook run after an entry has been promoted.
7327 The cursor will be at the beginning of the entry.
7328 When a subtree is being promoted, the hook will be called for each node.")
7330 (defun org-promote-subtree ()
7331 "Promote the entire subtree.
7332 See also `org-promote'."
7333 (interactive)
7334 (save-excursion
7335 (org-with-limited-levels (org-map-tree 'org-promote)))
7336 (org-fix-position-after-promote))
7338 (defun org-demote-subtree ()
7339 "Demote the entire subtree. See `org-demote'.
7340 See also `org-promote'."
7341 (interactive)
7342 (save-excursion
7343 (org-with-limited-levels (org-map-tree 'org-demote)))
7344 (org-fix-position-after-promote))
7347 (defun org-do-promote ()
7348 "Promote the current heading higher up the tree.
7349 If the region is active in `transient-mark-mode', promote all headings
7350 in the region."
7351 (interactive)
7352 (save-excursion
7353 (if (org-region-active-p)
7354 (org-map-region 'org-promote (region-beginning) (region-end))
7355 (org-promote)))
7356 (org-fix-position-after-promote))
7358 (defun org-do-demote ()
7359 "Demote the current heading lower down the tree.
7360 If the region is active in `transient-mark-mode', demote all headings
7361 in the region."
7362 (interactive)
7363 (save-excursion
7364 (if (org-region-active-p)
7365 (org-map-region 'org-demote (region-beginning) (region-end))
7366 (org-demote)))
7367 (org-fix-position-after-promote))
7369 (defun org-fix-position-after-promote ()
7370 "Make sure that after pro/demotion cursor position is right."
7371 (let ((pos (point)))
7372 (when (save-excursion
7373 (beginning-of-line 1)
7374 (looking-at org-todo-line-regexp)
7375 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7376 (cond ((eobp) (insert " "))
7377 ((eolp) (insert " "))
7378 ((equal (char-after) ?\ ) (forward-char 1))))))
7380 (defun org-current-level ()
7381 "Return the level of the current entry, or nil if before the first headline.
7382 The level is the number of stars at the beginning of the headline."
7383 (save-excursion
7384 (org-with-limited-levels
7385 (if (ignore-errors (org-back-to-heading t))
7386 (funcall outline-level)))))
7388 (defun org-get-previous-line-level ()
7389 "Return the outline depth of the last headline before the current line.
7390 Returns 0 for the first headline in the buffer, and nil if before the
7391 first headline."
7392 (let ((current-level (org-current-level))
7393 (prev-level (when (> (line-number-at-pos) 1)
7394 (save-excursion
7395 (beginning-of-line 0)
7396 (org-current-level)))))
7397 (cond ((null current-level) nil) ; Before first headline
7398 ((null prev-level) 0) ; At first headline
7399 (prev-level))))
7401 (defun org-reduced-level (l)
7402 "Compute the effective level of a heading.
7403 This takes into account the setting of `org-odd-levels-only'."
7404 (cond
7405 ((zerop l) 0)
7406 (org-odd-levels-only (1+ (floor (/ l 2))))
7407 (t l)))
7409 (defun org-level-increment ()
7410 "Return the number of stars that will be added or removed at a
7411 time to headlines when structure editing, based on the value of
7412 `org-odd-levels-only'."
7413 (if org-odd-levels-only 2 1))
7415 (defun org-get-valid-level (level &optional change)
7416 "Rectify a level change under the influence of `org-odd-levels-only'
7417 LEVEL is a current level, CHANGE is by how much the level should be
7418 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7419 even level numbers will become the next higher odd number."
7420 (if org-odd-levels-only
7421 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7422 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7423 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7424 (max 1 (+ level (or change 0)))))
7426 (if (boundp 'define-obsolete-function-alias)
7427 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7428 (define-obsolete-function-alias 'org-get-legal-level
7429 'org-get-valid-level)
7430 (define-obsolete-function-alias 'org-get-legal-level
7431 'org-get-valid-level "23.1")))
7433 (defun org-promote ()
7434 "Promote the current heading higher up the tree.
7435 If the region is active in `transient-mark-mode', promote all headings
7436 in the region."
7437 (org-back-to-heading t)
7438 (let* ((level (save-match-data (funcall outline-level)))
7439 (after-change-functions (remove 'flyspell-after-change-function
7440 after-change-functions))
7441 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7442 (diff (abs (- level (length up-head) -1))))
7443 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7444 (replace-match up-head nil t)
7445 ;; Fixup tag positioning
7446 (and org-auto-align-tags (org-set-tags nil t))
7447 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7448 (run-hooks 'org-after-promote-entry-hook)))
7450 (defun org-demote ()
7451 "Demote the current heading lower down the tree.
7452 If the region is active in `transient-mark-mode', demote all headings
7453 in the region."
7454 (org-back-to-heading t)
7455 (let* ((level (save-match-data (funcall outline-level)))
7456 (after-change-functions (remove 'flyspell-after-change-function
7457 after-change-functions))
7458 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7459 (diff (abs (- level (length down-head) -1))))
7460 (replace-match down-head nil t)
7461 ;; Fixup tag positioning
7462 (and org-auto-align-tags (org-set-tags nil t))
7463 (if org-adapt-indentation (org-fixup-indentation diff))
7464 (run-hooks 'org-after-demote-entry-hook)))
7466 (defun org-cycle-level ()
7467 "Cycle the level of an empty headline through possible states.
7468 This goes first to child, then to parent, level, then up the hierarchy.
7469 After top level, it switches back to sibling level."
7470 (interactive)
7471 (let ((org-adapt-indentation nil))
7472 (when (org-point-at-end-of-empty-headline)
7473 (setq this-command 'org-cycle-level) ; Only needed for caching
7474 (let ((cur-level (org-current-level))
7475 (prev-level (org-get-previous-line-level)))
7476 (cond
7477 ;; If first headline in file, promote to top-level.
7478 ((= prev-level 0)
7479 (loop repeat (/ (- cur-level 1) (org-level-increment))
7480 do (org-do-promote)))
7481 ;; If same level as prev, demote one.
7482 ((= prev-level cur-level)
7483 (org-do-demote))
7484 ;; If parent is top-level, promote to top level if not already.
7485 ((= prev-level 1)
7486 (loop repeat (/ (- cur-level 1) (org-level-increment))
7487 do (org-do-promote)))
7488 ;; If top-level, return to prev-level.
7489 ((= cur-level 1)
7490 (loop repeat (/ (- prev-level 1) (org-level-increment))
7491 do (org-do-demote)))
7492 ;; If less than prev-level, promote one.
7493 ((< cur-level prev-level)
7494 (org-do-promote))
7495 ;; If deeper than prev-level, promote until higher than
7496 ;; prev-level.
7497 ((> cur-level prev-level)
7498 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7499 do (org-do-promote))))
7500 t))))
7502 (defun org-map-tree (fun)
7503 "Call FUN for every heading underneath the current one."
7504 (org-back-to-heading)
7505 (let ((level (funcall outline-level)))
7506 (save-excursion
7507 (funcall fun)
7508 (while (and (progn
7509 (outline-next-heading)
7510 (> (funcall outline-level) level))
7511 (not (eobp)))
7512 (funcall fun)))))
7514 (defun org-map-region (fun beg end)
7515 "Call FUN for every heading between BEG and END."
7516 (let ((org-ignore-region t))
7517 (save-excursion
7518 (setq end (copy-marker end))
7519 (goto-char beg)
7520 (if (and (re-search-forward org-outline-regexp-bol nil t)
7521 (< (point) end))
7522 (funcall fun))
7523 (while (and (progn
7524 (outline-next-heading)
7525 (< (point) end))
7526 (not (eobp)))
7527 (funcall fun)))))
7529 (defvar org-property-end-re) ; silence byte-compiler
7530 (defun org-fixup-indentation (diff)
7531 "Change the indentation in the current entry by DIFF.
7532 However, if any line in the current entry has no indentation, or if it
7533 would end up with no indentation after the change, nothing at all is done."
7534 (save-excursion
7535 (let ((end (save-excursion (outline-next-heading)
7536 (point-marker)))
7537 (prohibit (if (> diff 0)
7538 "^\\S-"
7539 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7540 col)
7541 (unless (save-excursion (end-of-line 1)
7542 (re-search-forward prohibit end t))
7543 (while (and (< (point) end)
7544 (re-search-forward "^[ \t]+" end t))
7545 (goto-char (match-end 0))
7546 (setq col (current-column))
7547 (if (< diff 0) (replace-match ""))
7548 (org-indent-to-column (+ diff col))))
7549 (move-marker end nil))))
7551 (defun org-convert-to-odd-levels ()
7552 "Convert an org-mode file with all levels allowed to one with odd levels.
7553 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7554 level 5 etc."
7555 (interactive)
7556 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7557 (let ((outline-level 'org-outline-level)
7558 (org-odd-levels-only nil) n)
7559 (save-excursion
7560 (goto-char (point-min))
7561 (while (re-search-forward "^\\*\\*+ " nil t)
7562 (setq n (- (length (match-string 0)) 2))
7563 (while (>= (setq n (1- n)) 0)
7564 (org-demote))
7565 (end-of-line 1))))))
7567 (defun org-convert-to-oddeven-levels ()
7568 "Convert an org-mode file with only odd levels to one with odd/even levels.
7569 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7570 file contains a section with an even level, conversion would
7571 destroy the structure of the file. An error is signaled in this
7572 case."
7573 (interactive)
7574 (goto-char (point-min))
7575 ;; First check if there are no even levels
7576 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7577 (org-show-context t)
7578 (error "Not all levels are odd in this file. Conversion not possible"))
7579 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7580 (let ((outline-regexp org-outline-regexp)
7581 (outline-level 'org-outline-level)
7582 (org-odd-levels-only nil) n)
7583 (save-excursion
7584 (goto-char (point-min))
7585 (while (re-search-forward "^\\*\\*+ " nil t)
7586 (setq n (/ (1- (length (match-string 0))) 2))
7587 (while (>= (setq n (1- n)) 0)
7588 (org-promote))
7589 (end-of-line 1))))))
7591 (defun org-tr-level (n)
7592 "Make N odd if required."
7593 (if org-odd-levels-only (1+ (/ n 2)) n))
7595 ;;; Vertical tree motion, cutting and pasting of subtrees
7597 (defun org-move-subtree-up (&optional arg)
7598 "Move the current subtree up past ARG headlines of the same level."
7599 (interactive "p")
7600 (org-move-subtree-down (- (prefix-numeric-value arg))))
7602 (defun org-move-subtree-down (&optional arg)
7603 "Move the current subtree down past ARG headlines of the same level."
7604 (interactive "p")
7605 (setq arg (prefix-numeric-value arg))
7606 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7607 'org-get-last-sibling))
7608 (ins-point (make-marker))
7609 (cnt (abs arg))
7610 (col (current-column))
7611 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7612 ;; Select the tree
7613 (org-back-to-heading)
7614 (setq beg0 (point))
7615 (save-excursion
7616 (setq ne-beg (org-back-over-empty-lines))
7617 (setq beg (point)))
7618 (save-match-data
7619 (save-excursion (outline-end-of-heading)
7620 (setq folded (outline-invisible-p)))
7621 (outline-end-of-subtree))
7622 (outline-next-heading)
7623 (setq ne-end (org-back-over-empty-lines))
7624 (setq end (point))
7625 (goto-char beg0)
7626 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7627 ;; include less whitespace
7628 (save-excursion
7629 (goto-char beg)
7630 (forward-line (- ne-beg ne-end))
7631 (setq beg (point))))
7632 ;; Find insertion point, with error handling
7633 (while (> cnt 0)
7634 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7635 (progn (goto-char beg0)
7636 (error "Cannot move past superior level or buffer limit")))
7637 (setq cnt (1- cnt)))
7638 (if (> arg 0)
7639 ;; Moving forward - still need to move over subtree
7640 (progn (org-end-of-subtree t t)
7641 (save-excursion
7642 (org-back-over-empty-lines)
7643 (or (bolp) (newline)))))
7644 (setq ne-ins (org-back-over-empty-lines))
7645 (move-marker ins-point (point))
7646 (setq txt (buffer-substring beg end))
7647 (org-save-markers-in-region beg end)
7648 (delete-region beg end)
7649 (org-remove-empty-overlays-at beg)
7650 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7651 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7652 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7653 (let ((bbb (point)))
7654 (insert-before-markers txt)
7655 (org-reinstall-markers-in-region bbb)
7656 (move-marker ins-point bbb))
7657 (or (bolp) (insert "\n"))
7658 (setq ins-end (point))
7659 (goto-char ins-point)
7660 (org-skip-whitespace)
7661 (when (and (< arg 0)
7662 (org-first-sibling-p)
7663 (> ne-ins ne-beg))
7664 ;; Move whitespace back to beginning
7665 (save-excursion
7666 (goto-char ins-end)
7667 (let ((kill-whole-line t))
7668 (kill-line (- ne-ins ne-beg)) (point)))
7669 (insert (make-string (- ne-ins ne-beg) ?\n)))
7670 (move-marker ins-point nil)
7671 (if folded
7672 (hide-subtree)
7673 (org-show-entry)
7674 (show-children)
7675 (org-cycle-hide-drawers 'children))
7676 (org-clean-visibility-after-subtree-move)
7677 ;; move back to the initial column we were at
7678 (move-to-column col)))
7680 (defvar org-subtree-clip ""
7681 "Clipboard for cut and paste of subtrees.
7682 This is actually only a copy of the kill, because we use the normal kill
7683 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7685 (defvar org-subtree-clip-folded nil
7686 "Was the last copied subtree folded?
7687 This is used to fold the tree back after pasting.")
7689 (defun org-cut-subtree (&optional n)
7690 "Cut the current subtree into the clipboard.
7691 With prefix arg N, cut this many sequential subtrees.
7692 This is a short-hand for marking the subtree and then cutting it."
7693 (interactive "p")
7694 (org-copy-subtree n 'cut))
7696 (defun org-copy-subtree (&optional n cut force-store-markers)
7697 "Cut the current subtree into the clipboard.
7698 With prefix arg N, cut this many sequential subtrees.
7699 This is a short-hand for marking the subtree and then copying it.
7700 If CUT is non-nil, actually cut the subtree.
7701 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7702 of some markers in the region, even if CUT is non-nil. This is
7703 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7704 (interactive "p")
7705 (let (beg end folded (beg0 (point)))
7706 (if (org-called-interactively-p 'any)
7707 (org-back-to-heading nil) ; take what looks like a subtree
7708 (org-back-to-heading t)) ; take what is really there
7709 (org-back-over-empty-lines)
7710 (setq beg (point))
7711 (skip-chars-forward " \t\r\n")
7712 (save-match-data
7713 (save-excursion (outline-end-of-heading)
7714 (setq folded (outline-invisible-p)))
7715 (condition-case nil
7716 (org-forward-same-level (1- n) t)
7717 (error nil))
7718 (org-end-of-subtree t t))
7719 (org-back-over-empty-lines)
7720 (setq end (point))
7721 (goto-char beg0)
7722 (when (> end beg)
7723 (setq org-subtree-clip-folded folded)
7724 (when (or cut force-store-markers)
7725 (org-save-markers-in-region beg end))
7726 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7727 (setq org-subtree-clip (current-kill 0))
7728 (message "%s: Subtree(s) with %d characters"
7729 (if cut "Cut" "Copied")
7730 (length org-subtree-clip)))))
7732 (defun org-paste-subtree (&optional level tree for-yank)
7733 "Paste the clipboard as a subtree, with modification of headline level.
7734 The entire subtree is promoted or demoted in order to match a new headline
7735 level.
7737 If the cursor is at the beginning of a headline, the same level as
7738 that headline is used to paste the tree
7740 If not, the new level is derived from the *visible* headings
7741 before and after the insertion point, and taken to be the inferior headline
7742 level of the two. So if the previous visible heading is level 3 and the
7743 next is level 4 (or vice versa), level 4 will be used for insertion.
7744 This makes sure that the subtree remains an independent subtree and does
7745 not swallow low level entries.
7747 You can also force a different level, either by using a numeric prefix
7748 argument, or by inserting the heading marker by hand. For example, if the
7749 cursor is after \"*****\", then the tree will be shifted to level 5.
7751 If optional TREE is given, use this text instead of the kill ring.
7753 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7754 move back over whitespace before inserting, and move point to the end of
7755 the inserted text when done."
7756 (interactive "P")
7757 (setq tree (or tree (and kill-ring (current-kill 0))))
7758 (unless (org-kill-is-subtree-p tree)
7759 (error "%s"
7760 (substitute-command-keys
7761 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7762 (org-with-limited-levels
7763 (let* ((visp (not (outline-invisible-p)))
7764 (txt tree)
7765 (^re_ "\\(\\*+\\)[ \t]*")
7766 (old-level (if (string-match org-outline-regexp-bol txt)
7767 (- (match-end 0) (match-beginning 0) 1)
7768 -1))
7769 (force-level (cond (level (prefix-numeric-value level))
7770 ((and (looking-at "[ \t]*$")
7771 (string-match
7772 "^\\*+$" (buffer-substring
7773 (point-at-bol) (point))))
7774 (- (match-end 1) (match-beginning 1)))
7775 ((and (bolp)
7776 (looking-at org-outline-regexp))
7777 (- (match-end 0) (point) 1))
7778 (t nil)))
7779 (previous-level (save-excursion
7780 (condition-case nil
7781 (progn
7782 (outline-previous-visible-heading 1)
7783 (if (looking-at ^re_)
7784 (- (match-end 0) (match-beginning 0) 1)
7786 (error 1))))
7787 (next-level (save-excursion
7788 (condition-case nil
7789 (progn
7790 (or (looking-at org-outline-regexp)
7791 (outline-next-visible-heading 1))
7792 (if (looking-at ^re_)
7793 (- (match-end 0) (match-beginning 0) 1)
7795 (error 1))))
7796 (new-level (or force-level (max previous-level next-level)))
7797 (shift (if (or (= old-level -1)
7798 (= new-level -1)
7799 (= old-level new-level))
7801 (- new-level old-level)))
7802 (delta (if (> shift 0) -1 1))
7803 (func (if (> shift 0) 'org-demote 'org-promote))
7804 (org-odd-levels-only nil)
7805 beg end newend)
7806 ;; Remove the forced level indicator
7807 (if force-level
7808 (delete-region (point-at-bol) (point)))
7809 ;; Paste
7810 (beginning-of-line (if (bolp) 1 2))
7811 (unless for-yank (org-back-over-empty-lines))
7812 (setq beg (point))
7813 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7814 (insert-before-markers txt)
7815 (unless (string-match "\n\\'" txt) (insert "\n"))
7816 (setq newend (point))
7817 (org-reinstall-markers-in-region beg)
7818 (setq end (point))
7819 (goto-char beg)
7820 (skip-chars-forward " \t\n\r")
7821 (setq beg (point))
7822 (if (and (outline-invisible-p) visp)
7823 (save-excursion (outline-show-heading)))
7824 ;; Shift if necessary
7825 (unless (= shift 0)
7826 (save-restriction
7827 (narrow-to-region beg end)
7828 (while (not (= shift 0))
7829 (org-map-region func (point-min) (point-max))
7830 (setq shift (+ delta shift)))
7831 (goto-char (point-min))
7832 (setq newend (point-max))))
7833 (when (or (org-called-interactively-p 'interactive) for-yank)
7834 (message "Clipboard pasted as level %d subtree" new-level))
7835 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7836 kill-ring
7837 (eq org-subtree-clip (current-kill 0))
7838 org-subtree-clip-folded)
7839 ;; The tree was folded before it was killed/copied
7840 (hide-subtree))
7841 (and for-yank (goto-char newend)))))
7843 (defun org-kill-is-subtree-p (&optional txt)
7844 "Check if the current kill is an outline subtree, or a set of trees.
7845 Returns nil if kill does not start with a headline, or if the first
7846 headline level is not the largest headline level in the tree.
7847 So this will actually accept several entries of equal levels as well,
7848 which is OK for `org-paste-subtree'.
7849 If optional TXT is given, check this string instead of the current kill."
7850 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7851 (re (org-get-limited-outline-regexp))
7852 (^re (concat "^" re))
7853 (start-level (and kill
7854 (string-match
7855 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7856 kill)
7857 (- (match-end 2) (match-beginning 2) 1)))
7858 (start (1+ (or (match-beginning 2) -1))))
7859 (if (not start-level)
7860 (progn
7861 nil) ;; does not even start with a heading
7862 (catch 'exit
7863 (while (setq start (string-match ^re kill (1+ start)))
7864 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7865 (throw 'exit nil)))
7866 t))))
7868 (defvar org-markers-to-move nil
7869 "Markers that should be moved with a cut-and-paste operation.
7870 Those markers are stored together with their positions relative to
7871 the start of the region.")
7873 (defun org-save-markers-in-region (beg end)
7874 "Check markers in region.
7875 If these markers are between BEG and END, record their position relative
7876 to BEG, so that after moving the block of text, we can put the markers back
7877 into place.
7878 This function gets called just before an entry or tree gets cut from the
7879 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7880 called immediately, to move the markers with the entries."
7881 (setq org-markers-to-move nil)
7882 (when (featurep 'org-clock)
7883 (org-clock-save-markers-for-cut-and-paste beg end))
7884 (when (featurep 'org-agenda)
7885 (org-agenda-save-markers-for-cut-and-paste beg end)))
7887 (defun org-check-and-save-marker (marker beg end)
7888 "Check if MARKER is between BEG and END.
7889 If yes, remember the marker and the distance to BEG."
7890 (when (and (marker-buffer marker)
7891 (equal (marker-buffer marker) (current-buffer)))
7892 (if (and (>= marker beg) (< marker end))
7893 (push (cons marker (- marker beg)) org-markers-to-move))))
7895 (defun org-reinstall-markers-in-region (beg)
7896 "Move all remembered markers to their position relative to BEG."
7897 (mapc (lambda (x)
7898 (move-marker (car x) (+ beg (cdr x))))
7899 org-markers-to-move)
7900 (setq org-markers-to-move nil))
7902 (defun org-narrow-to-subtree ()
7903 "Narrow buffer to the current subtree."
7904 (interactive)
7905 (save-excursion
7906 (save-match-data
7907 (org-with-limited-levels
7908 (narrow-to-region
7909 (progn (org-back-to-heading t) (point))
7910 (progn (org-end-of-subtree t t)
7911 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7912 (point)))))))
7914 (defun org-narrow-to-block ()
7915 "Narrow buffer to the current block."
7916 (interactive)
7917 (let* ((case-fold-search t)
7918 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7919 "^[ \t]*#\\+end_.*")))
7920 (if blockp
7921 (narrow-to-region (car blockp) (cdr blockp))
7922 (error "Not in a block"))))
7924 (eval-when-compile
7925 (defvar org-property-drawer-re))
7927 (defvar org-property-start-re) ;; defined below
7928 (defun org-clone-subtree-with-time-shift (n &optional shift)
7929 "Clone the task (subtree) at point N times.
7930 The clones will be inserted as siblings.
7932 In interactive use, the user will be prompted for the number of
7933 clones to be produced, and for a time SHIFT, which may be a
7934 repeater as used in time stamps, for example `+3d'.
7936 When a valid repeater is given and the entry contains any time
7937 stamps, the clones will become a sequence in time, with time
7938 stamps in the subtree shifted for each clone produced. If SHIFT
7939 is nil or the empty string, time stamps will be left alone. The
7940 ID property of the original subtree is removed.
7942 If the original subtree did contain time stamps with a repeater,
7943 the following will happen:
7944 - the repeater will be removed in each clone
7945 - an additional clone will be produced, with the current, unshifted
7946 date(s) in the entry.
7947 - the original entry will be placed *after* all the clones, with
7948 repeater intact.
7949 - the start days in the repeater in the original entry will be shifted
7950 to past the last clone.
7951 In this way you can spell out a number of instances of a repeating task,
7952 and still retain the repeater to cover future instances of the task."
7953 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7954 (let (beg end template task idprop
7955 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7956 (drawer-re org-drawer-regexp))
7957 (if (not (and (integerp n) (> n 0)))
7958 (error "Invalid number of replications %s" n))
7959 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7960 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7961 shift)))
7962 (error "Invalid shift specification %s" shift))
7963 (when doshift
7964 (setq shift-n (string-to-number (match-string 1 shift))
7965 shift-what (cdr (assoc (match-string 2 shift)
7966 '(("d" . day) ("w" . week)
7967 ("m" . month) ("y" . year))))))
7968 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7969 (setq nmin 1 nmax n)
7970 (org-back-to-heading t)
7971 (setq beg (point))
7972 (setq idprop (org-entry-get nil "ID"))
7973 (org-end-of-subtree t t)
7974 (or (bolp) (insert "\n"))
7975 (setq end (point))
7976 (setq template (buffer-substring beg end))
7977 (when (and doshift
7978 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[dwmy][^<>\n]*>" template))
7979 (delete-region beg end)
7980 (setq end beg)
7981 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7982 (goto-char end)
7983 (loop for n from nmin to nmax do
7984 ;; prepare clone
7985 (with-temp-buffer
7986 (insert template)
7987 (org-mode)
7988 (goto-char (point-min))
7989 (org-show-subtree)
7990 (and idprop (if org-clone-delete-id
7991 (org-entry-delete nil "ID")
7992 (org-id-get-create t)))
7993 (unless (= n 0)
7994 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7995 (kill-whole-line))
7996 (goto-char (point-min))
7997 (while (re-search-forward drawer-re nil t)
7998 (mapc (lambda (d)
7999 (org-remove-empty-drawer-at d (point))) org-drawers)))
8000 (goto-char (point-min))
8001 (when doshift
8002 (while (re-search-forward org-ts-regexp-both nil t)
8003 (org-timestamp-change (* n shift-n) shift-what))
8004 (unless (= n n-no-remove)
8005 (goto-char (point-min))
8006 (while (re-search-forward org-ts-regexp nil t)
8007 (save-excursion
8008 (goto-char (match-beginning 0))
8009 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[dwmy]\\)")
8010 (delete-region (match-beginning 1) (match-end 1)))))))
8011 (setq task (buffer-string)))
8012 (insert task))
8013 (goto-char beg)))
8015 ;;; Outline Sorting
8017 (defun org-sort (with-case)
8018 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8019 Optional argument WITH-CASE means sort case-sensitively."
8020 (interactive "P")
8021 (cond
8022 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8023 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8025 (org-call-with-arg 'org-sort-entries with-case))))
8027 (defun org-sort-remove-invisible (s)
8028 (remove-text-properties 0 (length s) org-rm-props s)
8029 (while (string-match org-bracket-link-regexp s)
8030 (setq s (replace-match (if (match-end 2)
8031 (match-string 3 s)
8032 (match-string 1 s)) t t s)))
8035 (defvar org-priority-regexp) ; defined later in the file
8037 (defvar org-after-sorting-entries-or-items-hook nil
8038 "Hook that is run after a bunch of entries or items have been sorted.
8039 When children are sorted, the cursor is in the parent line when this
8040 hook gets called. When a region or a plain list is sorted, the cursor
8041 will be in the first entry of the sorted region/list.")
8043 (defun org-sort-entries
8044 (&optional with-case sorting-type getkey-func compare-func property)
8045 "Sort entries on a certain level of an outline tree.
8046 If there is an active region, the entries in the region are sorted.
8047 Else, if the cursor is before the first entry, sort the top-level items.
8048 Else, the children of the entry at point are sorted.
8050 Sorting can be alphabetically, numerically, by date/time as given by
8051 a time stamp, by a property or by priority.
8053 The command prompts for the sorting type unless it has been given to the
8054 function through the SORTING-TYPE argument, which needs to be a character,
8055 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8056 precise meaning of each character:
8058 n Numerically, by converting the beginning of the entry/item to a number.
8059 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8060 t By date/time, either the first active time stamp in the entry, or, if
8061 none exist, by the first inactive one.
8062 s By the scheduled date/time.
8063 d By deadline date/time.
8064 c By creation time, which is assumed to be the first inactive time stamp
8065 at the beginning of a line.
8066 p By priority according to the cookie.
8067 r By the value of a property.
8069 Capital letters will reverse the sort order.
8071 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8072 called with point at the beginning of the record. It must return either
8073 a string or a number that should serve as the sorting key for that record.
8075 Comparing entries ignores case by default. However, with an optional argument
8076 WITH-CASE, the sorting considers case as well."
8077 (interactive "P")
8078 (let ((case-func (if with-case 'identity 'downcase))
8079 start beg end stars re re2
8080 txt what tmp)
8081 ;; Find beginning and end of region to sort
8082 (cond
8083 ((org-region-active-p)
8084 ;; we will sort the region
8085 (setq end (region-end)
8086 what "region")
8087 (goto-char (region-beginning))
8088 (if (not (org-at-heading-p)) (outline-next-heading))
8089 (setq start (point)))
8090 ((or (org-at-heading-p)
8091 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8092 ;; we will sort the children of the current headline
8093 (org-back-to-heading)
8094 (setq start (point)
8095 end (progn (org-end-of-subtree t t)
8096 (or (bolp) (insert "\n"))
8097 (org-back-over-empty-lines)
8098 (point))
8099 what "children")
8100 (goto-char start)
8101 (show-subtree)
8102 (outline-next-heading))
8104 ;; we will sort the top-level entries in this file
8105 (goto-char (point-min))
8106 (or (org-at-heading-p) (outline-next-heading))
8107 (setq start (point))
8108 (goto-char (point-max))
8109 (beginning-of-line 1)
8110 (when (looking-at ".*?\\S-")
8111 ;; File ends in a non-white line
8112 (end-of-line 1)
8113 (insert "\n"))
8114 (setq end (point-max))
8115 (setq what "top-level")
8116 (goto-char start)
8117 (show-all)))
8119 (setq beg (point))
8120 (if (>= beg end) (error "Nothing to sort"))
8122 (looking-at "\\(\\*+\\)")
8123 (setq stars (match-string 1)
8124 re (concat "^" (regexp-quote stars) " +")
8125 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8126 txt (buffer-substring beg end))
8127 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8128 (if (and (not (equal stars "*")) (string-match re2 txt))
8129 (error "Region to sort contains a level above the first entry"))
8131 (unless sorting-type
8132 (message
8133 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8134 [t]ime [s]cheduled [d]eadline [c]reated
8135 A/N/T/S/D/C/P/O/F means reversed:"
8136 what)
8137 (setq sorting-type (read-char-exclusive))
8139 (and (= (downcase sorting-type) ?f)
8140 (setq getkey-func
8141 (org-icompleting-read "Sort using function: "
8142 obarray 'fboundp t nil nil))
8143 (setq getkey-func (intern getkey-func)))
8145 (and (= (downcase sorting-type) ?r)
8146 (setq property
8147 (org-icompleting-read "Property: "
8148 (mapcar 'list (org-buffer-property-keys t))
8149 nil t))))
8151 (message "Sorting entries...")
8153 (save-restriction
8154 (narrow-to-region start end)
8155 (let ((dcst (downcase sorting-type))
8156 (case-fold-search nil)
8157 (now (current-time)))
8158 (sort-subr
8159 (/= dcst sorting-type)
8160 ;; This function moves to the beginning character of the "record" to
8161 ;; be sorted.
8162 (lambda nil
8163 (if (re-search-forward re nil t)
8164 (goto-char (match-beginning 0))
8165 (goto-char (point-max))))
8166 ;; This function moves to the last character of the "record" being
8167 ;; sorted.
8168 (lambda nil
8169 (save-match-data
8170 (condition-case nil
8171 (outline-forward-same-level 1)
8172 (error
8173 (goto-char (point-max))))))
8174 ;; This function returns the value that gets sorted against.
8175 (lambda nil
8176 (cond
8177 ((= dcst ?n)
8178 (if (looking-at org-complex-heading-regexp)
8179 (string-to-number (match-string 4))
8180 nil))
8181 ((= dcst ?a)
8182 (if (looking-at org-complex-heading-regexp)
8183 (funcall case-func (match-string 4))
8184 nil))
8185 ((= dcst ?t)
8186 (let ((end (save-excursion (outline-next-heading) (point))))
8187 (if (or (re-search-forward org-ts-regexp end t)
8188 (re-search-forward org-ts-regexp-both end t))
8189 (org-time-string-to-seconds (match-string 0))
8190 (org-float-time now))))
8191 ((= dcst ?c)
8192 (let ((end (save-excursion (outline-next-heading) (point))))
8193 (if (re-search-forward
8194 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8195 end t)
8196 (org-time-string-to-seconds (match-string 0))
8197 (org-float-time now))))
8198 ((= dcst ?s)
8199 (let ((end (save-excursion (outline-next-heading) (point))))
8200 (if (re-search-forward org-scheduled-time-regexp end t)
8201 (org-time-string-to-seconds (match-string 1))
8202 (org-float-time now))))
8203 ((= dcst ?d)
8204 (let ((end (save-excursion (outline-next-heading) (point))))
8205 (if (re-search-forward org-deadline-time-regexp end t)
8206 (org-time-string-to-seconds (match-string 1))
8207 (org-float-time now))))
8208 ((= dcst ?p)
8209 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8210 (string-to-char (match-string 2))
8211 org-default-priority))
8212 ((= dcst ?r)
8213 (or (org-entry-get nil property) ""))
8214 ((= dcst ?o)
8215 (if (looking-at org-complex-heading-regexp)
8216 (- 9999 (length (member (match-string 2)
8217 org-todo-keywords-1)))))
8218 ((= dcst ?f)
8219 (if getkey-func
8220 (progn
8221 (setq tmp (funcall getkey-func))
8222 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8223 tmp)
8224 (error "Invalid key function `%s'" getkey-func)))
8225 (t (error "Invalid sorting type `%c'" sorting-type))))
8227 (cond
8228 ((= dcst ?a) 'string<)
8229 ((= dcst ?f) compare-func)
8230 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8231 (t nil)))))
8232 (run-hooks 'org-after-sorting-entries-or-items-hook)
8233 (message "Sorting entries...done")))
8235 (defun org-do-sort (table what &optional with-case sorting-type)
8236 "Sort TABLE of WHAT according to SORTING-TYPE.
8237 The user will be prompted for the SORTING-TYPE if the call to this
8238 function does not specify it. WHAT is only for the prompt, to indicate
8239 what is being sorted. The sorting key will be extracted from
8240 the car of the elements of the table.
8241 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8242 (unless sorting-type
8243 (message
8244 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8245 what)
8246 (setq sorting-type (read-char-exclusive)))
8247 (let ((dcst (downcase sorting-type))
8248 extractfun comparefun)
8249 ;; Define the appropriate functions
8250 (cond
8251 ((= dcst ?n)
8252 (setq extractfun 'string-to-number
8253 comparefun (if (= dcst sorting-type) '< '>)))
8254 ((= dcst ?a)
8255 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8256 (lambda(x) (downcase (org-sort-remove-invisible x))))
8257 comparefun (if (= dcst sorting-type)
8258 'string<
8259 (lambda (a b) (and (not (string< a b))
8260 (not (string= a b)))))))
8261 ((= dcst ?t)
8262 (setq extractfun
8263 (lambda (x)
8264 (if (or (string-match org-ts-regexp x)
8265 (string-match org-ts-regexp-both x))
8266 (org-float-time
8267 (org-time-string-to-time (match-string 0 x)))
8269 comparefun (if (= dcst sorting-type) '< '>)))
8270 (t (error "Invalid sorting type `%c'" sorting-type)))
8272 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8273 table)
8274 (lambda (a b) (funcall comparefun (car a) (car b))))))
8277 ;;; The orgstruct minor mode
8279 ;; Define a minor mode which can be used in other modes in order to
8280 ;; integrate the org-mode structure editing commands.
8282 ;; This is really a hack, because the org-mode structure commands use
8283 ;; keys which normally belong to the major mode. Here is how it
8284 ;; works: The minor mode defines all the keys necessary to operate the
8285 ;; structure commands, but wraps the commands into a function which
8286 ;; tests if the cursor is currently at a headline or a plain list
8287 ;; item. If that is the case, the structure command is used,
8288 ;; temporarily setting many Org-mode variables like regular
8289 ;; expressions for filling etc. However, when any of those keys is
8290 ;; used at a different location, function uses `key-binding' to look
8291 ;; up if the key has an associated command in another currently active
8292 ;; keymap (minor modes, major mode, global), and executes that
8293 ;; command. There might be problems if any of the keys is otherwise
8294 ;; used as a prefix key.
8296 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8297 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8298 ;; addresses this by checking explicitly for both bindings.
8300 (defvar orgstruct-mode-map (make-sparse-keymap)
8301 "Keymap for the minor `orgstruct-mode'.")
8303 (defvar org-local-vars nil
8304 "List of local variables, for use by `orgstruct-mode'.")
8306 ;;;###autoload
8307 (define-minor-mode orgstruct-mode
8308 "Toggle the minor mode `orgstruct-mode'.
8309 This mode is for using Org-mode structure commands in other
8310 modes. The following keys behave as if Org-mode were active, if
8311 the cursor is on a headline, or on a plain list item (both as
8312 defined by Org-mode).
8314 M-up Move entry/item up
8315 M-down Move entry/item down
8316 M-left Promote
8317 M-right Demote
8318 M-S-up Move entry/item up
8319 M-S-down Move entry/item down
8320 M-S-left Promote subtree
8321 M-S-right Demote subtree
8322 M-q Fill paragraph and items like in Org-mode
8323 C-c ^ Sort entries
8324 C-c - Cycle list bullet
8325 TAB Cycle item visibility
8326 M-RET Insert new heading/item
8327 S-M-RET Insert new TODO heading / Checkbox item
8328 C-c C-c Set tags / toggle checkbox"
8329 nil " OrgStruct" nil
8330 (org-load-modules-maybe)
8331 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8333 ;;;###autoload
8334 (defun turn-on-orgstruct ()
8335 "Unconditionally turn on `orgstruct-mode'."
8336 (orgstruct-mode 1))
8338 (defun orgstruct++-mode (&optional arg)
8339 "Toggle `orgstruct-mode', the enhanced version of it.
8340 In addition to setting orgstruct-mode, this also exports all indentation
8341 and autofilling variables from org-mode into the buffer. It will also
8342 recognize item context in multiline items.
8343 Note that turning off orgstruct-mode will *not* remove the
8344 indentation/paragraph settings. This can only be done by refreshing the
8345 major mode, for example with \\[normal-mode]."
8346 (interactive "P")
8347 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8348 (if (< arg 1)
8349 (orgstruct-mode -1)
8350 (orgstruct-mode 1)
8351 (let (var val)
8352 (mapc
8353 (lambda (x)
8354 (when (string-match
8355 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8356 (symbol-name (car x)))
8357 (setq var (car x) val (nth 1 x))
8358 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8359 org-local-vars)
8360 (org-set-local 'orgstruct-is-++ t))))
8362 (defvar orgstruct-is-++ nil
8363 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8364 (make-variable-buffer-local 'orgstruct-is-++)
8366 ;;;###autoload
8367 (defun turn-on-orgstruct++ ()
8368 "Unconditionally turn on `orgstruct++-mode'."
8369 (orgstruct++-mode 1))
8371 (defun orgstruct-error ()
8372 "Error when there is no default binding for a structure key."
8373 (interactive)
8374 (error "This key has no function outside structure elements"))
8376 (defun orgstruct-setup ()
8377 "Setup orgstruct keymaps."
8378 (let ((nfunc 0)
8379 (bindings
8380 (list
8381 '([(meta up)] org-metaup)
8382 '([(meta down)] org-metadown)
8383 '([(meta left)] org-metaleft)
8384 '([(meta right)] org-metaright)
8385 '([(meta shift up)] org-shiftmetaup)
8386 '([(meta shift down)] org-shiftmetadown)
8387 '([(meta shift left)] org-shiftmetaleft)
8388 '([(meta shift right)] org-shiftmetaright)
8389 '([?\e (up)] org-metaup)
8390 '([?\e (down)] org-metadown)
8391 '([?\e (left)] org-metaleft)
8392 '([?\e (right)] org-metaright)
8393 '([?\e (shift up)] org-shiftmetaup)
8394 '([?\e (shift down)] org-shiftmetadown)
8395 '([?\e (shift left)] org-shiftmetaleft)
8396 '([?\e (shift right)] org-shiftmetaright)
8397 '([(shift up)] org-shiftup)
8398 '([(shift down)] org-shiftdown)
8399 '([(shift left)] org-shiftleft)
8400 '([(shift right)] org-shiftright)
8401 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8402 '("\M-q" fill-paragraph)
8403 '("\C-c^" org-sort)
8404 '("\C-c-" org-cycle-list-bullet)))
8405 elt key fun cmd)
8406 (while (setq elt (pop bindings))
8407 (setq nfunc (1+ nfunc))
8408 (setq key (org-key (car elt))
8409 fun (nth 1 elt)
8410 cmd (orgstruct-make-binding fun nfunc key))
8411 (org-defkey orgstruct-mode-map key cmd))
8413 ;; Special treatment needed for TAB and RET
8414 (org-defkey orgstruct-mode-map [(tab)]
8415 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8416 (org-defkey orgstruct-mode-map "\C-i"
8417 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8419 (org-defkey orgstruct-mode-map "\M-\C-m"
8420 (orgstruct-make-binding 'org-insert-heading 105
8421 "\M-\C-m" [(meta return)]))
8422 (org-defkey orgstruct-mode-map [(meta return)]
8423 (orgstruct-make-binding 'org-insert-heading 106
8424 [(meta return)] "\M-\C-m"))
8426 (org-defkey orgstruct-mode-map [(shift meta return)]
8427 (orgstruct-make-binding 'org-insert-todo-heading 107
8428 [(meta return)] "\M-\C-m"))
8430 (org-defkey orgstruct-mode-map "\e\C-m"
8431 (orgstruct-make-binding 'org-insert-heading 108
8432 "\e\C-m" [?\e (return)]))
8433 (org-defkey orgstruct-mode-map [?\e (return)]
8434 (orgstruct-make-binding 'org-insert-heading 109
8435 [?\e (return)] "\e\C-m"))
8436 (org-defkey orgstruct-mode-map [?\e (shift return)]
8437 (orgstruct-make-binding 'org-insert-todo-heading 110
8438 [?\e (return)] "\e\C-m"))
8440 (unless org-local-vars
8441 (setq org-local-vars (org-get-local-variables)))
8445 (defun orgstruct-make-binding (fun n &rest keys)
8446 "Create a function for binding in the structure minor mode.
8447 FUN is the command to call inside a table. N is used to create a unique
8448 command name. KEYS are keys that should be checked in for a command
8449 to execute outside of tables."
8450 (eval
8451 (list 'defun
8452 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8453 '(arg)
8454 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8455 "Outside of structure, run the binding of `"
8456 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8457 "'.")
8458 '(interactive "p")
8459 (list 'if
8460 `(org-context-p 'headline 'item
8461 (and orgstruct-is-++
8462 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8463 'item-body))
8464 (list 'org-run-like-in-org-mode (list 'quote fun))
8465 (list 'let '(orgstruct-mode)
8466 (list 'call-interactively
8467 (append '(or)
8468 (mapcar (lambda (k)
8469 (list 'key-binding k))
8470 keys)
8471 '('orgstruct-error))))))))
8473 (defun org-context-p (&rest contexts)
8474 "Check if local context is any of CONTEXTS.
8475 Possible values in the list of contexts are `table', `headline', and `item'."
8476 (let ((pos (point)))
8477 (goto-char (point-at-bol))
8478 (prog1 (or (and (memq 'table contexts)
8479 (looking-at "[ \t]*|"))
8480 (and (memq 'headline contexts)
8481 (looking-at org-outline-regexp))
8482 (and (memq 'item contexts)
8483 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8484 (and (memq 'item-body contexts)
8485 (org-in-item-p)))
8486 (goto-char pos))))
8488 (defun org-get-local-variables ()
8489 "Return a list of all local variables in an org-mode buffer."
8490 (let (varlist)
8491 (with-current-buffer (get-buffer-create "*Org tmp*")
8492 (erase-buffer)
8493 (org-mode)
8494 (setq varlist (buffer-local-variables)))
8495 (kill-buffer "*Org tmp*")
8496 (delq nil
8497 (mapcar
8498 (lambda (x)
8499 (setq x
8500 (if (symbolp x)
8501 (list x)
8502 (list (car x) (list 'quote (cdr x)))))
8503 (if (string-match
8504 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8505 (symbol-name (car x)))
8506 x nil))
8507 varlist))))
8509 (defun org-clone-local-variables (from-buffer &optional regexp)
8510 "Clone local variables from FROM-BUFFER.
8511 Optional argument REGEXP selects variables to clone."
8512 (mapc
8513 (lambda (pair)
8514 (and (symbolp (car pair))
8515 (or (null regexp)
8516 (string-match regexp (symbol-name (car pair))))
8517 (set (make-local-variable (car pair))
8518 (cdr pair))))
8519 (buffer-local-variables from-buffer)))
8521 ;;;###autoload
8522 (defun org-run-like-in-org-mode (cmd)
8523 "Run a command, pretending that the current buffer is in Org-mode.
8524 This will temporarily bind local variables that are typically bound in
8525 Org-mode to the values they have in Org-mode, and then interactively
8526 call CMD."
8527 (org-load-modules-maybe)
8528 (unless org-local-vars
8529 (setq org-local-vars (org-get-local-variables)))
8530 (eval (list 'let org-local-vars
8531 (list 'call-interactively (list 'quote cmd)))))
8533 ;;;; Archiving
8535 (defun org-get-category (&optional pos force-refresh)
8536 "Get the category applying to position POS."
8537 (if force-refresh (org-refresh-category-properties))
8538 (let ((pos (or pos (point))))
8539 (or (get-text-property pos 'org-category)
8540 (progn (org-refresh-category-properties)
8541 (get-text-property pos 'org-category)))))
8543 (defun org-refresh-category-properties ()
8544 "Refresh category text properties in the buffer."
8545 (let ((def-cat (cond
8546 ((null org-category)
8547 (if buffer-file-name
8548 (file-name-sans-extension
8549 (file-name-nondirectory buffer-file-name))
8550 "???"))
8551 ((symbolp org-category) (symbol-name org-category))
8552 (t org-category)))
8553 beg end cat pos optionp)
8554 (org-unmodified
8555 (save-excursion
8556 (save-restriction
8557 (widen)
8558 (goto-char (point-min))
8559 (put-text-property (point) (point-max) 'org-category def-cat)
8560 (while (re-search-forward
8561 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8562 (setq pos (match-end 0)
8563 optionp (equal (char-after (match-beginning 0)) ?#)
8564 cat (org-trim (match-string 2)))
8565 (if optionp
8566 (setq beg (point-at-bol) end (point-max))
8567 (org-back-to-heading t)
8568 (setq beg (point) end (org-end-of-subtree t t)))
8569 (put-text-property beg end 'org-category cat)
8570 (put-text-property beg end 'org-category-position beg)
8571 (goto-char pos)))))))
8574 ;;;; Link Stuff
8576 ;;; Link abbreviations
8578 (defun org-link-expand-abbrev (link)
8579 "Apply replacements as defined in `org-link-abbrev-alist."
8580 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8581 (let* ((key (match-string 1 link))
8582 (as (or (assoc key org-link-abbrev-alist-local)
8583 (assoc key org-link-abbrev-alist)))
8584 (tag (and (match-end 2) (match-string 3 link)))
8585 rpl)
8586 (if (not as)
8587 link
8588 (setq rpl (cdr as))
8589 (cond
8590 ((symbolp rpl) (funcall rpl tag))
8591 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8592 ((string-match "%h" rpl)
8593 (replace-match (url-hexify-string (or tag "")) t t rpl))
8594 (t (concat rpl tag)))))
8595 link))
8597 ;;; Storing and inserting links
8599 (defvar org-insert-link-history nil
8600 "Minibuffer history for links inserted with `org-insert-link'.")
8602 (defvar org-stored-links nil
8603 "Contains the links stored with `org-store-link'.")
8605 (defvar org-store-link-plist nil
8606 "Plist with info about the most recently link created with `org-store-link'.")
8608 (defvar org-link-protocols nil
8609 "Link protocols added to Org-mode using `org-add-link-type'.")
8611 (defvar org-store-link-functions nil
8612 "List of functions that are called to create and store a link.
8613 Each function will be called in turn until one returns a non-nil
8614 value. Each function should check if it is responsible for creating
8615 this link (for example by looking at the major mode).
8616 If not, it must exit and return nil.
8617 If yes, it should return a non-nil value after a calling
8618 `org-store-link-props' with a list of properties and values.
8619 Special properties are:
8621 :type The link prefix, like \"http\". This must be given.
8622 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8623 This is obligatory as well.
8624 :description Optional default description for the second pair
8625 of brackets in an Org-mode link. The user can still change
8626 this when inserting this link into an Org-mode buffer.
8628 In addition to these, any additional properties can be specified
8629 and then used in remember templates.")
8631 (defun org-add-link-type (type &optional follow export)
8632 "Add TYPE to the list of `org-link-types'.
8633 Re-compute all regular expressions depending on `org-link-types'
8635 FOLLOW and EXPORT are two functions.
8637 FOLLOW should take the link path as the single argument and do whatever
8638 is necessary to follow the link, for example find a file or display
8639 a mail message.
8641 EXPORT should format the link path for export to one of the export formats.
8642 It should be a function accepting three arguments:
8644 path the path of the link, the text after the prefix (like \"http:\")
8645 desc the description of the link, if any, or a description added by
8646 org-export-normalize-links if there is none
8647 format the export format, a symbol like `html' or `latex' or `ascii'..
8649 The function may use the FORMAT information to return different values
8650 depending on the format. The return value will be put literally into
8651 the exported file. If the return value is nil, this means Org should
8652 do what it normally does with links which do not have EXPORT defined.
8654 Org-mode has a built-in default for exporting links. If you are happy with
8655 this default, there is no need to define an export function for the link
8656 type. For a simple example of an export function, see `org-bbdb.el'."
8657 (add-to-list 'org-link-types type t)
8658 (org-make-link-regexps)
8659 (if (assoc type org-link-protocols)
8660 (setcdr (assoc type org-link-protocols) (list follow export))
8661 (push (list type follow export) org-link-protocols)))
8663 (defvar org-agenda-buffer-name)
8665 ;;;###autoload
8666 (defun org-store-link (arg)
8667 "\\<org-mode-map>Store an org-link to the current location.
8668 This link is added to `org-stored-links' and can later be inserted
8669 into an org-buffer with \\[org-insert-link].
8671 For some link types, a prefix arg is interpreted:
8672 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8673 For file links, arg negates `org-context-in-file-links'."
8674 (interactive "P")
8675 (org-load-modules-maybe)
8676 (setq org-store-link-plist nil) ; reset
8677 (org-with-limited-levels
8678 (let (link cpltxt desc description search txt custom-id agenda-link)
8679 (cond
8681 ((run-hook-with-args-until-success 'org-store-link-functions)
8682 (setq link (plist-get org-store-link-plist :link)
8683 desc (or (plist-get org-store-link-plist :description) link)))
8685 ((equal (buffer-name) "*Org Edit Src Example*")
8686 (let (label gc)
8687 (while (or (not label)
8688 (save-excursion
8689 (save-restriction
8690 (widen)
8691 (goto-char (point-min))
8692 (re-search-forward
8693 (regexp-quote (format org-coderef-label-format label))
8694 nil t))))
8695 (when label (message "Label exists already") (sit-for 2))
8696 (setq label (read-string "Code line label: " label)))
8697 (end-of-line 1)
8698 (setq link (format org-coderef-label-format label))
8699 (setq gc (- 79 (length link)))
8700 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8701 (insert link)
8702 (setq link (concat "(" label ")") desc nil)))
8704 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8705 ;; We are in the agenda, link to referenced location
8706 (let ((m (or (get-text-property (point) 'org-hd-marker)
8707 (get-text-property (point) 'org-marker))))
8708 (when m
8709 (org-with-point-at m
8710 (setq agenda-link
8711 (if (org-called-interactively-p 'any)
8712 (call-interactively 'org-store-link)
8713 (org-store-link nil)))))))
8715 ((eq major-mode 'calendar-mode)
8716 (let ((cd (calendar-cursor-to-date)))
8717 (setq link
8718 (format-time-string
8719 (car org-time-stamp-formats)
8720 (apply 'encode-time
8721 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8722 nil nil nil))))
8723 (org-store-link-props :type "calendar" :date cd)))
8725 ((eq major-mode 'w3-mode)
8726 (setq cpltxt (if (and (buffer-name)
8727 (not (string-match "Untitled" (buffer-name))))
8728 (buffer-name)
8729 (url-view-url t))
8730 link (org-make-link (url-view-url t)))
8731 (org-store-link-props :type "w3" :url (url-view-url t)))
8733 ((eq major-mode 'w3m-mode)
8734 (setq cpltxt (or w3m-current-title w3m-current-url)
8735 link (org-make-link w3m-current-url))
8736 (org-store-link-props :type "w3m" :url (url-view-url t)))
8738 ((setq search (run-hook-with-args-until-success
8739 'org-create-file-search-functions))
8740 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8741 "::" search))
8742 (setq cpltxt (or description link)))
8744 ((eq major-mode 'image-mode)
8745 (setq cpltxt (concat "file:"
8746 (abbreviate-file-name buffer-file-name))
8747 link (org-make-link cpltxt))
8748 (org-store-link-props :type "image" :file buffer-file-name))
8750 ((eq major-mode 'dired-mode)
8751 ;; link to the file in the current line
8752 (let ((file (dired-get-filename nil t)))
8753 (setq file (if file
8754 (abbreviate-file-name
8755 (expand-file-name (dired-get-filename nil t)))
8756 ;; otherwise, no file so use current directory.
8757 default-directory))
8758 (setq cpltxt (concat "file:" file)
8759 link (org-make-link cpltxt))))
8761 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8762 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8763 (cond
8764 ((org-in-regexp "<<\\(.*?\\)>>")
8765 (setq cpltxt
8766 (concat "file:"
8767 (abbreviate-file-name
8768 (buffer-file-name (buffer-base-buffer)))
8769 "::" (match-string 1))
8770 link (org-make-link cpltxt)))
8771 ((and (featurep 'org-id)
8772 (or (eq org-link-to-org-use-id t)
8773 (and (eq org-link-to-org-use-id 'create-if-interactive)
8774 (org-called-interactively-p 'any))
8775 (and (eq org-link-to-org-use-id
8776 'create-if-interactive-and-no-custom-id)
8777 (org-called-interactively-p 'any)
8778 (not custom-id))
8779 (and org-link-to-org-use-id
8780 (org-entry-get nil "ID"))))
8781 ;; We can make a link using the ID.
8782 (setq link (condition-case nil
8783 (prog1 (org-id-store-link)
8784 (setq desc (plist-get org-store-link-plist
8785 :description)))
8786 (error
8787 ;; probably before first headline, link to file only
8788 (concat "file:"
8789 (abbreviate-file-name
8790 (buffer-file-name (buffer-base-buffer))))))))
8792 ;; Just link to current headline
8793 (setq cpltxt (concat "file:"
8794 (abbreviate-file-name
8795 (buffer-file-name (buffer-base-buffer)))))
8796 ;; Add a context search string
8797 (when (org-xor org-context-in-file-links arg)
8798 (setq txt (cond
8799 ((org-at-heading-p) nil)
8800 ((org-region-active-p)
8801 (buffer-substring (region-beginning) (region-end)))
8802 (t nil)))
8803 (when (or (null txt) (string-match "\\S-" txt))
8804 (setq cpltxt
8805 (concat cpltxt "::"
8806 (condition-case nil
8807 (org-make-org-heading-search-string txt)
8808 (error "")))
8809 desc (or (nth 4 (ignore-errors
8810 (org-heading-components))) "NONE"))))
8811 (if (string-match "::\\'" cpltxt)
8812 (setq cpltxt (substring cpltxt 0 -2)))
8813 (setq link (org-make-link cpltxt)))))
8815 ((buffer-file-name (buffer-base-buffer))
8816 ;; Just link to this file here.
8817 (setq cpltxt (concat "file:"
8818 (abbreviate-file-name
8819 (buffer-file-name (buffer-base-buffer)))))
8820 ;; Add a context string
8821 (when (org-xor org-context-in-file-links arg)
8822 (setq txt (if (org-region-active-p)
8823 (buffer-substring (region-beginning) (region-end))
8824 (buffer-substring (point-at-bol) (point-at-eol))))
8825 ;; Only use search option if there is some text.
8826 (when (string-match "\\S-" txt)
8827 (setq cpltxt
8828 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8829 desc "NONE")))
8830 (setq link (org-make-link cpltxt)))
8832 ((org-called-interactively-p 'interactive)
8833 (error "Cannot link to a buffer which is not visiting a file"))
8835 (t (setq link nil)))
8837 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8838 (setq link (or link cpltxt)
8839 desc (or desc cpltxt))
8840 (if (equal desc "NONE") (setq desc nil))
8842 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8843 (progn
8844 (setq org-stored-links
8845 (cons (list link desc) org-stored-links))
8846 (message "Stored: %s" (or desc link))
8847 (when custom-id
8848 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8849 "::#" custom-id))
8850 (setq org-stored-links
8851 (cons (list link desc) org-stored-links))))
8852 (or agenda-link (and link (org-make-link-string link desc)))))))
8854 (defun org-store-link-props (&rest plist)
8855 "Store link properties, extract names and addresses."
8856 (let (x adr)
8857 (when (setq x (plist-get plist :from))
8858 (setq adr (mail-extract-address-components x))
8859 (setq plist (plist-put plist :fromname (car adr)))
8860 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8861 (when (setq x (plist-get plist :to))
8862 (setq adr (mail-extract-address-components x))
8863 (setq plist (plist-put plist :toname (car adr)))
8864 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8865 (let ((from (plist-get plist :from))
8866 (to (plist-get plist :to)))
8867 (when (and from to org-from-is-user-regexp)
8868 (setq plist
8869 (plist-put plist :fromto
8870 (if (string-match org-from-is-user-regexp from)
8871 (concat "to %t")
8872 (concat "from %f"))))))
8873 (setq org-store-link-plist plist))
8875 (defun org-add-link-props (&rest plist)
8876 "Add these properties to the link property list."
8877 (let (key value)
8878 (while plist
8879 (setq key (pop plist) value (pop plist))
8880 (setq org-store-link-plist
8881 (plist-put org-store-link-plist key value)))))
8883 (defun org-email-link-description (&optional fmt)
8884 "Return the description part of an email link.
8885 This takes information from `org-store-link-plist' and formats it
8886 according to FMT (default from `org-email-link-description-format')."
8887 (setq fmt (or fmt org-email-link-description-format))
8888 (let* ((p org-store-link-plist)
8889 (to (plist-get p :toaddress))
8890 (from (plist-get p :fromaddress))
8891 (table
8892 (list
8893 (cons "%c" (plist-get p :fromto))
8894 (cons "%F" (plist-get p :from))
8895 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8896 (cons "%T" (plist-get p :to))
8897 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8898 (cons "%s" (plist-get p :subject))
8899 (cons "%d" (plist-get p :date))
8900 (cons "%m" (plist-get p :message-id)))))
8901 (when (string-match "%c" fmt)
8902 ;; Check if the user wrote this message
8903 (if (and org-from-is-user-regexp from to
8904 (save-match-data (string-match org-from-is-user-regexp from)))
8905 (setq fmt (replace-match "to %t" t t fmt))
8906 (setq fmt (replace-match "from %f" t t fmt))))
8907 (org-replace-escapes fmt table)))
8909 (defun org-make-org-heading-search-string (&optional string heading)
8910 "Make search string for STRING or current headline."
8911 (interactive)
8912 (let ((s (or string (org-get-heading)))
8913 (lines org-context-in-file-links))
8914 (unless (and string (not heading))
8915 ;; We are using a headline, clean up garbage in there.
8916 (if (string-match org-todo-regexp s)
8917 (setq s (replace-match "" t t s)))
8918 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8919 (setq s (replace-match "" t t s)))
8920 (setq s (org-trim s))
8921 (if (string-match (concat "^\\(" org-quote-string "\\|"
8922 org-comment-string "\\)") s)
8923 (setq s (replace-match "" t t s)))
8924 (while (string-match org-ts-regexp s)
8925 (setq s (replace-match "" t t s))))
8926 (or string (setq s (concat "*" s))) ; Add * for headlines
8927 (when (and string (integerp lines) (> lines 0))
8928 (let ((slines (org-split-string s "\n")))
8929 (when (< lines (length slines))
8930 (setq s (mapconcat
8931 'identity
8932 (reverse (nthcdr (- (length slines) lines)
8933 (reverse slines))) "\n")))))
8934 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8936 (defun org-make-link (&rest strings)
8937 "Concatenate STRINGS."
8938 (apply 'concat strings))
8940 (defun org-make-link-string (link &optional description)
8941 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8942 (unless (string-match "\\S-" link)
8943 (error "Empty link"))
8944 (when (and description
8945 (stringp description)
8946 (not (string-match "\\S-" description)))
8947 (setq description nil))
8948 (when (stringp description)
8949 ;; Remove brackets from the description, they are fatal.
8950 (while (string-match "\\[" description)
8951 (setq description (replace-match "{" t t description)))
8952 (while (string-match "\\]" description)
8953 (setq description (replace-match "}" t t description))))
8954 (when (equal link description)
8955 ;; No description needed, it is identical
8956 (setq description nil))
8957 (when (and (not description)
8958 (not (string-match (org-image-file-name-regexp) link))
8959 (not (equal link (org-link-escape link))))
8960 (setq description (org-extract-attributes link)))
8961 (setq link
8962 (cond ((string-match (org-image-file-name-regexp) link) link)
8963 ((string-match org-link-types-re link)
8964 (concat (match-string 1 link)
8965 (org-link-escape (substring link (match-end 1)))))
8966 (t (org-link-escape link))))
8967 (concat "[[" link "]"
8968 (if description (concat "[" description "]") "")
8969 "]"))
8971 (defconst org-link-escape-chars
8972 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8973 "List of characters that should be escaped in link.
8974 This is the list that is used for internal purposes.")
8976 (defvar org-url-encoding-use-url-hexify nil)
8978 (defconst org-link-escape-chars-browser
8979 '(?\ )
8980 "List of escapes for characters that are problematic in links.
8981 This is the list that is used before handing over to the browser.")
8983 (defun org-link-escape (text &optional table merge)
8984 "Return percent escaped representation of TEXT.
8985 TEXT is a string with the text to escape.
8986 Optional argument TABLE is a list with characters that should be
8987 escaped. When nil, `org-link-escape-chars' is used.
8988 If optional argument MERGE is set, merge TABLE into
8989 `org-link-escape-chars'."
8990 (if (and org-url-encoding-use-url-hexify (not table))
8991 (url-hexify-string text)
8992 (cond
8993 ((and table merge)
8994 (mapc (lambda (defchr)
8995 (unless (member defchr table)
8996 (setq table (cons defchr table)))) org-link-escape-chars))
8997 ((null table)
8998 (setq table org-link-escape-chars)))
8999 (mapconcat
9000 (lambda (char)
9001 (if (or (member char table)
9002 (< char 32) (= char 37) (> char 126))
9003 (mapconcat (lambda (sequence-element)
9004 (format "%%%.2X" sequence-element))
9005 (or (encode-coding-char char 'utf-8)
9006 (error "Unable to percent escape character: %s"
9007 (char-to-string char))) "")
9008 (char-to-string char))) text "")))
9010 (defun org-link-unescape (str)
9011 "Unhex hexified Unicode strings as returned from the JavaScript function
9012 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9013 (unless (and (null str) (string= "" str))
9014 (let ((pos 0) (case-fold-search t) unhexed)
9015 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9016 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9017 (setq str (replace-match unhexed t t str))
9018 (setq pos (+ pos (length unhexed))))))
9019 str)
9021 (defun org-link-unescape-compound (hex)
9022 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9023 Note: this function also decodes single byte encodings like
9024 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9025 (save-match-data
9026 (let* ((bytes (cdr (split-string hex "%")))
9027 (ret "")
9028 (eat 0)
9029 (sum 0))
9030 (while bytes
9031 (let* ((val (string-to-number (pop bytes) 16))
9032 (shift-xor
9033 (if (= 0 eat)
9034 (cond
9035 ((>= val 252) (cons 6 252))
9036 ((>= val 248) (cons 5 248))
9037 ((>= val 240) (cons 4 240))
9038 ((>= val 224) (cons 3 224))
9039 ((>= val 192) (cons 2 192))
9040 (t (cons 0 0)))
9041 (cons 6 128))))
9042 (if (>= val 192) (setq eat (car shift-xor)))
9043 (setq val (logxor val (cdr shift-xor)))
9044 (setq sum (+ (lsh sum (car shift-xor)) val))
9045 (if (> eat 0) (setq eat (- eat 1)))
9046 (cond
9047 ((= 0 eat) ;multi byte
9048 (setq ret (concat ret (org-char-to-string sum)))
9049 (setq sum 0))
9050 ((not bytes) ; single byte(s)
9051 (setq ret (org-link-unescape-single-byte-sequence hex))))
9052 )) ;; end (while bytes
9053 ret )))
9055 (defun org-link-unescape-single-byte-sequence (hex)
9056 "Unhexify hex-encoded single byte character sequences."
9057 (mapconcat (lambda (byte)
9058 (char-to-string (string-to-number byte 16)))
9059 (cdr (split-string hex "%")) ""))
9061 (defun org-xor (a b)
9062 "Exclusive or."
9063 (if a (not b) b))
9065 (defun org-fixup-message-id-for-http (s)
9066 "Replace special characters in a message id, so it can be used in an http query."
9067 (when (string-match "%" s)
9068 (setq s (mapconcat (lambda (c)
9069 (if (eq c ?%)
9070 "%25"
9071 (char-to-string c)))
9072 s "")))
9073 (while (string-match "<" s)
9074 (setq s (replace-match "%3C" t t s)))
9075 (while (string-match ">" s)
9076 (setq s (replace-match "%3E" t t s)))
9077 (while (string-match "@" s)
9078 (setq s (replace-match "%40" t t s)))
9081 ;;;###autoload
9082 (defun org-insert-link-global ()
9083 "Insert a link like Org-mode does.
9084 This command can be called in any mode to insert a link in Org-mode syntax."
9085 (interactive)
9086 (org-load-modules-maybe)
9087 (org-run-like-in-org-mode 'org-insert-link))
9089 (defun org-insert-link (&optional complete-file link-location default-description)
9090 "Insert a link. At the prompt, enter the link.
9092 Completion can be used to insert any of the link protocol prefixes like
9093 http or ftp in use.
9095 The history can be used to select a link previously stored with
9096 `org-store-link'. When the empty string is entered (i.e. if you just
9097 press RET at the prompt), the link defaults to the most recently
9098 stored link. As SPC triggers completion in the minibuffer, you need to
9099 use M-SPC or C-q SPC to force the insertion of a space character.
9101 You will also be prompted for a description, and if one is given, it will
9102 be displayed in the buffer instead of the link.
9104 If there is already a link at point, this command will allow you to edit link
9105 and description parts.
9107 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9108 be selected using completion. The path to the file will be relative to the
9109 current directory if the file is in the current directory or a subdirectory.
9110 Otherwise, the link will be the absolute path as completed in the minibuffer
9111 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9112 option `org-link-file-path-type'.
9114 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9115 the current directory or below.
9117 With three \\[universal-argument] prefixes, negate the meaning of
9118 `org-keep-stored-link-after-insertion'.
9120 If `org-make-link-description-function' is non-nil, this function will be
9121 called with the link target, and the result will be the default
9122 link description.
9124 If the LINK-LOCATION parameter is non-nil, this value will be
9125 used as the link location instead of reading one interactively.
9127 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9128 be used as the default description."
9129 (interactive "P")
9130 (let* ((wcf (current-window-configuration))
9131 (region (if (org-region-active-p)
9132 (buffer-substring (region-beginning) (region-end))))
9133 (remove (and region (list (region-beginning) (region-end))))
9134 (desc region)
9135 tmphist ; byte-compile incorrectly complains about this
9136 (link link-location)
9137 entry file all-prefixes)
9138 (cond
9139 (link-location) ; specified by arg, just use it.
9140 ((org-in-regexp org-bracket-link-regexp 1)
9141 ;; We do have a link at point, and we are going to edit it.
9142 (setq remove (list (match-beginning 0) (match-end 0)))
9143 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9144 (setq link (read-string "Link: "
9145 (org-link-unescape
9146 (org-match-string-no-properties 1)))))
9147 ((or (org-in-regexp org-angle-link-re)
9148 (org-in-regexp org-plain-link-re))
9149 ;; Convert to bracket link
9150 (setq remove (list (match-beginning 0) (match-end 0))
9151 link (read-string "Link: "
9152 (org-remove-angle-brackets (match-string 0)))))
9153 ((member complete-file '((4) (16)))
9154 ;; Completing read for file names.
9155 (setq link (org-file-complete-link complete-file)))
9157 ;; Read link, with completion for stored links.
9158 (with-output-to-temp-buffer "*Org Links*"
9159 (princ "Insert a link.
9160 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9161 (when org-stored-links
9162 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9163 (princ (mapconcat
9164 (lambda (x)
9165 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9166 (reverse org-stored-links) "\n"))))
9167 (let ((cw (selected-window)))
9168 (select-window (get-buffer-window "*Org Links*" 'visible))
9169 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9170 (unless (pos-visible-in-window-p (point-max))
9171 (org-fit-window-to-buffer))
9172 (and (window-live-p cw) (select-window cw)))
9173 ;; Fake a link history, containing the stored links.
9174 (setq tmphist (append (mapcar 'car org-stored-links)
9175 org-insert-link-history))
9176 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9177 (mapcar 'car org-link-abbrev-alist)
9178 org-link-types))
9179 (unwind-protect
9180 (progn
9181 (setq link
9182 (let ((org-completion-use-ido nil)
9183 (org-completion-use-iswitchb nil))
9184 (org-completing-read
9185 "Link: "
9186 (append
9187 (mapcar (lambda (x) (list (concat x ":")))
9188 all-prefixes)
9189 (mapcar 'car org-stored-links))
9190 nil nil nil
9191 'tmphist
9192 (car (car org-stored-links)))))
9193 (if (not (string-match "\\S-" link))
9194 (error "No link selected"))
9195 (if (or (member link all-prefixes)
9196 (and (equal ":" (substring link -1))
9197 (member (substring link 0 -1) all-prefixes)
9198 (setq link (substring link 0 -1))))
9199 (setq link (org-link-try-special-completion link))))
9200 (set-window-configuration wcf)
9201 (kill-buffer "*Org Links*"))
9202 (setq entry (assoc link org-stored-links))
9203 (or entry (push link org-insert-link-history))
9204 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9205 (not org-keep-stored-link-after-insertion))
9206 (setq org-stored-links (delq (assoc link org-stored-links)
9207 org-stored-links)))
9208 (setq desc (or desc (nth 1 entry)))))
9210 (if (string-match org-plain-link-re link)
9211 ;; URL-like link, normalize the use of angular brackets.
9212 (setq link (org-make-link (org-remove-angle-brackets link))))
9214 ;; Check if we are linking to the current file with a search option
9215 ;; If yes, simplify the link by using only the search option.
9216 (when (and buffer-file-name
9217 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9218 (let* ((path (match-string 1 link))
9219 (case-fold-search nil)
9220 (search (match-string 2 link)))
9221 (save-match-data
9222 (if (equal (file-truename buffer-file-name) (file-truename path))
9223 ;; We are linking to this same file, with a search option
9224 (setq link search)))))
9226 ;; Check if we can/should use a relative path. If yes, simplify the link
9227 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9228 (let* ((type (match-string 1 link))
9229 (path (match-string 2 link))
9230 (origpath path)
9231 (case-fold-search nil))
9232 (cond
9233 ((or (eq org-link-file-path-type 'absolute)
9234 (equal complete-file '(16)))
9235 (setq path (abbreviate-file-name (expand-file-name path))))
9236 ((eq org-link-file-path-type 'noabbrev)
9237 (setq path (expand-file-name path)))
9238 ((eq org-link-file-path-type 'relative)
9239 (setq path (file-relative-name path)))
9241 (save-match-data
9242 (if (string-match (concat "^" (regexp-quote
9243 (expand-file-name
9244 (file-name-as-directory
9245 default-directory))))
9246 (expand-file-name path))
9247 ;; We are linking a file with relative path name.
9248 (setq path (substring (expand-file-name path)
9249 (match-end 0)))
9250 (setq path (abbreviate-file-name (expand-file-name path)))))))
9251 (setq link (concat type path))
9252 (if (equal desc origpath)
9253 (setq desc path))))
9255 (if org-make-link-description-function
9256 (setq desc (funcall org-make-link-description-function link desc))
9257 (if default-description (setq desc default-description)))
9259 (setq desc (read-string "Description: " desc))
9260 (unless (string-match "\\S-" desc) (setq desc nil))
9261 (if remove (apply 'delete-region remove))
9262 (insert (org-make-link-string link desc))))
9264 (defun org-link-try-special-completion (type)
9265 "If there is completion support for link type TYPE, offer it."
9266 (let ((fun (intern (concat "org-" type "-complete-link"))))
9267 (if (functionp fun)
9268 (funcall fun)
9269 (read-string "Link (no completion support): " (concat type ":")))))
9271 (defun org-file-complete-link (&optional arg)
9272 "Create a file link using completion."
9273 (let (file link)
9274 (setq file (read-file-name "File: "))
9275 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9276 (pwd1 (file-name-as-directory (abbreviate-file-name
9277 (expand-file-name ".")))))
9278 (cond
9279 ((equal arg '(16))
9280 (setq link (org-make-link
9281 "file:"
9282 (abbreviate-file-name (expand-file-name file)))))
9283 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9284 (setq link (org-make-link "file:" (match-string 1 file))))
9285 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9286 (expand-file-name file))
9287 (setq link (org-make-link
9288 "file:" (match-string 1 (expand-file-name file)))))
9289 (t (setq link (org-make-link "file:" file)))))
9290 link))
9292 (defun org-completing-read (&rest args)
9293 "Completing-read with SPACE being a normal character."
9294 (let ((enable-recursive-minibuffers t)
9295 (minibuffer-local-completion-map
9296 (copy-keymap minibuffer-local-completion-map)))
9297 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9298 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9299 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9300 (apply 'org-icompleting-read args)))
9302 (defun org-completing-read-no-i (&rest args)
9303 (let (org-completion-use-ido org-completion-use-iswitchb)
9304 (apply 'org-completing-read args)))
9306 (defun org-iswitchb-completing-read (prompt choices &rest args)
9307 "Use iswitch as a completing-read replacement to choose from choices.
9308 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9309 from."
9310 (let* ((iswitchb-use-virtual-buffers nil)
9311 (iswitchb-make-buflist-hook
9312 (lambda ()
9313 (setq iswitchb-temp-buflist choices))))
9314 (iswitchb-read-buffer prompt)))
9316 (defun org-icompleting-read (&rest args)
9317 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9318 (org-without-partial-completion
9319 (if (and org-completion-use-ido
9320 (fboundp 'ido-completing-read)
9321 (boundp 'ido-mode) ido-mode
9322 (listp (second args)))
9323 (let ((ido-enter-matching-directory nil))
9324 (apply 'ido-completing-read (concat (car args))
9325 (if (consp (car (nth 1 args)))
9326 (mapcar 'car (nth 1 args))
9327 (nth 1 args))
9328 (cddr args)))
9329 (if (and org-completion-use-iswitchb
9330 (boundp 'iswitchb-mode) iswitchb-mode
9331 (listp (second args)))
9332 (apply 'org-iswitchb-completing-read (concat (car args))
9333 (if (consp (car (nth 1 args)))
9334 (mapcar 'car (nth 1 args))
9335 (nth 1 args))
9336 (cddr args))
9337 (apply 'completing-read args)))))
9339 (defun org-extract-attributes (s)
9340 "Extract the attributes cookie from a string and set as text property."
9341 (let (a attr (start 0) key value)
9342 (save-match-data
9343 (when (string-match "{{\\([^}]+\\)}}$" s)
9344 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9345 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9346 (setq key (match-string 1 a) value (match-string 2 a)
9347 start (match-end 0)
9348 attr (plist-put attr (intern key) value))))
9349 (org-add-props s nil 'org-attr attr))
9352 (defun org-extract-attributes-from-string (tag)
9353 (let (key value attr)
9354 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9355 (setq key (match-string 1 tag) value (match-string 2 tag)
9356 tag (replace-match "" t t tag)
9357 attr (plist-put attr (intern key) value)))
9358 (cons tag attr)))
9360 (defun org-attributes-to-string (plist)
9361 "Format a property list into an HTML attribute list."
9362 (let ((s "") key value)
9363 (while plist
9364 (setq key (pop plist) value (pop plist))
9365 (and value
9366 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9369 ;;; Opening/following a link
9371 (defvar org-link-search-failed nil)
9373 (defvar org-open-link-functions nil
9374 "Hook for functions finding a plain text link.
9375 These functions must take a single argument, the link content.
9376 They will be called for links that look like [[link text][description]]
9377 when LINK TEXT does not have a protocol like \"http:\" and does not look
9378 like a filename (e.g. \"./blue.png\").
9380 These functions will be called *before* Org attempts to resolve the
9381 link by doing text searches in the current buffer - so if you want a
9382 link \"[[target]]\" to still find \"<<target>>\", your function should
9383 handle this as a special case.
9385 When the function does handle the link, it must return a non-nil value.
9386 If it decides that it is not responsible for this link, it must return
9387 nil to indicate that that Org-mode can continue with other options
9388 like exact and fuzzy text search.")
9390 (defun org-next-link ()
9391 "Move forward to the next link.
9392 If the link is in hidden text, expose it."
9393 (interactive)
9394 (when (and org-link-search-failed (eq this-command last-command))
9395 (goto-char (point-min))
9396 (message "Link search wrapped back to beginning of buffer"))
9397 (setq org-link-search-failed nil)
9398 (let* ((pos (point))
9399 (ct (org-context))
9400 (a (assoc :link ct)))
9401 (if a (goto-char (nth 2 a)))
9402 (if (re-search-forward org-any-link-re nil t)
9403 (progn
9404 (goto-char (match-beginning 0))
9405 (if (outline-invisible-p) (org-show-context)))
9406 (goto-char pos)
9407 (setq org-link-search-failed t)
9408 (error "No further link found"))))
9410 (defun org-previous-link ()
9411 "Move backward to the previous link.
9412 If the link is in hidden text, expose it."
9413 (interactive)
9414 (when (and org-link-search-failed (eq this-command last-command))
9415 (goto-char (point-max))
9416 (message "Link search wrapped back to end of buffer"))
9417 (setq org-link-search-failed nil)
9418 (let* ((pos (point))
9419 (ct (org-context))
9420 (a (assoc :link ct)))
9421 (if a (goto-char (nth 1 a)))
9422 (if (re-search-backward org-any-link-re nil t)
9423 (progn
9424 (goto-char (match-beginning 0))
9425 (if (outline-invisible-p) (org-show-context)))
9426 (goto-char pos)
9427 (setq org-link-search-failed t)
9428 (error "No further link found"))))
9430 (defun org-translate-link (s)
9431 "Translate a link string if a translation function has been defined."
9432 (if (and org-link-translation-function
9433 (fboundp org-link-translation-function)
9434 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9435 (progn
9436 (setq s (funcall org-link-translation-function
9437 (match-string 1) (match-string 2)))
9438 (concat (car s) ":" (cdr s)))
9441 (defun org-translate-link-from-planner (type path)
9442 "Translate a link from Emacs Planner syntax so that Org can follow it.
9443 This is still an experimental function, your mileage may vary."
9444 (cond
9445 ((member type '("http" "https" "news" "ftp"))
9446 ;; standard Internet links are the same.
9447 nil)
9448 ((and (equal type "irc") (string-match "^//" path))
9449 ;; Planner has two / at the beginning of an irc link, we have 1.
9450 ;; We should have zero, actually....
9451 (setq path (substring path 1)))
9452 ((and (equal type "lisp") (string-match "^/" path))
9453 ;; Planner has a slash, we do not.
9454 (setq type "elisp" path (substring path 1)))
9455 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9456 ;; A typical message link. Planner has the id after the final slash,
9457 ;; we separate it with a hash mark
9458 (setq path (concat (match-string 1 path) "#"
9459 (org-remove-angle-brackets (match-string 2 path)))))
9461 (cons type path))
9463 (defun org-find-file-at-mouse (ev)
9464 "Open file link or URL at mouse."
9465 (interactive "e")
9466 (mouse-set-point ev)
9467 (org-open-at-point 'in-emacs))
9469 (defun org-open-at-mouse (ev)
9470 "Open file link or URL at mouse.
9471 See the docstring of `org-open-file' for details."
9472 (interactive "e")
9473 (mouse-set-point ev)
9474 (if (eq major-mode 'org-agenda-mode)
9475 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9476 (org-open-at-point))
9478 (defvar org-window-config-before-follow-link nil
9479 "The window configuration before following a link.
9480 This is saved in case the need arises to restore it.")
9482 (defvar org-open-link-marker (make-marker)
9483 "Marker pointing to the location where `org-open-at-point; was called.")
9485 ;;;###autoload
9486 (defun org-open-at-point-global ()
9487 "Follow a link like Org-mode does.
9488 This command can be called in any mode to follow a link that has
9489 Org-mode syntax."
9490 (interactive)
9491 (org-run-like-in-org-mode 'org-open-at-point))
9493 ;;;###autoload
9494 (defun org-open-link-from-string (s &optional arg reference-buffer)
9495 "Open a link in the string S, as if it was in Org-mode."
9496 (interactive "sLink: \nP")
9497 (let ((reference-buffer (or reference-buffer (current-buffer))))
9498 (with-temp-buffer
9499 (let ((org-inhibit-startup (not reference-buffer)))
9500 (org-mode)
9501 (insert s)
9502 (goto-char (point-min))
9503 (when reference-buffer
9504 (setq org-link-abbrev-alist-local
9505 (with-current-buffer reference-buffer
9506 org-link-abbrev-alist-local)))
9507 (org-open-at-point arg reference-buffer)))))
9509 (defvar org-open-at-point-functions nil
9510 "Hook that is run when following a link at point.
9512 Functions in this hook must return t if they identify and follow
9513 a link at point. If they don't find anything interesting at point,
9514 they must return nil.")
9516 (defun org-open-at-point (&optional arg reference-buffer)
9517 "Open link at or after point.
9518 If there is no link at point, this function will search forward up to
9519 the end of the current line.
9520 Normally, files will be opened by an appropriate application. If the
9521 optional prefix argument ARG is non-nil, Emacs will visit the file.
9522 With a double prefix argument, try to open outside of Emacs, in the
9523 application the system uses for this file type."
9524 (interactive "P")
9525 ;; if in a code block, then open the block's results
9526 (unless (call-interactively #'org-babel-open-src-block-result)
9527 (org-load-modules-maybe)
9528 (move-marker org-open-link-marker (point))
9529 (setq org-window-config-before-follow-link (current-window-configuration))
9530 (org-remove-occur-highlights nil nil t)
9531 (cond
9532 ((and (org-at-heading-p)
9533 (not (org-in-regexp
9534 (concat org-plain-link-re "\\|"
9535 org-bracket-link-regexp "\\|"
9536 org-angle-link-re "\\|"
9537 "[ \t]:[^ \t\n]+:[ \t]*$")))
9538 (not (get-text-property (point) 'org-linked-text)))
9539 (or (org-offer-links-in-entry arg)
9540 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9541 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9542 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9543 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9544 (not (org-in-regexp org-bracket-link-regexp)))
9545 (org-footnote-action))
9547 (let (type path link line search (pos (point)))
9548 (catch 'match
9549 (save-excursion
9550 (skip-chars-forward "^]\n\r")
9551 (when (org-in-regexp org-bracket-link-regexp 1)
9552 (setq link (org-extract-attributes
9553 (org-link-unescape (org-match-string-no-properties 1))))
9554 (while (string-match " *\n *" link)
9555 (setq link (replace-match " " t t link)))
9556 (setq link (org-link-expand-abbrev link))
9557 (cond
9558 ((or (file-name-absolute-p link)
9559 (string-match "^\\.\\.?/" link))
9560 (setq type "file" path link))
9561 ((string-match org-link-re-with-space3 link)
9562 (setq type (match-string 1 link) path (match-string 2 link)))
9563 (t (setq type "thisfile" path link)))
9564 (throw 'match t)))
9566 (when (get-text-property (point) 'org-linked-text)
9567 (setq type "thisfile"
9568 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9569 (1+ (point)) (point))
9570 path (buffer-substring
9571 (or (previous-single-property-change pos 'org-linked-text)
9572 (point-min))
9573 (or (next-single-property-change pos 'org-linked-text)
9574 (point-max))))
9575 (throw 'match t))
9577 (save-excursion
9578 (when (or (org-in-regexp org-angle-link-re)
9579 (org-in-regexp org-plain-link-re))
9580 (setq type (match-string 1)
9581 path (org-link-unescape (match-string 2)))
9582 (throw 'match t)))
9583 (save-excursion
9584 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9585 (setq type "tags"
9586 path (match-string 1))
9587 (while (string-match ":" path)
9588 (setq path (replace-match "+" t t path)))
9589 (throw 'match t)))
9590 (when (org-in-regexp "<\\([^><\n]+\\)>")
9591 (setq type "tree-match"
9592 path (match-string 1))
9593 (throw 'match t)))
9594 (unless path
9595 (error "No link found"))
9597 ;; switch back to reference buffer
9598 ;; needed when if called in a temporary buffer through
9599 ;; org-open-link-from-string
9600 (with-current-buffer (or reference-buffer (current-buffer))
9602 ;; Remove any trailing spaces in path
9603 (if (string-match " +\\'" path)
9604 (setq path (replace-match "" t t path)))
9605 (if (and org-link-translation-function
9606 (fboundp org-link-translation-function))
9607 ;; Check if we need to translate the link
9608 (let ((tmp (funcall org-link-translation-function type path)))
9609 (setq type (car tmp) path (cdr tmp))))
9611 (cond
9613 ((assoc type org-link-protocols)
9614 (funcall (nth 1 (assoc type org-link-protocols)) path))
9616 ((equal type "mailto")
9617 (let ((cmd (car org-link-mailto-program))
9618 (args (cdr org-link-mailto-program)) args1
9619 (address path) (subject "") a)
9620 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9621 (setq address (match-string 1 path)
9622 subject (org-link-escape (match-string 2 path))))
9623 (while args
9624 (cond
9625 ((not (stringp (car args))) (push (pop args) args1))
9626 (t (setq a (pop args))
9627 (if (string-match "%a" a)
9628 (setq a (replace-match address t t a)))
9629 (if (string-match "%s" a)
9630 (setq a (replace-match subject t t a)))
9631 (push a args1))))
9632 (apply cmd (nreverse args1))))
9634 ((member type '("http" "https" "ftp" "news"))
9635 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9636 (org-link-escape
9637 path org-link-escape-chars-browser)
9638 path))))
9640 ((string= type "doi")
9641 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9642 (org-link-escape
9643 path org-link-escape-chars-browser)
9644 path))))
9646 ((member type '("message"))
9647 (browse-url (concat type ":" path)))
9649 ((string= type "tags")
9650 (org-tags-view arg path))
9652 ((string= type "tree-match")
9653 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9655 ((string= type "file")
9656 (if (string-match "::\\([0-9]+\\)\\'" path)
9657 (setq line (string-to-number (match-string 1 path))
9658 path (substring path 0 (match-beginning 0)))
9659 (if (string-match "::\\(.+\\)\\'" path)
9660 (setq search (match-string 1 path)
9661 path (substring path 0 (match-beginning 0)))))
9662 (if (string-match "[*?{]" (file-name-nondirectory path))
9663 (dired path)
9664 (org-open-file path arg line search)))
9666 ((string= type "shell")
9667 (let ((cmd path))
9668 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9669 (string-match org-confirm-shell-link-not-regexp cmd))
9670 (not org-confirm-shell-link-function)
9671 (funcall org-confirm-shell-link-function
9672 (format "Execute \"%s\" in shell? "
9673 (org-add-props cmd nil
9674 'face 'org-warning))))
9675 (progn
9676 (message "Executing %s" cmd)
9677 (shell-command cmd))
9678 (error "Abort"))))
9680 ((string= type "elisp")
9681 (let ((cmd path))
9682 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9683 (string-match org-confirm-elisp-link-not-regexp cmd))
9684 (not org-confirm-elisp-link-function)
9685 (funcall org-confirm-elisp-link-function
9686 (format "Execute \"%s\" as elisp? "
9687 (org-add-props cmd nil
9688 'face 'org-warning))))
9689 (message "%s => %s" cmd
9690 (if (equal (string-to-char cmd) ?\()
9691 (eval (read cmd))
9692 (call-interactively (read cmd))))
9693 (error "Abort"))))
9695 ((and (string= type "thisfile")
9696 (run-hook-with-args-until-success
9697 'org-open-link-functions path)))
9699 ((string= type "thisfile")
9700 (if arg
9701 (switch-to-buffer-other-window
9702 (org-get-buffer-for-internal-link (current-buffer)))
9703 (org-mark-ring-push))
9704 (let ((cmd `(org-link-search
9705 ,path
9706 ,(cond ((equal arg '(4)) ''occur)
9707 ((equal arg '(16)) ''org-occur)
9708 (t nil))
9709 ,pos)))
9710 (condition-case nil (let ((org-link-search-inhibit-query t))
9711 (eval cmd))
9712 (error (progn (widen) (eval cmd))))))
9715 (browse-url-at-point)))))))
9716 (move-marker org-open-link-marker nil)
9717 (run-hook-with-args 'org-follow-link-hook)))
9719 (defun org-offer-links-in-entry (&optional nth zero)
9720 "Offer links in the current entry and follow the selected link.
9721 If there is only one link, follow it immediately as well.
9722 If NTH is an integer, immediately pick the NTH link found.
9723 If ZERO is a string, check also this string for a link, and if
9724 there is one, offer it as link number zero."
9725 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9726 "\\(" org-angle-link-re "\\)\\|"
9727 "\\(" org-plain-link-re "\\)"))
9728 (cnt ?0)
9729 (in-emacs (if (integerp nth) nil nth))
9730 have-zero end links link c)
9731 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9732 (push (match-string 0 zero) links)
9733 (setq cnt (1- cnt) have-zero t))
9734 (save-excursion
9735 (org-back-to-heading t)
9736 (setq end (save-excursion (outline-next-heading) (point)))
9737 (while (re-search-forward re end t)
9738 (push (match-string 0) links))
9739 (setq links (org-uniquify (reverse links))))
9741 (cond
9742 ((null links)
9743 (message "No links"))
9744 ((equal (length links) 1)
9745 (setq link (list (car links))))
9746 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9747 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9748 (t ; we have to select a link
9749 (save-excursion
9750 (save-window-excursion
9751 (delete-other-windows)
9752 (with-output-to-temp-buffer "*Select Link*"
9753 (mapc (lambda (l)
9754 (if (not (string-match org-bracket-link-regexp l))
9755 (princ (format "[%c] %s\n" (incf cnt)
9756 (org-remove-angle-brackets l)))
9757 (if (match-end 3)
9758 (princ (format "[%c] %s (%s)\n" (incf cnt)
9759 (match-string 3 l) (match-string 1 l)))
9760 (princ (format "[%c] %s\n" (incf cnt)
9761 (match-string 1 l))))))
9762 links))
9763 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9764 (message "Select link to open, RET to open all:")
9765 (setq c (read-char-exclusive))
9766 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9767 (when (equal c ?q) (error "Abort"))
9768 (if (equal c ?\C-m)
9769 (setq link links)
9770 (setq nth (- c ?0))
9771 (if have-zero (setq nth (1+ nth)))
9772 (unless (and (integerp nth) (>= (length links) nth))
9773 (error "Invalid link selection"))
9774 (setq link (list (nth (1- nth) links))))))
9775 (if link
9776 (let ((buf (current-buffer)))
9777 (dolist (l link)
9778 (org-open-link-from-string l in-emacs buf))
9780 nil)))
9782 ;; Add special file links that specify the way of opening
9784 (org-add-link-type "file+sys" 'org-open-file-with-system)
9785 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9786 (defun org-open-file-with-system (path)
9787 "Open file at PATH using the system way of opening it."
9788 (org-open-file path 'system))
9789 (defun org-open-file-with-emacs (path)
9790 "Open file at PATH in Emacs."
9791 (org-open-file path 'emacs))
9792 (defun org-remove-file-link-modifiers ()
9793 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9794 (goto-char (point-min))
9795 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9796 (org-if-unprotected
9797 (replace-match "file:" t t))))
9798 (eval-after-load "org-exp"
9799 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9800 'org-remove-file-link-modifiers))
9802 ;;;; Time estimates
9804 (defun org-get-effort (&optional pom)
9805 "Get the effort estimate for the current entry."
9806 (org-entry-get pom org-effort-property))
9808 ;;; File search
9810 (defvar org-create-file-search-functions nil
9811 "List of functions to construct the right search string for a file link.
9812 These functions are called in turn with point at the location to
9813 which the link should point.
9815 A function in the hook should first test if it would like to
9816 handle this file type, for example by checking the `major-mode'
9817 or the file extension. If it decides not to handle this file, it
9818 should just return nil to give other functions a chance. If it
9819 does handle the file, it must return the search string to be used
9820 when following the link. The search string will be part of the
9821 file link, given after a double colon, and `org-open-at-point'
9822 will automatically search for it. If special measures must be
9823 taken to make the search successful, another function should be
9824 added to the companion hook `org-execute-file-search-functions',
9825 which see.
9827 A function in this hook may also use `setq' to set the variable
9828 `description' to provide a suggestion for the descriptive text to
9829 be used for this link when it gets inserted into an Org-mode
9830 buffer with \\[org-insert-link].")
9832 (defvar org-execute-file-search-functions nil
9833 "List of functions to execute a file search triggered by a link.
9835 Functions added to this hook must accept a single argument, the
9836 search string that was part of the file link, the part after the
9837 double colon. The function must first check if it would like to
9838 handle this search, for example by checking the `major-mode' or
9839 the file extension. If it decides not to handle this search, it
9840 should just return nil to give other functions a chance. If it
9841 does handle the search, it must return a non-nil value to keep
9842 other functions from trying.
9844 Each function can access the current prefix argument through the
9845 variable `current-prefix-argument'. Note that a single prefix is
9846 used to force opening a link in Emacs, so it may be good to only
9847 use a numeric or double prefix to guide the search function.
9849 In case this is needed, a function in this hook can also restore
9850 the window configuration before `org-open-at-point' was called using:
9852 (set-window-configuration org-window-config-before-follow-link)")
9854 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9855 (defun org-link-search (s &optional type avoid-pos stealth)
9856 "Search for a link search option.
9857 If S is surrounded by forward slashes, it is interpreted as a
9858 regular expression. In org-mode files, this will create an `org-occur'
9859 sparse tree. In ordinary files, `occur' will be used to list matches.
9860 If the current buffer is in `dired-mode', grep will be used to search
9861 in all files. If AVOID-POS is given, ignore matches near that position.
9863 When optional argument STEALTH is non-nil, do not modify
9864 visibility around point, thus ignoring
9865 `org-show-hierarchy-above', `org-show-following-heading' and
9866 `org-show-siblings' variables."
9867 (let ((case-fold-search t)
9868 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9869 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9870 (append '(("") (" ") ("\t") ("\n"))
9871 org-emphasis-alist)
9872 "\\|") "\\)"))
9873 (pos (point))
9874 (pre nil) (post nil)
9875 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9876 (cond
9877 ;; First check if there are any special search functions
9878 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9879 ;; Now try the builtin stuff
9880 ((and (equal (string-to-char s0) ?#)
9881 (> (length s0) 1)
9882 (save-excursion
9883 (goto-char (point-min))
9884 (and
9885 (re-search-forward
9886 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9887 (setq type 'dedicated
9888 pos (match-beginning 0))))
9889 ;; There is an exact target for this
9890 (goto-char pos)
9891 (org-back-to-heading t)))
9892 ((save-excursion
9893 (goto-char (point-min))
9894 (and
9895 (re-search-forward
9896 (concat "<<" (regexp-quote s0) ">>") nil t)
9897 (setq type 'dedicated
9898 pos (match-beginning 0))))
9899 ;; There is an exact target for this
9900 (goto-char pos))
9901 ((save-excursion
9902 (goto-char (point-min))
9903 (and
9904 (re-search-forward
9905 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9906 (setq type 'dedicated pos (match-beginning 0))))
9907 ;; Found an invisible target.
9908 (goto-char pos))
9909 ((save-excursion
9910 (goto-char (point-min))
9911 (and
9912 (re-search-forward
9913 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9914 (setq type 'dedicated pos (match-beginning 0))))
9915 ;; Found an element with a matching #+name affiliated keyword.
9916 (goto-char pos))
9917 ((and (string-match "^(\\(.*\\))$" s0)
9918 (save-excursion
9919 (goto-char (point-min))
9920 (and
9921 (re-search-forward
9922 (concat "[^[]" (regexp-quote
9923 (format org-coderef-label-format
9924 (match-string 1 s0))))
9925 nil t)
9926 (setq type 'dedicated
9927 pos (1+ (match-beginning 0))))))
9928 ;; There is a coderef target for this
9929 (goto-char pos))
9930 ((string-match "^/\\(.*\\)/$" s)
9931 ;; A regular expression
9932 (cond
9933 ((eq major-mode 'org-mode)
9934 (org-occur (match-string 1 s)))
9935 ;;((eq major-mode 'dired-mode)
9936 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9937 (t (org-do-occur (match-string 1 s)))))
9938 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9939 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9940 (goto-char (point-min))
9941 (cond
9942 ((let (case-fold-search)
9943 (re-search-forward (format org-complex-heading-regexp-format
9944 (regexp-quote s))
9945 nil t))
9946 ;; OK, found a match
9947 (setq type 'dedicated)
9948 (goto-char (match-beginning 0)))
9949 ((and (not org-link-search-inhibit-query)
9950 (eq org-link-search-must-match-exact-headline 'query-to-create)
9951 (y-or-n-p "No match - create this as a new heading? "))
9952 (goto-char (point-max))
9953 (or (bolp) (newline))
9954 (insert "* " s "\n")
9955 (beginning-of-line 0))
9957 (goto-char pos)
9958 (error "No match"))))
9960 ;; A normal search string
9961 (when (equal (string-to-char s) ?*)
9962 ;; Anchor on headlines, post may include tags.
9963 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9964 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9965 s (substring s 1)))
9966 (remove-text-properties
9967 0 (length s)
9968 '(face nil mouse-face nil keymap nil fontified nil) s)
9969 ;; Make a series of regular expressions to find a match
9970 (setq words (org-split-string s "[ \n\r\t]+")
9972 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9973 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9974 "\\)" markers)
9975 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9976 re2a (concat "[ \t\r\n]" re2a_)
9977 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9978 re4 (concat "[^a-zA-Z_]" re4_)
9980 re1 (concat pre re2 post)
9981 re3 (concat pre (if pre re4_ re4) post)
9982 re5 (concat pre ".*" re4)
9983 re2 (concat pre re2)
9984 re2a (concat pre (if pre re2a_ re2a))
9985 re4 (concat pre (if pre re4_ re4))
9986 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9987 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9988 re5 "\\)"
9990 (cond
9991 ((eq type 'org-occur) (org-occur reall))
9992 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9993 (t (goto-char (point-min))
9994 (setq type 'fuzzy)
9995 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9996 (org-search-not-self 1 re1 nil t)
9997 (org-search-not-self 1 re2 nil t)
9998 (org-search-not-self 1 re2a nil t)
9999 (org-search-not-self 1 re3 nil t)
10000 (org-search-not-self 1 re4 nil t)
10001 (org-search-not-self 1 re5 nil t)
10003 (goto-char (match-beginning 1))
10004 (goto-char pos)
10005 (error "No match"))))))
10006 (and (eq major-mode 'org-mode)
10007 (not stealth)
10008 (org-show-context 'link-search))
10009 type))
10011 (defun org-search-not-self (group &rest args)
10012 "Execute `re-search-forward', but only accept matches that do not
10013 enclose the position of `org-open-link-marker'."
10014 (let ((m org-open-link-marker))
10015 (catch 'exit
10016 (while (apply 're-search-forward args)
10017 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10018 (goto-char (match-end group))
10019 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10020 (> (match-beginning 0) (marker-position m))
10021 (< (match-end 0) (marker-position m)))
10022 (save-match-data
10023 (or (not (org-in-regexp
10024 org-bracket-link-analytic-regexp 1))
10025 (not (match-end 4)) ; no description
10026 (and (<= (match-beginning 4) (point))
10027 (>= (match-end 4) (point))))))
10028 (throw 'exit (point))))))))
10030 (defun org-get-buffer-for-internal-link (buffer)
10031 "Return a buffer to be used for displaying the link target of internal links."
10032 (cond
10033 ((not org-display-internal-link-with-indirect-buffer)
10034 buffer)
10035 ((string-match "(Clone)$" (buffer-name buffer))
10036 (message "Buffer is already a clone, not making another one")
10037 ;; we also do not modify visibility in this case
10038 buffer)
10039 (t ; make a new indirect buffer for displaying the link
10040 (let* ((bn (buffer-name buffer))
10041 (ibn (concat bn "(Clone)"))
10042 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10043 (with-current-buffer ib (org-overview))
10044 ib))))
10046 (defun org-do-occur (regexp &optional cleanup)
10047 "Call the Emacs command `occur'.
10048 If CLEANUP is non-nil, remove the printout of the regular expression
10049 in the *Occur* buffer. This is useful if the regex is long and not useful
10050 to read."
10051 (occur regexp)
10052 (when cleanup
10053 (let ((cwin (selected-window)) win beg end)
10054 (when (setq win (get-buffer-window "*Occur*"))
10055 (select-window win))
10056 (goto-char (point-min))
10057 (when (re-search-forward "match[a-z]+" nil t)
10058 (setq beg (match-end 0))
10059 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10060 (setq end (1- (match-beginning 0)))))
10061 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10062 (goto-char (point-min))
10063 (select-window cwin))))
10065 ;;; The mark ring for links jumps
10067 (defvar org-mark-ring nil
10068 "Mark ring for positions before jumps in Org-mode.")
10069 (defvar org-mark-ring-last-goto nil
10070 "Last position in the mark ring used to go back.")
10071 ;; Fill and close the ring
10072 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10073 (loop for i from 1 to org-mark-ring-length do
10074 (push (make-marker) org-mark-ring))
10075 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10076 org-mark-ring)
10078 (defun org-mark-ring-push (&optional pos buffer)
10079 "Put the current position or POS into the mark ring and rotate it."
10080 (interactive)
10081 (setq pos (or pos (point)))
10082 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10083 (move-marker (car org-mark-ring)
10084 (or pos (point))
10085 (or buffer (current-buffer)))
10086 (message "%s"
10087 (substitute-command-keys
10088 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10090 (defun org-mark-ring-goto (&optional n)
10091 "Jump to the previous position in the mark ring.
10092 With prefix arg N, jump back that many stored positions. When
10093 called several times in succession, walk through the entire ring.
10094 Org-mode commands jumping to a different position in the current file,
10095 or to another Org-mode file, automatically push the old position
10096 onto the ring."
10097 (interactive "p")
10098 (let (p m)
10099 (if (eq last-command this-command)
10100 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10101 (setq p org-mark-ring))
10102 (setq org-mark-ring-last-goto p)
10103 (setq m (car p))
10104 (org-pop-to-buffer-same-window (marker-buffer m))
10105 (goto-char m)
10106 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10108 (defun org-remove-angle-brackets (s)
10109 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10110 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10112 (defun org-add-angle-brackets (s)
10113 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10114 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10116 (defun org-remove-double-quotes (s)
10117 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10118 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10121 ;;; Following specific links
10123 (defun org-follow-timestamp-link ()
10124 (cond
10125 ((org-at-date-range-p t)
10126 (let ((org-agenda-start-on-weekday)
10127 (t1 (match-string 1))
10128 (t2 (match-string 2)))
10129 (setq t1 (time-to-days (org-time-string-to-time t1))
10130 t2 (time-to-days (org-time-string-to-time t2)))
10131 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10132 ((org-at-timestamp-p t)
10133 (org-agenda-list nil (time-to-days (org-time-string-to-time
10134 (substring (match-string 1) 0 10)))
10136 (t (error "This should not happen"))))
10139 ;;; Following file links
10140 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10141 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10142 (declare-function mailcap-mime-info
10143 "mailcap" (string &optional request no-decode))
10144 (defvar org-wait nil)
10145 (defun org-open-file (path &optional in-emacs line search)
10146 "Open the file at PATH.
10147 First, this expands any special file name abbreviations. Then the
10148 configuration variable `org-file-apps' is checked if it contains an
10149 entry for this file type, and if yes, the corresponding command is launched.
10151 If no application is found, Emacs simply visits the file.
10153 With optional prefix argument IN-EMACS, Emacs will visit the file.
10154 With a double \\[universal-argument] \\[universal-argument] \
10155 prefix arg, Org tries to avoid opening in Emacs
10156 and to use an external application to visit the file.
10158 Optional LINE specifies a line to go to, optional SEARCH a string
10159 to search for. If LINE or SEARCH is given, the file will be
10160 opened in Emacs, unless an entry from org-file-apps that makes
10161 use of groups in a regexp matches.
10163 If you want to change the way frames are used when following a
10164 link, please customize `org-link-frame-setup'.
10166 If the file does not exist, an error is thrown."
10167 (let* ((file (if (equal path "")
10168 buffer-file-name
10169 (substitute-in-file-name (expand-file-name path))))
10170 (file-apps (append org-file-apps (org-default-apps)))
10171 (apps (org-remove-if
10172 'org-file-apps-entry-match-against-dlink-p file-apps))
10173 (apps-dlink (org-remove-if-not
10174 'org-file-apps-entry-match-against-dlink-p file-apps))
10175 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10176 (dirp (if remp nil (file-directory-p file)))
10177 (file (if (and dirp org-open-directory-means-index-dot-org)
10178 (concat (file-name-as-directory file) "index.org")
10179 file))
10180 (a-m-a-p (assq 'auto-mode apps))
10181 (dfile (downcase file))
10182 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10183 (link (cond ((and (eq line nil)
10184 (eq search nil))
10185 file)
10186 (line
10187 (concat file "::" (number-to-string line)))
10188 (search
10189 (concat file "::" search))))
10190 (dlink (downcase link))
10191 (old-buffer (current-buffer))
10192 (old-pos (point))
10193 (old-mode major-mode)
10194 ext cmd link-match-data)
10195 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10196 (setq ext (match-string 1 dfile))
10197 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10198 (setq ext (match-string 1 dfile))))
10199 (cond
10200 ((member in-emacs '((16) system))
10201 (setq cmd (cdr (assoc 'system apps))))
10202 (in-emacs (setq cmd 'emacs))
10204 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10205 (and dirp (cdr (assoc 'directory apps)))
10206 ; first, try matching against apps-dlink
10207 ; if we get a match here, store the match data for later
10208 (let ((match (assoc-default dlink apps-dlink
10209 'string-match)))
10210 (if match
10211 (progn (setq link-match-data (match-data))
10212 match)
10213 (progn (setq in-emacs (or in-emacs line search))
10214 nil))) ; if we have no match in apps-dlink,
10215 ; always open the file in emacs if line or search
10216 ; is given (for backwards compatibility)
10217 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10218 'string-match)
10219 (cdr (assoc ext apps))
10220 (cdr (assoc t apps))))))
10221 (when (eq cmd 'system)
10222 (setq cmd (cdr (assoc 'system apps))))
10223 (when (eq cmd 'default)
10224 (setq cmd (cdr (assoc t apps))))
10225 (when (eq cmd 'mailcap)
10226 (require 'mailcap)
10227 (mailcap-parse-mailcaps)
10228 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10229 (command (mailcap-mime-info mime-type)))
10230 (if (stringp command)
10231 (setq cmd command)
10232 (setq cmd 'emacs))))
10233 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10234 (not (file-exists-p file))
10235 (not org-open-non-existing-files))
10236 (error "No such file: %s" file))
10237 (cond
10238 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10239 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10240 (while (string-match "['\"]%s['\"]" cmd)
10241 (setq cmd (replace-match "%s" t t cmd)))
10242 (while (string-match "%s" cmd)
10243 (setq cmd (replace-match
10244 (save-match-data
10245 (shell-quote-argument
10246 (convert-standard-filename file)))
10247 t t cmd)))
10249 ;; Replace "%1", "%2" etc. in command with group matches from regex
10250 (save-match-data
10251 (let ((match-index 1)
10252 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10253 (set-match-data link-match-data)
10254 (while (<= match-index number-of-groups)
10255 (let ((regex (concat "%" (number-to-string match-index)))
10256 (replace-with (match-string match-index dlink)))
10257 (while (string-match regex cmd)
10258 (setq cmd (replace-match replace-with t t cmd))))
10259 (setq match-index (+ match-index 1)))))
10261 (save-window-excursion
10262 (start-process-shell-command cmd nil cmd)
10263 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10265 ((or (stringp cmd)
10266 (eq cmd 'emacs))
10267 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10268 (widen)
10269 (if line (org-goto-line line)
10270 (if search (org-link-search search))))
10271 ((consp cmd)
10272 (let ((file (convert-standard-filename file)))
10273 (save-match-data
10274 (set-match-data link-match-data)
10275 (eval cmd))))
10276 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10277 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10278 (or (not (equal old-buffer (current-buffer)))
10279 (not (equal old-pos (point))))
10280 (org-mark-ring-push old-pos old-buffer))))
10282 (defun org-file-apps-entry-match-against-dlink-p (entry)
10283 "This function returns non-nil if `entry' uses a regular
10284 expression which should be matched against the whole link by
10285 org-open-file.
10287 It assumes that is the case when the entry uses a regular
10288 expression which has at least one grouping construct and the
10289 action is either a lisp form or a command string containing
10290 '%1', i.e. using at least one subexpression match as a
10291 parameter."
10292 (let ((selector (car entry))
10293 (action (cdr entry)))
10294 (if (stringp selector)
10295 (and (> (regexp-opt-depth selector) 0)
10296 (or (and (stringp action)
10297 (string-match "%[0-9]" action))
10298 (consp action)))
10299 nil)))
10301 (defun org-default-apps ()
10302 "Return the default applications for this operating system."
10303 (cond
10304 ((eq system-type 'darwin)
10305 org-file-apps-defaults-macosx)
10306 ((eq system-type 'windows-nt)
10307 org-file-apps-defaults-windowsnt)
10308 (t org-file-apps-defaults-gnu)))
10310 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10311 "Convert extensions to regular expressions in the cars of LIST.
10312 Also, weed out any non-string entries, because the return value is used
10313 only for regexp matching.
10314 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10315 point to the symbol `emacs', indicating that the file should
10316 be opened in Emacs."
10317 (append
10318 (delq nil
10319 (mapcar (lambda (x)
10320 (if (not (stringp (car x)))
10322 (if (string-match "\\W" (car x))
10324 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10325 list))
10326 (if add-auto-mode
10327 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10329 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10330 (defun org-file-remote-p (file)
10331 "Test whether FILE specifies a location on a remote system.
10332 Return non-nil if the location is indeed remote.
10334 For example, the filename \"/user@host:/foo\" specifies a location
10335 on the system \"/user@host:\"."
10336 (cond ((fboundp 'file-remote-p)
10337 (file-remote-p file))
10338 ((fboundp 'tramp-handle-file-remote-p)
10339 (tramp-handle-file-remote-p file))
10340 ((and (boundp 'ange-ftp-name-format)
10341 (string-match (car ange-ftp-name-format) file))
10343 (t nil)))
10346 ;;;; Refiling
10348 (defun org-get-org-file ()
10349 "Read a filename, with default directory `org-directory'."
10350 (let ((default (or org-default-notes-file remember-data-file)))
10351 (read-file-name (format "File name [%s]: " default)
10352 (file-name-as-directory org-directory)
10353 default)))
10355 (defun org-notes-order-reversed-p ()
10356 "Check if the current file should receive notes in reversed order."
10357 (cond
10358 ((not org-reverse-note-order) nil)
10359 ((eq t org-reverse-note-order) t)
10360 ((not (listp org-reverse-note-order)) nil)
10361 (t (catch 'exit
10362 (let ((all org-reverse-note-order)
10363 entry)
10364 (while (setq entry (pop all))
10365 (if (string-match (car entry) buffer-file-name)
10366 (throw 'exit (cdr entry))))
10367 nil)))))
10369 (defvar org-refile-target-table nil
10370 "The list of refile targets, created by `org-refile'.")
10372 (defvar org-agenda-new-buffers nil
10373 "Buffers created to visit agenda files.")
10375 (defvar org-refile-cache nil
10376 "Cache for refile targets.")
10378 (defvar org-refile-markers nil
10379 "All the markers used for caching refile locations.")
10381 (defun org-refile-marker (pos)
10382 "Get a new refile marker, but only if caching is in use."
10383 (if (not org-refile-use-cache)
10385 (let ((m (make-marker)))
10386 (move-marker m pos)
10387 (push m org-refile-markers)
10388 m)))
10390 (defun org-refile-cache-clear ()
10391 "Clear the refile cache and disable all the markers."
10392 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10393 (setq org-refile-markers nil)
10394 (setq org-refile-cache nil)
10395 (message "Refile cache has been cleared"))
10397 (defun org-refile-cache-check-set (set)
10398 "Check if all the markers in the cache still have live buffers."
10399 (let (marker)
10400 (catch 'exit
10401 (while (and set (setq marker (nth 3 (pop set))))
10402 ;; if org-refile-use-outline-path is 'file, marker may be nil
10403 (when (and marker (null (marker-buffer marker)))
10404 (message "not found") (sit-for 3)
10405 (throw 'exit nil)))
10406 t)))
10408 (defun org-refile-cache-put (set &rest identifiers)
10409 "Push the refile targets SET into the cache, under IDENTIFIERS."
10410 (let* ((key (sha1 (prin1-to-string identifiers)))
10411 (entry (assoc key org-refile-cache)))
10412 (if entry
10413 (setcdr entry set)
10414 (push (cons key set) org-refile-cache))))
10416 (defun org-refile-cache-get (&rest identifiers)
10417 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10418 (cond
10419 ((not org-refile-cache) nil)
10420 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10422 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10423 org-refile-cache))))
10424 (and set (org-refile-cache-check-set set) set)))))
10426 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10427 "Produce a table with refile targets."
10428 (let ((case-fold-search nil)
10429 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10430 (entries (or org-refile-targets '((nil . (:level . 1)))))
10431 targets tgs txt re files f desc descre fast-path-p level pos0)
10432 (message "Getting targets...")
10433 (with-current-buffer (or default-buffer (current-buffer))
10434 (while (setq entry (pop entries))
10435 (setq files (car entry) desc (cdr entry))
10436 (setq fast-path-p nil)
10437 (cond
10438 ((null files) (setq files (list (current-buffer))))
10439 ((eq files 'org-agenda-files)
10440 (setq files (org-agenda-files 'unrestricted)))
10441 ((and (symbolp files) (fboundp files))
10442 (setq files (funcall files)))
10443 ((and (symbolp files) (boundp files))
10444 (setq files (symbol-value files))))
10445 (if (stringp files) (setq files (list files)))
10446 (cond
10447 ((eq (car desc) :tag)
10448 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10449 ((eq (car desc) :todo)
10450 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10451 ((eq (car desc) :regexp)
10452 (setq descre (cdr desc)))
10453 ((eq (car desc) :level)
10454 (setq descre (concat "^\\*\\{" (number-to-string
10455 (if org-odd-levels-only
10456 (1- (* 2 (cdr desc)))
10457 (cdr desc)))
10458 "\\}[ \t]")))
10459 ((eq (car desc) :maxlevel)
10460 (setq fast-path-p t)
10461 (setq descre (concat "^\\*\\{1," (number-to-string
10462 (if org-odd-levels-only
10463 (1- (* 2 (cdr desc)))
10464 (cdr desc)))
10465 "\\}[ \t]")))
10466 (t (error "Bad refiling target description %s" desc)))
10467 (while (setq f (pop files))
10468 (with-current-buffer
10469 (if (bufferp f) f (org-get-agenda-file-buffer f))
10471 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10472 (progn
10473 (if (bufferp f) (setq f (buffer-file-name
10474 (buffer-base-buffer f))))
10475 (setq f (and f (expand-file-name f)))
10476 (if (eq org-refile-use-outline-path 'file)
10477 (push (list (file-name-nondirectory f) f nil nil) tgs))
10478 (save-excursion
10479 (save-restriction
10480 (widen)
10481 (goto-char (point-min))
10482 (while (re-search-forward descre nil t)
10483 (goto-char (setq pos0 (point-at-bol)))
10484 (catch 'next
10485 (when org-refile-target-verify-function
10486 (save-match-data
10487 (or (funcall org-refile-target-verify-function)
10488 (throw 'next t))))
10489 (when (and (looking-at org-complex-heading-regexp)
10490 (not (member (match-string 4) excluded-entries))
10491 (match-string 4))
10492 (setq level (org-reduced-level
10493 (- (match-end 1) (match-beginning 1)))
10494 txt (org-link-display-format (match-string 4))
10495 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10496 re (format org-complex-heading-regexp-format
10497 (regexp-quote (match-string 4))))
10498 (when org-refile-use-outline-path
10499 (setq txt (mapconcat
10500 'org-protect-slash
10501 (append
10502 (if (eq org-refile-use-outline-path
10503 'file)
10504 (list (file-name-nondirectory
10505 (buffer-file-name
10506 (buffer-base-buffer))))
10507 (if (eq org-refile-use-outline-path
10508 'full-file-path)
10509 (list (buffer-file-name
10510 (buffer-base-buffer)))))
10511 (org-get-outline-path fast-path-p
10512 level txt)
10513 (list txt))
10514 "/")))
10515 (push (list txt f re (org-refile-marker (point)))
10516 tgs)))
10517 (when (= (point) pos0)
10518 ;; verification function has not moved point
10519 (goto-char (point-at-eol))))))))
10520 (when org-refile-use-cache
10521 (org-refile-cache-put tgs (buffer-file-name) descre))
10522 (setq targets (append tgs targets))
10523 ))))
10524 (message "Getting targets...done")
10525 (nreverse targets)))
10527 (defun org-protect-slash (s)
10528 (while (string-match "/" s)
10529 (setq s (replace-match "\\" t t s)))
10532 (defvar org-olpa (make-vector 20 nil))
10534 (defun org-get-outline-path (&optional fastp level heading)
10535 "Return the outline path to the current entry, as a list.
10537 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10538 routine which makes outline path derivations for an entire file,
10539 avoiding backtracing. Refile target collection makes use of that."
10540 (if fastp
10541 (progn
10542 (if (> level 19)
10543 (error "Outline path failure, more than 19 levels"))
10544 (loop for i from level upto 19 do
10545 (aset org-olpa i nil))
10546 (prog1
10547 (delq nil (append org-olpa nil))
10548 (aset org-olpa level heading)))
10549 (let (rtn case-fold-search)
10550 (save-excursion
10551 (save-restriction
10552 (widen)
10553 (while (org-up-heading-safe)
10554 (when (looking-at org-complex-heading-regexp)
10555 (push (org-match-string-no-properties 4) rtn)))
10556 rtn)))))
10558 (defun org-format-outline-path (path &optional width prefix)
10559 "Format the outline path PATH for display.
10560 Width is the maximum number of characters that is available.
10561 Prefix is a prefix to be included in the returned string,
10562 such as the file name."
10563 (setq width (or width 79))
10564 (if prefix (setq width (- width (length prefix))))
10565 (if (not path)
10566 (or prefix "")
10567 (let* ((nsteps (length path))
10568 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10569 (maxwidth (if (<= total-width width)
10570 10000 ;; everything fits
10571 ;; we need to shorten the level headings
10572 (/ (- width nsteps) nsteps)))
10573 (org-odd-levels-only nil)
10574 (n 0)
10575 (total (1+ (length prefix))))
10576 (setq maxwidth (max maxwidth 10))
10577 (concat prefix
10578 (mapconcat
10579 (lambda (h)
10580 (setq n (1+ n))
10581 (if (and (= n nsteps) (< maxwidth 10000))
10582 (setq maxwidth (- total-width total)))
10583 (if (< (length h) maxwidth)
10584 (progn (setq total (+ total (length h) 1)) h)
10585 (setq h (substring h 0 (- maxwidth 2))
10586 total (+ total maxwidth 1))
10587 (if (string-match "[ \t]+\\'" h)
10588 (setq h (substring h 0 (match-beginning 0))))
10589 (setq h (concat h "..")))
10590 (org-add-props h nil 'face
10591 (nth (% (1- n) org-n-level-faces)
10592 org-level-faces))
10594 path "/")))))
10596 (defun org-display-outline-path (&optional file current)
10597 "Display the current outline path in the echo area."
10598 (interactive "P")
10599 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10600 (case-fold-search nil)
10601 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10602 (if current (setq path (append path
10603 (save-excursion
10604 (org-back-to-heading t)
10605 (if (looking-at org-complex-heading-regexp)
10606 (list (match-string 4)))))))
10607 (message "%s"
10608 (org-format-outline-path
10609 path
10610 (1- (frame-width))
10611 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10613 (defvar org-refile-history nil
10614 "History for refiling operations.")
10616 (defvar org-after-refile-insert-hook nil
10617 "Hook run after `org-refile' has inserted its stuff at the new location.
10618 Note that this is still *before* the stuff will be removed from
10619 the *old* location.")
10621 (defvar org-capture-last-stored-marker)
10622 (defun org-refile (&optional goto default-buffer rfloc)
10623 "Move the entry or entries at point to another heading.
10624 The list of target headings is compiled using the information in
10625 `org-refile-targets', which see.
10627 At the target location, the entry is filed as a subitem of the target
10628 heading. Depending on `org-reverse-note-order', the new subitem will
10629 either be the first or the last subitem.
10631 If there is an active region, all entries in that region will be moved.
10632 However, the region must fulfill the requirement that the first heading
10633 is the first one sets the top-level of the moved text - at most siblings
10634 below it are allowed.
10636 With prefix arg GOTO, the command will only visit the target location
10637 and not actually move anything.
10639 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10640 go to the location where the last refiling operation has put the subtree.
10641 With a prefix argument of `2', refile to the running clock.
10643 RFLOC can be a refile location obtained in a different way.
10645 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10647 If you are using target caching (see `org-refile-use-cache'),
10648 You have to clear the target cache in order to find new targets.
10649 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10650 prefix argument (`C-u C-u C-u C-c C-w')."
10652 (interactive "P")
10653 (if (member goto '(0 (64)))
10654 (org-refile-cache-clear)
10655 (let* ((cbuf (current-buffer))
10656 (regionp (org-region-active-p))
10657 (region-start (and regionp (region-beginning)))
10658 (region-end (and regionp (region-end)))
10659 (region-length (and regionp (- region-end region-start)))
10660 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10661 pos it nbuf file re level reversed)
10662 (setq last-command nil)
10663 (when regionp
10664 (goto-char region-start)
10665 (or (bolp) (goto-char (point-at-bol)))
10666 (setq region-start (point))
10667 (unless (or (org-kill-is-subtree-p
10668 (buffer-substring region-start region-end))
10669 (prog1 org-refile-active-region-within-subtree
10670 (org-toggle-heading)))
10671 (error "The region is not a (sequence of) subtree(s)")))
10672 (if (equal goto '(16))
10673 (org-refile-goto-last-stored)
10674 (when (or
10675 (and (equal goto 2)
10676 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10677 (prog1
10678 (setq it (list (or org-clock-heading "running clock")
10679 (buffer-file-name
10680 (marker-buffer org-clock-hd-marker))
10682 (marker-position org-clock-hd-marker)))
10683 (setq goto nil)))
10684 (setq it (or rfloc
10685 (let (heading-text)
10686 (save-excursion
10687 (unless goto
10688 (org-back-to-heading t)
10689 (setq heading-text
10690 (nth 4 (org-heading-components))))
10691 (org-refile-get-location
10692 (cond (goto "Goto")
10693 (regionp "Refile region to")
10694 (t (concat "Refile subtree \""
10695 heading-text "\" to")))
10696 default-buffer
10697 org-refile-allow-creating-parent-nodes
10698 goto))))))
10699 (setq file (nth 1 it)
10700 re (nth 2 it)
10701 pos (nth 3 it))
10702 (if (and (not goto)
10704 (equal (buffer-file-name) file)
10705 (if regionp
10706 (and (>= pos region-start)
10707 (<= pos region-end))
10708 (and (>= pos (point))
10709 (< pos (save-excursion
10710 (org-end-of-subtree t t))))))
10711 (error "Cannot refile to position inside the tree or region"))
10713 (setq nbuf (or (find-buffer-visiting file)
10714 (find-file-noselect file)))
10715 (if goto
10716 (progn
10717 (org-pop-to-buffer-same-window nbuf)
10718 (goto-char pos)
10719 (org-show-context 'org-goto))
10720 (if regionp
10721 (progn
10722 (org-kill-new (buffer-substring region-start region-end))
10723 (org-save-markers-in-region region-start region-end))
10724 (org-copy-subtree 1 nil t))
10725 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10726 (find-file-noselect file)))
10727 (setq reversed (org-notes-order-reversed-p))
10728 (save-excursion
10729 (save-restriction
10730 (widen)
10731 (if pos
10732 (progn
10733 (goto-char pos)
10734 (looking-at org-outline-regexp)
10735 (setq level (org-get-valid-level (funcall outline-level) 1))
10736 (goto-char
10737 (if reversed
10738 (or (outline-next-heading) (point-max))
10739 (or (save-excursion (org-get-next-sibling))
10740 (org-end-of-subtree t t)
10741 (point-max)))))
10742 (setq level 1)
10743 (if (not reversed)
10744 (goto-char (point-max))
10745 (goto-char (point-min))
10746 (or (outline-next-heading) (goto-char (point-max)))))
10747 (if (not (bolp)) (newline))
10748 (org-paste-subtree level)
10749 (when org-log-refile
10750 (org-add-log-setup 'refile nil nil 'findpos
10751 org-log-refile)
10752 (unless (eq org-log-refile 'note)
10753 (save-excursion (org-add-log-note))))
10754 (and org-auto-align-tags (org-set-tags nil t))
10755 (bookmark-set "org-refile-last-stored")
10756 ;; If we are refiling for capture, make sure that the
10757 ;; last-capture pointers point here
10758 (when (org-bound-and-true-p org-refile-for-capture)
10759 (bookmark-set "org-capture-last-stored-marker")
10760 (move-marker org-capture-last-stored-marker (point)))
10761 (if (fboundp 'deactivate-mark) (deactivate-mark))
10762 (run-hooks 'org-after-refile-insert-hook))))
10763 (if regionp
10764 (delete-region (point) (+ (point) region-length))
10765 (org-cut-subtree))
10766 (when (featurep 'org-inlinetask)
10767 (org-inlinetask-remove-END-maybe))
10768 (setq org-markers-to-move nil)
10769 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10771 (defun org-refile-goto-last-stored ()
10772 "Go to the location where the last refile was stored."
10773 (interactive)
10774 (bookmark-jump "org-refile-last-stored")
10775 (message "This is the location of the last refile"))
10777 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10778 no-exclude)
10779 "Prompt the user for a refile location, using PROMPT.
10780 PROMPT should not be suffixed with a colon and a space, because
10781 this function appends the default value from
10782 `org-refile-history' automatically, if that is not empty.
10783 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10784 this is used for the GOTO interface."
10785 (let ((org-refile-targets org-refile-targets)
10786 (org-refile-use-outline-path org-refile-use-outline-path)
10787 excluded-entries)
10788 (when (and (eq major-mode 'org-mode)
10789 (not org-refile-use-cache)
10790 (not no-exclude))
10791 (org-map-tree
10792 (lambda()
10793 (setq excluded-entries
10794 (append excluded-entries (list (org-get-heading t t)))))))
10795 (setq org-refile-target-table
10796 (org-refile-get-targets default-buffer excluded-entries)))
10797 (unless org-refile-target-table
10798 (error "No refile targets"))
10799 (let* ((prompt (concat prompt
10800 (and (car org-refile-history)
10801 (concat " (default " (car org-refile-history) ")"))
10802 ": "))
10803 (cbuf (current-buffer))
10804 (partial-completion-mode nil)
10805 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10806 (cfunc (if (and org-refile-use-outline-path
10807 org-outline-path-complete-in-steps)
10808 'org-olpath-completing-read
10809 'org-icompleting-read))
10810 (extra (if org-refile-use-outline-path "/" ""))
10811 (filename (and cfn (expand-file-name cfn)))
10812 (tbl (mapcar
10813 (lambda (x)
10814 (if (and (not (member org-refile-use-outline-path
10815 '(file full-file-path)))
10816 (not (equal filename (nth 1 x))))
10817 (cons (concat (car x) extra " ("
10818 (file-name-nondirectory (nth 1 x)) ")")
10819 (cdr x))
10820 (cons (concat (car x) extra) (cdr x))))
10821 org-refile-target-table))
10822 (completion-ignore-case t)
10823 pa answ parent-target child parent old-hist)
10824 (setq old-hist org-refile-history)
10825 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10826 nil 'org-refile-history (car org-refile-history)))
10827 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10828 (org-refile-check-position pa)
10829 (if pa
10830 (progn
10831 (when (or (not org-refile-history)
10832 (not (eq old-hist org-refile-history))
10833 (not (equal (car pa) (car org-refile-history))))
10834 (setq org-refile-history
10835 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10836 org-refile-history
10837 (cdr org-refile-history))))
10838 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10839 (pop org-refile-history)))
10841 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10842 (progn
10843 (setq parent (match-string 1 answ)
10844 child (match-string 2 answ))
10845 (setq parent-target (or (assoc parent tbl)
10846 (assoc (concat parent "/") tbl)))
10847 (when (and parent-target
10848 (or (eq new-nodes t)
10849 (and (eq new-nodes 'confirm)
10850 (y-or-n-p (format "Create new node \"%s\"? "
10851 child)))))
10852 (org-refile-new-child parent-target child)))
10853 (error "Invalid target location")))))
10855 (defun org-refile-check-position (refile-pointer)
10856 "Check if the refile pointer matches the readline to which it points."
10857 (let* ((file (nth 1 refile-pointer))
10858 (re (nth 2 refile-pointer))
10859 (pos (nth 3 refile-pointer))
10860 buffer)
10861 (when (org-string-nw-p re)
10862 (setq buffer (if (markerp pos)
10863 (marker-buffer pos)
10864 (or (find-buffer-visiting file)
10865 (find-file-noselect file))))
10866 (with-current-buffer buffer
10867 (save-excursion
10868 (save-restriction
10869 (widen)
10870 (goto-char pos)
10871 (beginning-of-line 1)
10872 (unless (org-looking-at-p re)
10873 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10875 (defun org-refile-new-child (parent-target child)
10876 "Use refile target PARENT-TARGET to add new CHILD below it."
10877 (unless parent-target
10878 (error "Cannot find parent for new node"))
10879 (let ((file (nth 1 parent-target))
10880 (pos (nth 3 parent-target))
10881 level)
10882 (with-current-buffer (or (find-buffer-visiting file)
10883 (find-file-noselect file))
10884 (save-excursion
10885 (save-restriction
10886 (widen)
10887 (if pos
10888 (goto-char pos)
10889 (goto-char (point-max))
10890 (if (not (bolp)) (newline)))
10891 (when (looking-at org-outline-regexp)
10892 (setq level (funcall outline-level))
10893 (org-end-of-subtree t t))
10894 (org-back-over-empty-lines)
10895 (insert "\n" (make-string
10896 (if pos (org-get-valid-level level 1) 1) ?*)
10897 " " child "\n")
10898 (beginning-of-line 0)
10899 (list (concat (car parent-target) "/" child) file "" (point)))))))
10901 (defun org-olpath-completing-read (prompt collection &rest args)
10902 "Read an outline path like a file name."
10903 (let ((thetable collection)
10904 (org-completion-use-ido nil) ; does not work with ido.
10905 (org-completion-use-iswitchb nil)) ; or iswitchb
10906 (apply
10907 'org-icompleting-read prompt
10908 (lambda (string predicate &optional flag)
10909 (let (rtn r f (l (length string)))
10910 (cond
10911 ((eq flag nil)
10912 ;; try completion
10913 (try-completion string thetable))
10914 ((eq flag t)
10915 ;; all-completions
10916 (setq rtn (all-completions string thetable predicate))
10917 (mapcar
10918 (lambda (x)
10919 (setq r (substring x l))
10920 (if (string-match " ([^)]*)$" x)
10921 (setq f (match-string 0 x))
10922 (setq f ""))
10923 (if (string-match "/" r)
10924 (concat string (substring r 0 (match-end 0)) f)
10926 rtn))
10927 ((eq flag 'lambda)
10928 ;; exact match?
10929 (assoc string thetable)))
10931 args)))
10933 ;;;; Dynamic blocks
10935 (defun org-find-dblock (name)
10936 "Find the first dynamic block with name NAME in the buffer.
10937 If not found, stay at current position and return nil."
10938 (let (pos)
10939 (save-excursion
10940 (goto-char (point-min))
10941 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10942 nil t)
10943 (match-beginning 0))))
10944 (if pos (goto-char pos))
10945 pos))
10947 (defconst org-dblock-start-re
10948 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10949 "Matches the start line of a dynamic block, with parameters.")
10951 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10952 "Matches the end of a dynamic block.")
10954 (defun org-create-dblock (plist)
10955 "Create a dynamic block section, with parameters taken from PLIST.
10956 PLIST must contain a :name entry which is used as name of the block."
10957 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10958 (end-of-line 1)
10959 (newline))
10960 (let ((col (current-column))
10961 (name (plist-get plist :name)))
10962 (insert "#+BEGIN: " name)
10963 (while plist
10964 (if (eq (car plist) :name)
10965 (setq plist (cddr plist))
10966 (insert " " (prin1-to-string (pop plist)))))
10967 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10968 (beginning-of-line -2)))
10970 (defun org-prepare-dblock ()
10971 "Prepare dynamic block for refresh.
10972 This empties the block, puts the cursor at the insert position and returns
10973 the property list including an extra property :name with the block name."
10974 (unless (looking-at org-dblock-start-re)
10975 (error "Not at a dynamic block"))
10976 (let* ((begdel (1+ (match-end 0)))
10977 (name (org-no-properties (match-string 1)))
10978 (params (append (list :name name)
10979 (read (concat "(" (match-string 3) ")")))))
10980 (save-excursion
10981 (beginning-of-line 1)
10982 (skip-chars-forward " \t")
10983 (setq params (plist-put params :indentation-column (current-column))))
10984 (unless (re-search-forward org-dblock-end-re nil t)
10985 (error "Dynamic block not terminated"))
10986 (setq params
10987 (append params
10988 (list :content (buffer-substring
10989 begdel (match-beginning 0)))))
10990 (delete-region begdel (match-beginning 0))
10991 (goto-char begdel)
10992 (open-line 1)
10993 params))
10995 (defun org-map-dblocks (&optional command)
10996 "Apply COMMAND to all dynamic blocks in the current buffer.
10997 If COMMAND is not given, use `org-update-dblock'."
10998 (let ((cmd (or command 'org-update-dblock)))
10999 (save-excursion
11000 (goto-char (point-min))
11001 (while (re-search-forward org-dblock-start-re nil t)
11002 (goto-char (match-beginning 0))
11003 (save-excursion
11004 (condition-case nil
11005 (funcall cmd)
11006 (error (message "Error during update of dynamic block"))))
11007 (unless (re-search-forward org-dblock-end-re nil t)
11008 (error "Dynamic block not terminated"))))))
11010 (defun org-dblock-update (&optional arg)
11011 "User command for updating dynamic blocks.
11012 Update the dynamic block at point. With prefix ARG, update all dynamic
11013 blocks in the buffer."
11014 (interactive "P")
11015 (if arg
11016 (org-update-all-dblocks)
11017 (or (looking-at org-dblock-start-re)
11018 (org-beginning-of-dblock))
11019 (org-update-dblock)))
11021 (defun org-update-dblock ()
11022 "Update the dynamic block at point.
11023 This means to empty the block, parse for parameters and then call
11024 the correct writing function."
11025 (interactive)
11026 (save-window-excursion
11027 (let* ((pos (point))
11028 (line (org-current-line))
11029 (params (org-prepare-dblock))
11030 (name (plist-get params :name))
11031 (indent (plist-get params :indentation-column))
11032 (cmd (intern (concat "org-dblock-write:" name))))
11033 (message "Updating dynamic block `%s' at line %d..." name line)
11034 (funcall cmd params)
11035 (message "Updating dynamic block `%s' at line %d...done" name line)
11036 (goto-char pos)
11037 (when (and indent (> indent 0))
11038 (setq indent (make-string indent ?\ ))
11039 (save-excursion
11040 (org-beginning-of-dblock)
11041 (forward-line 1)
11042 (while (not (looking-at org-dblock-end-re))
11043 (insert indent)
11044 (beginning-of-line 2))
11045 (when (looking-at org-dblock-end-re)
11046 (and (looking-at "[ \t]+")
11047 (replace-match ""))
11048 (insert indent)))))))
11050 (defun org-beginning-of-dblock ()
11051 "Find the beginning of the dynamic block at point.
11052 Error if there is no such block at point."
11053 (let ((pos (point))
11054 beg)
11055 (end-of-line 1)
11056 (if (and (re-search-backward org-dblock-start-re nil t)
11057 (setq beg (match-beginning 0))
11058 (re-search-forward org-dblock-end-re nil t)
11059 (> (match-end 0) pos))
11060 (goto-char beg)
11061 (goto-char pos)
11062 (error "Not in a dynamic block"))))
11064 (defun org-update-all-dblocks ()
11065 "Update all dynamic blocks in the buffer.
11066 This function can be used in a hook."
11067 (interactive)
11068 (when (eq major-mode 'org-mode)
11069 (org-map-dblocks 'org-update-dblock)))
11072 ;;;; Completion
11074 (defconst org-additional-option-like-keywords
11075 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11076 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11077 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11078 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11079 "BEGIN:" "END:"
11080 "ORGTBL" "TBLFM:" "TBLNAME:"
11081 "BEGIN_EXAMPLE" "END_EXAMPLE"
11082 "BEGIN_QUOTE" "END_QUOTE"
11083 "BEGIN_VERSE" "END_VERSE"
11084 "BEGIN_CENTER" "END_CENTER"
11085 "BEGIN_SRC" "END_SRC"
11086 "BEGIN_RESULT" "END_RESULT"
11087 "NAME:" "RESULTS:"
11088 "HEADER:" "HEADERS:"
11089 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11090 "CAPTION:" "LABEL:"
11091 "SETUPFILE:"
11092 "INCLUDE:"
11093 "BIND:"
11094 "MACRO:"))
11096 (defcustom org-structure-template-alist
11098 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11099 "<src lang=\"?\">\n\n</src>")
11100 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11101 "<example>\n?\n</example>")
11102 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11103 "<quote>\n?\n</quote>")
11104 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11105 "<verse>\n?\n</verse>")
11106 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11107 "<center>\n?\n</center>")
11108 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11109 "<literal style=\"latex\">\n?\n</literal>")
11110 ("L" "#+LaTeX: "
11111 "<literal style=\"latex\">?</literal>")
11112 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11113 "<literal style=\"html\">\n?\n</literal>")
11114 ("H" "#+HTML: "
11115 "<literal style=\"html\">?</literal>")
11116 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11117 ("A" "#+ASCII: ")
11118 ("i" "#+INDEX: ?"
11119 "#+INDEX: ?")
11120 ("I" "#+INCLUDE %file ?"
11121 "<include file=%file markup=\"?\">")
11123 "Structure completion elements.
11124 This is a list of abbreviation keys and values. The value gets inserted
11125 if you type `<' followed by the key and then press the completion key,
11126 usually `M-TAB'. %file will be replaced by a file name after prompting
11127 for the file using completion. The cursor will be placed at the position
11128 of the `?` in the template.
11129 There are two templates for each key, the first uses the original Org syntax,
11130 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11131 the default when the /org-mtags.el/ module has been loaded. See also the
11132 variable `org-mtags-prefer-muse-templates'."
11133 :group 'org-completion
11134 :type '(repeat
11135 (string :tag "Key")
11136 (string :tag "Template")
11137 (string :tag "Muse Template")))
11139 (defun org-try-structure-completion ()
11140 "Try to complete a structure template before point.
11141 This looks for strings like \"<e\" on an otherwise empty line and
11142 expands them."
11143 (let ((l (buffer-substring (point-at-bol) (point)))
11145 (when (and (looking-at "[ \t]*$")
11146 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11147 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11148 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11149 (match-beginning 1)) a)
11150 t)))
11152 (defun org-complete-expand-structure-template (start cell)
11153 "Expand a structure template."
11154 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11155 (rpl (nth (if musep 2 1) cell))
11156 (ind ""))
11157 (delete-region start (point))
11158 (when (string-match "\\`#\\+" rpl)
11159 (cond
11160 ((bolp))
11161 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11162 (setq ind (buffer-substring (point-at-bol) (point))))
11163 (t (newline))))
11164 (setq start (point))
11165 (if (string-match "%file" rpl)
11166 (setq rpl (replace-match
11167 (concat
11168 "\""
11169 (save-match-data
11170 (abbreviate-file-name (read-file-name "Include file: ")))
11171 "\"")
11172 t t rpl)))
11173 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11174 (concat "\n" ind)))
11175 (insert rpl)
11176 (if (re-search-backward "\\?" start t) (delete-char 1))))
11178 ;;;; TODO, DEADLINE, Comments
11180 (defun org-toggle-comment ()
11181 "Change the COMMENT state of an entry."
11182 (interactive)
11183 (save-excursion
11184 (org-back-to-heading)
11185 (let (case-fold-search)
11186 (cond
11187 ((looking-at (format org-heading-keyword-regexp-format
11188 org-comment-string))
11189 (goto-char (match-end 1))
11190 (looking-at (concat " +" org-comment-string))
11191 (replace-match "" t t)
11192 (when (eolp) (insert " ")))
11193 ((looking-at org-outline-regexp)
11194 (goto-char (match-end 0))
11195 (insert org-comment-string " "))))))
11197 (defvar org-last-todo-state-is-todo nil
11198 "This is non-nil when the last TODO state change led to a TODO state.
11199 If the last change removed the TODO tag or switched to DONE, then
11200 this is nil.")
11202 (defvar org-setting-tags nil) ; dynamically skipped
11204 (defvar org-todo-setup-filter-hook nil
11205 "Hook for functions that pre-filter todo specs.
11206 Each function takes a todo spec and returns either nil or the spec
11207 transformed into canonical form." )
11209 (defvar org-todo-get-default-hook nil
11210 "Hook for functions that get a default item for todo.
11211 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11212 nil or a string to be used for the todo mark." )
11214 (defvar org-agenda-headline-snapshot-before-repeat)
11216 (defun org-current-effective-time ()
11217 "Return current time adjusted for `org-extend-today-until' variable"
11218 (let* ((ct (org-current-time))
11219 (dct (decode-time ct))
11220 (ct1
11221 (if (and org-use-effective-time
11222 (< (nth 2 dct) org-extend-today-until))
11223 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11224 ct)))
11225 ct1))
11227 (defun org-todo-yesterday (&optional arg)
11228 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11229 (interactive "P")
11230 (if (eq major-mode 'org-agenda-mode)
11231 (apply 'org-agenda-todo-yesterday arg)
11232 (let* ((hour (third (decode-time
11233 (org-current-time))))
11234 (org-extend-today-until (1+ hour)))
11235 (org-todo arg))))
11237 (defun org-todo (&optional arg)
11238 "Change the TODO state of an item.
11239 The state of an item is given by a keyword at the start of the heading,
11240 like
11241 *** TODO Write paper
11242 *** DONE Call mom
11244 The different keywords are specified in the variable `org-todo-keywords'.
11245 By default the available states are \"TODO\" and \"DONE\".
11246 So for this example: when the item starts with TODO, it is changed to DONE.
11247 When it starts with DONE, the DONE is removed. And when neither TODO nor
11248 DONE are present, add TODO at the beginning of the heading.
11250 With \\[universal-argument] prefix arg, use completion to determine the new \
11251 state.
11252 With numeric prefix arg, switch to that state.
11253 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11254 keywords (nextset).
11255 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11256 With a numeric prefix arg of 0, inhibit note taking for the change.
11258 For calling through lisp, arg is also interpreted in the following way:
11259 'none -> empty state
11260 \"\"(empty string) -> switch to empty state
11261 'done -> switch to DONE
11262 'nextset -> switch to the next set of keywords
11263 'previousset -> switch to the previous set of keywords
11264 \"WAITING\" -> switch to the specified keyword, but only if it
11265 really is a member of `org-todo-keywords'."
11266 (interactive "P")
11267 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11268 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11269 'region-start-level 'region))
11270 org-loop-over-headlines-in-active-region)
11271 (org-map-entries
11272 `(org-todo ,arg)
11273 org-loop-over-headlines-in-active-region
11274 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11275 (if (equal arg '(16)) (setq arg 'nextset))
11276 (let ((org-blocker-hook org-blocker-hook)
11277 (case-fold-search nil))
11278 (when (equal arg '(64))
11279 (setq arg nil org-blocker-hook nil))
11280 (when (and org-blocker-hook
11281 (or org-inhibit-blocking
11282 (org-entry-get nil "NOBLOCKING")))
11283 (setq org-blocker-hook nil))
11284 (save-excursion
11285 (catch 'exit
11286 (org-back-to-heading t)
11287 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11288 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11289 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11290 (let* ((match-data (match-data))
11291 (startpos (point-at-bol))
11292 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11293 (org-log-done org-log-done)
11294 (org-log-repeat org-log-repeat)
11295 (org-todo-log-states org-todo-log-states)
11296 (org-inhibit-logging
11297 (if (equal arg 0)
11298 (progn (setq arg nil) 'note) org-inhibit-logging))
11299 (this (match-string 1))
11300 (hl-pos (match-beginning 0))
11301 (head (org-get-todo-sequence-head this))
11302 (ass (assoc head org-todo-kwd-alist))
11303 (interpret (nth 1 ass))
11304 (done-word (nth 3 ass))
11305 (final-done-word (nth 4 ass))
11306 (last-state (or this ""))
11307 (completion-ignore-case t)
11308 (member (member this org-todo-keywords-1))
11309 (tail (cdr member))
11310 (state (cond
11311 ((and org-todo-key-trigger
11312 (or (and (equal arg '(4))
11313 (eq org-use-fast-todo-selection 'prefix))
11314 (and (not arg) org-use-fast-todo-selection
11315 (not (eq org-use-fast-todo-selection
11316 'prefix)))))
11317 ;; Use fast selection
11318 (org-fast-todo-selection))
11319 ((and (equal arg '(4))
11320 (or (not org-use-fast-todo-selection)
11321 (not org-todo-key-trigger)))
11322 ;; Read a state with completion
11323 (org-icompleting-read
11324 "State: " (mapcar (lambda(x) (list x))
11325 org-todo-keywords-1)
11326 nil t))
11327 ((eq arg 'right)
11328 (if this
11329 (if tail (car tail) nil)
11330 (car org-todo-keywords-1)))
11331 ((eq arg 'left)
11332 (if (equal member org-todo-keywords-1)
11334 (if this
11335 (nth (- (length org-todo-keywords-1)
11336 (length tail) 2)
11337 org-todo-keywords-1)
11338 (org-last org-todo-keywords-1))))
11339 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11340 (setq arg nil))) ; hack to fall back to cycling
11341 (arg
11342 ;; user or caller requests a specific state
11343 (cond
11344 ((equal arg "") nil)
11345 ((eq arg 'none) nil)
11346 ((eq arg 'done) (or done-word (car org-done-keywords)))
11347 ((eq arg 'nextset)
11348 (or (car (cdr (member head org-todo-heads)))
11349 (car org-todo-heads)))
11350 ((eq arg 'previousset)
11351 (let ((org-todo-heads (reverse org-todo-heads)))
11352 (or (car (cdr (member head org-todo-heads)))
11353 (car org-todo-heads))))
11354 ((car (member arg org-todo-keywords-1)))
11355 ((stringp arg)
11356 (error "State `%s' not valid in this file" arg))
11357 ((nth (1- (prefix-numeric-value arg))
11358 org-todo-keywords-1))))
11359 ((null member) (or head (car org-todo-keywords-1)))
11360 ((equal this final-done-word) nil) ;; -> make empty
11361 ((null tail) nil) ;; -> first entry
11362 ((memq interpret '(type priority))
11363 (if (eq this-command last-command)
11364 (car tail)
11365 (if (> (length tail) 0)
11366 (or done-word (car org-done-keywords))
11367 nil)))
11369 (car tail))))
11370 (state (or
11371 (run-hook-with-args-until-success
11372 'org-todo-get-default-hook state last-state)
11373 state))
11374 (next (if state (concat " " state " ") " "))
11375 (change-plist (list :type 'todo-state-change :from this :to state
11376 :position startpos))
11377 dolog now-done-p)
11378 (when org-blocker-hook
11379 (setq org-last-todo-state-is-todo
11380 (not (member this org-done-keywords)))
11381 (unless (save-excursion
11382 (save-match-data
11383 (org-with-wide-buffer
11384 (run-hook-with-args-until-failure
11385 'org-blocker-hook change-plist))))
11386 (if (org-called-interactively-p 'interactive)
11387 (error "TODO state change from %s to %s blocked" this state)
11388 ;; fail silently
11389 (message "TODO state change from %s to %s blocked" this state)
11390 (throw 'exit nil))))
11391 (store-match-data match-data)
11392 (replace-match next t t)
11393 (unless (pos-visible-in-window-p hl-pos)
11394 (message "TODO state changed to %s" (org-trim next)))
11395 (unless head
11396 (setq head (org-get-todo-sequence-head state)
11397 ass (assoc head org-todo-kwd-alist)
11398 interpret (nth 1 ass)
11399 done-word (nth 3 ass)
11400 final-done-word (nth 4 ass)))
11401 (when (memq arg '(nextset previousset))
11402 (message "Keyword-Set %d/%d: %s"
11403 (- (length org-todo-sets) -1
11404 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11405 (length org-todo-sets)
11406 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11407 (setq org-last-todo-state-is-todo
11408 (not (member state org-done-keywords)))
11409 (setq now-done-p (and (member state org-done-keywords)
11410 (not (member this org-done-keywords))))
11411 (and logging (org-local-logging logging))
11412 (when (and (or org-todo-log-states org-log-done)
11413 (not (eq org-inhibit-logging t))
11414 (not (memq arg '(nextset previousset))))
11415 ;; we need to look at recording a time and note
11416 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11417 (nth 2 (assoc this org-todo-log-states))))
11418 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11419 (setq dolog 'time))
11420 (when (and state
11421 (member state org-not-done-keywords)
11422 (not (member this org-not-done-keywords)))
11423 ;; This is now a todo state and was not one before
11424 ;; If there was a CLOSED time stamp, get rid of it.
11425 (org-add-planning-info nil nil 'closed))
11426 (when (and now-done-p org-log-done)
11427 ;; It is now done, and it was not done before
11428 (org-add-planning-info 'closed (org-current-effective-time))
11429 (if (and (not dolog) (eq 'note org-log-done))
11430 (org-add-log-setup 'done state this 'findpos 'note)))
11431 (when (and state dolog)
11432 ;; This is a non-nil state, and we need to log it
11433 (org-add-log-setup 'state state this 'findpos dolog)))
11434 ;; Fixup tag positioning
11435 (org-todo-trigger-tag-changes state)
11436 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11437 (when org-provide-todo-statistics
11438 (org-update-parent-todo-statistics))
11439 (run-hooks 'org-after-todo-state-change-hook)
11440 (if (and arg (not (member state org-done-keywords)))
11441 (setq head (org-get-todo-sequence-head state)))
11442 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11443 ;; Do we need to trigger a repeat?
11444 (when now-done-p
11445 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11446 ;; This is for the agenda, take a snapshot of the headline.
11447 (save-match-data
11448 (setq org-agenda-headline-snapshot-before-repeat
11449 (org-get-heading))))
11450 (org-auto-repeat-maybe state))
11451 ;; Fixup cursor location if close to the keyword
11452 (if (and (outline-on-heading-p)
11453 (not (bolp))
11454 (save-excursion (beginning-of-line 1)
11455 (looking-at org-todo-line-regexp))
11456 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11457 (progn
11458 (goto-char (or (match-end 2) (match-end 1)))
11459 (and (looking-at " ") (just-one-space))))
11460 (when org-trigger-hook
11461 (save-excursion
11462 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11464 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11465 "Block turning an entry into a TODO, using the hierarchy.
11466 This checks whether the current task should be blocked from state
11467 changes. Such blocking occurs when:
11469 1. The task has children which are not all in a completed state.
11471 2. A task has a parent with the property :ORDERED:, and there
11472 are siblings prior to the current task with incomplete
11473 status.
11475 3. The parent of the task is blocked because it has siblings that should
11476 be done first, or is child of a block grandparent TODO entry."
11478 (if (not org-enforce-todo-dependencies)
11479 t ; if locally turned off don't block
11480 (catch 'dont-block
11481 ;; If this is not a todo state change, or if this entry is already DONE,
11482 ;; do not block
11483 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11484 (member (plist-get change-plist :from)
11485 (cons 'done org-done-keywords))
11486 (member (plist-get change-plist :to)
11487 (cons 'todo org-not-done-keywords))
11488 (not (plist-get change-plist :to)))
11489 (throw 'dont-block t))
11490 ;; If this task has children, and any are undone, it's blocked
11491 (save-excursion
11492 (org-back-to-heading t)
11493 (let ((this-level (funcall outline-level)))
11494 (outline-next-heading)
11495 (let ((child-level (funcall outline-level)))
11496 (while (and (not (eobp))
11497 (> child-level this-level))
11498 ;; this todo has children, check whether they are all
11499 ;; completed
11500 (if (and (not (org-entry-is-done-p))
11501 (org-entry-is-todo-p))
11502 (throw 'dont-block nil))
11503 (outline-next-heading)
11504 (setq child-level (funcall outline-level))))))
11505 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11506 ;; any previous siblings are undone, it's blocked
11507 (save-excursion
11508 (org-back-to-heading t)
11509 (let* ((pos (point))
11510 (parent-pos (and (org-up-heading-safe) (point))))
11511 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11512 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11513 (forward-line 1)
11514 (re-search-forward org-not-done-heading-regexp pos t))
11515 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11516 ;; Search further up the hierarchy, to see if an ancestor is blocked
11517 (while t
11518 (goto-char parent-pos)
11519 (if (not (looking-at org-not-done-heading-regexp))
11520 (throw 'dont-block t)) ; do not block, parent is not a TODO
11521 (setq pos (point))
11522 (setq parent-pos (and (org-up-heading-safe) (point)))
11523 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11524 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11525 (forward-line 1)
11526 (re-search-forward org-not-done-heading-regexp pos t))
11527 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11529 (defcustom org-track-ordered-property-with-tag nil
11530 "Should the ORDERED property also be shown as a tag?
11531 The ORDERED property decides if an entry should require subtasks to be
11532 completed in sequence. Since a property is not very visible, setting
11533 this option means that toggling the ORDERED property with the command
11534 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11535 not relevant for the behavior, but it makes things more visible.
11537 Note that toggling the tag with tags commands will not change the property
11538 and therefore not influence behavior!
11540 This can be t, meaning the tag ORDERED should be used, It can also be a
11541 string to select a different tag for this task."
11542 :group 'org-todo
11543 :type '(choice
11544 (const :tag "No tracking" nil)
11545 (const :tag "Track with ORDERED tag" t)
11546 (string :tag "Use other tag")))
11548 (defun org-toggle-ordered-property ()
11549 "Toggle the ORDERED property of the current entry.
11550 For better visibility, you can track the value of this property with a tag.
11551 See variable `org-track-ordered-property-with-tag'."
11552 (interactive)
11553 (let* ((t1 org-track-ordered-property-with-tag)
11554 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11555 (save-excursion
11556 (org-back-to-heading)
11557 (if (org-entry-get nil "ORDERED")
11558 (progn
11559 (org-delete-property "ORDERED")
11560 (and tag (org-toggle-tag tag 'off))
11561 (message "Subtasks can be completed in arbitrary order"))
11562 (org-entry-put nil "ORDERED" "t")
11563 (and tag (org-toggle-tag tag 'on))
11564 (message "Subtasks must be completed in sequence")))))
11566 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11567 (defun org-block-todo-from-checkboxes (change-plist)
11568 "Block turning an entry into a TODO, using checkboxes.
11569 This checks whether the current task should be blocked from state
11570 changes because there are unchecked boxes in this entry."
11571 (if (not org-enforce-todo-checkbox-dependencies)
11572 t ; if locally turned off don't block
11573 (catch 'dont-block
11574 ;; If this is not a todo state change, or if this entry is already DONE,
11575 ;; do not block
11576 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11577 (member (plist-get change-plist :from)
11578 (cons 'done org-done-keywords))
11579 (member (plist-get change-plist :to)
11580 (cons 'todo org-not-done-keywords))
11581 (not (plist-get change-plist :to)))
11582 (throw 'dont-block t))
11583 ;; If this task has checkboxes that are not checked, it's blocked
11584 (save-excursion
11585 (org-back-to-heading t)
11586 (let ((beg (point)) end)
11587 (outline-next-heading)
11588 (setq end (point))
11589 (goto-char beg)
11590 (if (org-list-search-forward
11591 (concat (org-item-beginning-re)
11592 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11593 "\\[[- ]\\]")
11594 end t)
11595 (progn
11596 (if (boundp 'org-blocked-by-checkboxes)
11597 (setq org-blocked-by-checkboxes t))
11598 (throw 'dont-block nil)))))
11599 t))) ; do not block
11601 (defun org-entry-blocked-p ()
11602 "Is the current entry blocked?"
11603 (if (org-entry-get nil "NOBLOCKING")
11604 nil ;; Never block this entry
11605 (not
11606 (run-hook-with-args-until-failure
11607 'org-blocker-hook
11608 (list :type 'todo-state-change
11609 :position (point)
11610 :from 'todo
11611 :to 'done)))))
11613 (defun org-update-statistics-cookies (all)
11614 "Update the statistics cookie, either from TODO or from checkboxes.
11615 This should be called with the cursor in a line with a statistics cookie."
11616 (interactive "P")
11617 (if all
11618 (progn
11619 (org-update-checkbox-count 'all)
11620 (org-map-entries 'org-update-parent-todo-statistics))
11621 (if (not (org-at-heading-p))
11622 (org-update-checkbox-count)
11623 (let ((pos (move-marker (make-marker) (point)))
11624 end l1 l2)
11625 (ignore-errors (org-back-to-heading t))
11626 (if (not (org-at-heading-p))
11627 (org-update-checkbox-count)
11628 (setq l1 (org-outline-level))
11629 (setq end (save-excursion
11630 (outline-next-heading)
11631 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11632 (point)))
11633 (if (and (save-excursion
11634 (re-search-forward
11635 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11636 (not (save-excursion (re-search-forward
11637 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11638 (org-update-checkbox-count)
11639 (if (and l2 (> l2 l1))
11640 (progn
11641 (goto-char end)
11642 (org-update-parent-todo-statistics))
11643 (goto-char pos)
11644 (beginning-of-line 1)
11645 (while (re-search-forward
11646 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11647 (point-at-eol) t)
11648 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11649 (goto-char pos)
11650 (move-marker pos nil)))))
11652 (defvar org-entry-property-inherited-from) ;; defined below
11653 (defun org-update-parent-todo-statistics ()
11654 "Update any statistics cookie in the parent of the current headline.
11655 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11656 the entire subtree and this will travel up the hierarchy and update
11657 statistics everywhere."
11658 (let* ((prop (save-excursion (org-up-heading-safe)
11659 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11660 (recursive (or (not org-hierarchical-todo-statistics)
11661 (and prop (string-match "\\<recursive\\>" prop))))
11662 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11664 (first t)
11665 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11666 level ltoggle l1 new ndel
11667 (cnt-all 0) (cnt-done 0) is-percent kwd
11668 checkbox-beg ov ovs ove cookie-present)
11669 (catch 'exit
11670 (save-excursion
11671 (beginning-of-line 1)
11672 (setq ltoggle (funcall outline-level))
11673 ;; Three situations are to consider:
11675 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11676 ;; to the top-level ancestor on the headline;
11678 ;; 2. If parent has "recursive" property, repeat up to the
11679 ;; headline setting that property, taking inheritance into
11680 ;; account;
11682 ;; 3. Else, move up to direct parent and proceed only once.
11683 (while (and (setq level (org-up-heading-safe))
11684 (or recursive first)
11685 (>= (point) lim))
11686 (setq first nil cookie-present nil)
11687 (unless (and level
11688 (not (string-match
11689 "\\<checkbox\\>"
11690 (downcase (or (org-entry-get nil "COOKIE_DATA")
11691 "")))))
11692 (throw 'exit nil))
11693 (while (re-search-forward box-re (point-at-eol) t)
11694 (setq cnt-all 0 cnt-done 0 cookie-present t)
11695 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11696 (save-match-data
11697 (unless (outline-next-heading) (throw 'exit nil))
11698 (while (and (looking-at org-complex-heading-regexp)
11699 (> (setq l1 (length (match-string 1))) level))
11700 (setq kwd (and (or recursive (= l1 ltoggle))
11701 (match-string 2)))
11702 (if (or (eq org-provide-todo-statistics 'all-headlines)
11703 (and (listp org-provide-todo-statistics)
11704 (or (member kwd org-provide-todo-statistics)
11705 (member kwd org-done-keywords))))
11706 (setq cnt-all (1+ cnt-all))
11707 (if (eq org-provide-todo-statistics t)
11708 (and kwd (setq cnt-all (1+ cnt-all)))))
11709 (and (member kwd org-done-keywords)
11710 (setq cnt-done (1+ cnt-done)))
11711 (outline-next-heading)))
11712 (setq new
11713 (if is-percent
11714 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11715 (format "[%d/%d]" cnt-done cnt-all))
11716 ndel (- (match-end 0) checkbox-beg))
11717 ;; handle overlays when updating cookie from column view
11718 (when (setq ov (car (overlays-at checkbox-beg)))
11719 (setq ovs (overlay-start ov) ove (overlay-end ov))
11720 (delete-overlay ov))
11721 (goto-char checkbox-beg)
11722 (insert new)
11723 (delete-region (point) (+ (point) ndel))
11724 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11725 (when ov (move-overlay ov ovs ove)))
11726 (when cookie-present
11727 (run-hook-with-args 'org-after-todo-statistics-hook
11728 cnt-done (- cnt-all cnt-done))))))
11729 (run-hooks 'org-todo-statistics-hook)))
11731 (defvar org-after-todo-statistics-hook nil
11732 "Hook that is called after a TODO statistics cookie has been updated.
11733 Each function is called with two arguments: the number of not-done entries
11734 and the number of done entries.
11736 For example, the following function, when added to this hook, will switch
11737 an entry to DONE when all children are done, and back to TODO when new
11738 entries are set to a TODO status. Note that this hook is only called
11739 when there is a statistics cookie in the headline!
11741 (defun org-summary-todo (n-done n-not-done)
11742 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11743 (let (org-log-done org-log-states) ; turn off logging
11744 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11747 (defvar org-todo-statistics-hook nil
11748 "Hook that is run whenever Org thinks TODO statistics should be updated.
11749 This hook runs even if there is no statistics cookie present, in which case
11750 `org-after-todo-statistics-hook' would not run.")
11752 (defun org-todo-trigger-tag-changes (state)
11753 "Apply the changes defined in `org-todo-state-tags-triggers'."
11754 (let ((l org-todo-state-tags-triggers)
11755 changes)
11756 (when (or (not state) (equal state ""))
11757 (setq changes (append changes (cdr (assoc "" l)))))
11758 (when (and (stringp state) (> (length state) 0))
11759 (setq changes (append changes (cdr (assoc state l)))))
11760 (when (member state org-not-done-keywords)
11761 (setq changes (append changes (cdr (assoc 'todo l)))))
11762 (when (member state org-done-keywords)
11763 (setq changes (append changes (cdr (assoc 'done l)))))
11764 (dolist (c changes)
11765 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11767 (defun org-local-logging (value)
11768 "Get logging settings from a property VALUE."
11769 (let* (words w a)
11770 ;; directly set the variables, they are already local.
11771 (setq org-log-done nil
11772 org-log-repeat nil
11773 org-todo-log-states nil)
11774 (setq words (org-split-string value))
11775 (while (setq w (pop words))
11776 (cond
11777 ((setq a (assoc w org-startup-options))
11778 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11779 (set (nth 1 a) (nth 2 a))))
11780 ((setq a (org-extract-log-state-settings w))
11781 (and (member (car a) org-todo-keywords-1)
11782 (push a org-todo-log-states)))))))
11784 (defun org-get-todo-sequence-head (kwd)
11785 "Return the head of the TODO sequence to which KWD belongs.
11786 If KWD is not set, check if there is a text property remembering the
11787 right sequence."
11788 (let (p)
11789 (cond
11790 ((not kwd)
11791 (or (get-text-property (point-at-bol) 'org-todo-head)
11792 (progn
11793 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11794 nil (point-at-eol)))
11795 (get-text-property p 'org-todo-head))))
11796 ((not (member kwd org-todo-keywords-1))
11797 (car org-todo-keywords-1))
11798 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11800 (defun org-fast-todo-selection ()
11801 "Fast TODO keyword selection with single keys.
11802 Returns the new TODO keyword, or nil if no state change should occur."
11803 (let* ((fulltable org-todo-key-alist)
11804 (done-keywords org-done-keywords) ;; needed for the faces.
11805 (maxlen (apply 'max (mapcar
11806 (lambda (x)
11807 (if (stringp (car x)) (string-width (car x)) 0))
11808 fulltable)))
11809 (expert nil)
11810 (fwidth (+ maxlen 3 1 3))
11811 (ncol (/ (- (window-width) 4) fwidth))
11812 tg cnt e c tbl
11813 groups ingroup)
11814 (save-excursion
11815 (save-window-excursion
11816 (if expert
11817 (set-buffer (get-buffer-create " *Org todo*"))
11818 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11819 (erase-buffer)
11820 (org-set-local 'org-done-keywords done-keywords)
11821 (setq tbl fulltable cnt 0)
11822 (while (setq e (pop tbl))
11823 (cond
11824 ((equal e '(:startgroup))
11825 (push '() groups) (setq ingroup t)
11826 (when (not (= cnt 0))
11827 (setq cnt 0)
11828 (insert "\n"))
11829 (insert "{ "))
11830 ((equal e '(:endgroup))
11831 (setq ingroup nil cnt 0)
11832 (insert "}\n"))
11833 ((equal e '(:newline))
11834 (when (not (= cnt 0))
11835 (setq cnt 0)
11836 (insert "\n")
11837 (setq e (car tbl))
11838 (while (equal (car tbl) '(:newline))
11839 (insert "\n")
11840 (setq tbl (cdr tbl)))))
11842 (setq tg (car e) c (cdr e))
11843 (if ingroup (push tg (car groups)))
11844 (setq tg (org-add-props tg nil 'face
11845 (org-get-todo-face tg)))
11846 (if (and (= cnt 0) (not ingroup)) (insert " "))
11847 (insert "[" c "] " tg (make-string
11848 (- fwidth 4 (length tg)) ?\ ))
11849 (when (= (setq cnt (1+ cnt)) ncol)
11850 (insert "\n")
11851 (if ingroup (insert " "))
11852 (setq cnt 0)))))
11853 (insert "\n")
11854 (goto-char (point-min))
11855 (if (not expert) (org-fit-window-to-buffer))
11856 (message "[a-z..]:Set [SPC]:clear")
11857 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11858 (cond
11859 ((or (= c ?\C-g)
11860 (and (= c ?q) (not (rassoc c fulltable))))
11861 (setq quit-flag t))
11862 ((= c ?\ ) nil)
11863 ((setq e (rassoc c fulltable) tg (car e))
11865 (t (setq quit-flag t)))))))
11867 (defun org-entry-is-todo-p ()
11868 (member (org-get-todo-state) org-not-done-keywords))
11870 (defun org-entry-is-done-p ()
11871 (member (org-get-todo-state) org-done-keywords))
11873 (defun org-get-todo-state ()
11874 (save-excursion
11875 (org-back-to-heading t)
11876 (and (looking-at org-todo-line-regexp)
11877 (match-end 2)
11878 (match-string 2))))
11880 (defun org-at-date-range-p (&optional inactive-ok)
11881 "Is the cursor inside a date range?"
11882 (interactive)
11883 (save-excursion
11884 (catch 'exit
11885 (let ((pos (point)))
11886 (skip-chars-backward "^[<\r\n")
11887 (skip-chars-backward "<[")
11888 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11889 (>= (match-end 0) pos)
11890 (throw 'exit t))
11891 (skip-chars-backward "^<[\r\n")
11892 (skip-chars-backward "<[")
11893 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11894 (>= (match-end 0) pos)
11895 (throw 'exit t)))
11896 nil)))
11898 (defun org-get-repeat (&optional tagline)
11899 "Check if there is a deadline/schedule with repeater in this entry."
11900 (save-match-data
11901 (save-excursion
11902 (org-back-to-heading t)
11903 (and (re-search-forward (if tagline
11904 (concat tagline "\\s-*" org-repeat-re)
11905 org-repeat-re)
11906 (org-entry-end-position) t)
11907 (match-string-no-properties 1)))))
11909 (defvar org-last-changed-timestamp)
11910 (defvar org-last-inserted-timestamp)
11911 (defvar org-log-post-message)
11912 (defvar org-log-note-purpose)
11913 (defvar org-log-note-how)
11914 (defvar org-log-note-extra)
11915 (defun org-auto-repeat-maybe (done-word)
11916 "Check if the current headline contains a repeated deadline/schedule.
11917 If yes, set TODO state back to what it was and change the base date
11918 of repeating deadline/scheduled time stamps to new date.
11919 This function is run automatically after each state change to a DONE state."
11920 ;; last-state is dynamically scoped into this function
11921 (let* ((repeat (org-get-repeat))
11922 (aa (assoc last-state org-todo-kwd-alist))
11923 (interpret (nth 1 aa))
11924 (head (nth 2 aa))
11925 (whata '(("d" . day) ("m" . month) ("y" . year)))
11926 (msg "Entry repeats: ")
11927 (org-log-done nil)
11928 (org-todo-log-states nil)
11929 re type n what ts time to-state)
11930 (when repeat
11931 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11932 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11933 org-todo-repeat-to-state))
11934 (unless (and to-state (member to-state org-todo-keywords-1))
11935 (setq to-state (if (eq interpret 'type) last-state head)))
11936 (org-todo to-state)
11937 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11938 (org-entry-put nil "LAST_REPEAT" (format-time-string
11939 (org-time-stamp-format t t))))
11940 (when org-log-repeat
11941 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11942 (memq 'org-add-log-note post-command-hook))
11943 ;; OK, we are already setup for some record
11944 (if (eq org-log-repeat 'note)
11945 ;; make sure we take a note, not only a time stamp
11946 (setq org-log-note-how 'note))
11947 ;; Set up for taking a record
11948 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11949 last-state
11950 'findpos org-log-repeat)))
11951 (org-back-to-heading t)
11952 (org-add-planning-info nil nil 'closed)
11953 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11954 org-deadline-time-regexp "\\)\\|\\("
11955 org-ts-regexp "\\)"))
11956 (while (re-search-forward
11957 re (save-excursion (outline-next-heading) (point)) t)
11958 (setq type (if (match-end 1) org-scheduled-string
11959 (if (match-end 3) org-deadline-string "Plain:"))
11960 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11961 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11962 (setq n (string-to-number (match-string 2 ts))
11963 what (match-string 3 ts))
11964 (if (equal what "w") (setq n (* n 7) what "d"))
11965 ;; Preparation, see if we need to modify the start date for the change
11966 (when (match-end 1)
11967 (setq time (save-match-data (org-time-string-to-time ts)))
11968 (cond
11969 ((equal (match-string 1 ts) ".")
11970 ;; Shift starting date to today
11971 (org-timestamp-change
11972 (- (org-today) (time-to-days time))
11973 'day))
11974 ((equal (match-string 1 ts) "+")
11975 (let ((nshiftmax 10) (nshift 0))
11976 (while (or (= nshift 0)
11977 (<= (time-to-days time)
11978 (time-to-days (current-time))))
11979 (when (= (incf nshift) nshiftmax)
11980 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11981 (error "Abort")))
11982 (org-timestamp-change n (cdr (assoc what whata)))
11983 (org-at-timestamp-p t)
11984 (setq ts (match-string 1))
11985 (setq time (save-match-data (org-time-string-to-time ts)))))
11986 (org-timestamp-change (- n) (cdr (assoc what whata)))
11987 ;; rematch, so that we have everything in place for the real shift
11988 (org-at-timestamp-p t)
11989 (setq ts (match-string 1))
11990 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11991 (org-timestamp-change n (cdr (assoc what whata)))
11992 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11993 (setq org-log-post-message msg)
11994 (message "%s" msg))))
11996 (defun org-show-todo-tree (arg)
11997 "Make a compact tree which shows all headlines marked with TODO.
11998 The tree will show the lines where the regexp matches, and all higher
11999 headlines above the match.
12000 With a \\[universal-argument] prefix, prompt for a regexp to match.
12001 With a numeric prefix N, construct a sparse tree for the Nth element
12002 of `org-todo-keywords-1'."
12003 (interactive "P")
12004 (let ((case-fold-search nil)
12005 (kwd-re
12006 (cond ((null arg) org-not-done-regexp)
12007 ((equal arg '(4))
12008 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12009 (mapcar 'list org-todo-keywords-1))))
12010 (concat "\\("
12011 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12012 "\\)\\>")))
12013 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12014 (regexp-quote (nth (1- (prefix-numeric-value arg))
12015 org-todo-keywords-1)))
12016 (t (error "Invalid prefix argument: %s" arg)))))
12017 (message "%d TODO entries found"
12018 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12020 (defun org-deadline (&optional remove time)
12021 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12022 With argument REMOVE, remove any deadline from the item.
12023 With argument TIME, set the deadline at the corresponding date. TIME
12024 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12025 (interactive "P")
12026 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12027 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12028 'region-start-level 'region))
12029 org-loop-over-headlines-in-active-region)
12030 (org-map-entries
12031 `(org-deadline ',remove ,time)
12032 org-loop-over-headlines-in-active-region
12033 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12034 (let* ((old-date (org-entry-get nil "DEADLINE"))
12035 (repeater (and old-date
12036 (string-match
12037 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12038 old-date)
12039 (match-string 1 old-date))))
12040 (if remove
12041 (progn
12042 (when (and old-date org-log-redeadline)
12043 (org-add-log-setup 'deldeadline nil old-date 'findpos
12044 org-log-redeadline))
12045 (org-remove-timestamp-with-keyword org-deadline-string)
12046 (message "Item no longer has a deadline."))
12047 (org-add-planning-info 'deadline time 'closed)
12048 (when (and old-date org-log-redeadline
12049 (not (equal old-date
12050 (substring org-last-inserted-timestamp 1 -1))))
12051 (org-add-log-setup 'redeadline nil old-date 'findpos
12052 org-log-redeadline))
12053 (when repeater
12054 (save-excursion
12055 (org-back-to-heading t)
12056 (when (re-search-forward (concat org-deadline-string " "
12057 org-last-inserted-timestamp)
12058 (save-excursion
12059 (outline-next-heading) (point)) t)
12060 (goto-char (1- (match-end 0)))
12061 (insert " " repeater)
12062 (setq org-last-inserted-timestamp
12063 (concat (substring org-last-inserted-timestamp 0 -1)
12064 " " repeater
12065 (substring org-last-inserted-timestamp -1))))))
12066 (message "Deadline on %s" org-last-inserted-timestamp)))))
12068 (defun org-schedule (&optional remove time)
12069 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12070 With argument REMOVE, remove any scheduling date from the item.
12071 With argument TIME, scheduled at the corresponding date. TIME can
12072 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12073 (interactive "P")
12074 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12075 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12076 'region-start-level 'region))
12077 org-loop-over-headlines-in-active-region)
12078 (org-map-entries
12079 `(org-schedule ',remove ,time)
12080 org-loop-over-headlines-in-active-region
12081 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12082 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12083 (repeater (and old-date
12084 (string-match
12085 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12086 old-date)
12087 (match-string 1 old-date))))
12088 (if remove
12089 (progn
12090 (when (and old-date org-log-reschedule)
12091 (org-add-log-setup 'delschedule nil old-date 'findpos
12092 org-log-reschedule))
12093 (org-remove-timestamp-with-keyword org-scheduled-string)
12094 (message "Item is no longer scheduled."))
12095 (org-add-planning-info 'scheduled time 'closed)
12096 (when (and old-date org-log-reschedule
12097 (not (equal old-date
12098 (substring org-last-inserted-timestamp 1 -1))))
12099 (org-add-log-setup 'reschedule nil old-date 'findpos
12100 org-log-reschedule))
12101 (when repeater
12102 (save-excursion
12103 (org-back-to-heading t)
12104 (when (re-search-forward (concat org-scheduled-string " "
12105 org-last-inserted-timestamp)
12106 (save-excursion
12107 (outline-next-heading) (point)) t)
12108 (goto-char (1- (match-end 0)))
12109 (insert " " repeater)
12110 (setq org-last-inserted-timestamp
12111 (concat (substring org-last-inserted-timestamp 0 -1)
12112 " " repeater
12113 (substring org-last-inserted-timestamp -1))))))
12114 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12116 (defun org-get-scheduled-time (pom &optional inherit)
12117 "Get the scheduled time as a time tuple, of a format suitable
12118 for calling org-schedule with, or if there is no scheduling,
12119 returns nil."
12120 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12121 (when time
12122 (apply 'encode-time (org-parse-time-string time)))))
12124 (defun org-get-deadline-time (pom &optional inherit)
12125 "Get the deadline as a time tuple, of a format suitable for
12126 calling org-deadline with, or if there is no scheduling, returns
12127 nil."
12128 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12129 (when time
12130 (apply 'encode-time (org-parse-time-string time)))))
12132 (defun org-remove-timestamp-with-keyword (keyword)
12133 "Remove all time stamps with KEYWORD in the current entry."
12134 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12135 beg)
12136 (save-excursion
12137 (org-back-to-heading t)
12138 (setq beg (point))
12139 (outline-next-heading)
12140 (while (re-search-backward re beg t)
12141 (replace-match "")
12142 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12143 (equal (char-before) ?\ ))
12144 (backward-delete-char 1)
12145 (if (string-match "^[ \t]*$" (buffer-substring
12146 (point-at-bol) (point-at-eol)))
12147 (delete-region (point-at-bol)
12148 (min (point-max) (1+ (point-at-eol))))))))))
12150 (defun org-add-planning-info (what &optional time &rest remove)
12151 "Insert new timestamp with keyword in the line directly after the headline.
12152 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12153 If non is given, the user is prompted for a date.
12154 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12155 be removed."
12156 (interactive)
12157 (let (org-time-was-given org-end-time-was-given ts
12158 end default-time default-input)
12160 (catch 'exit
12161 (when (and (memq what '(scheduled deadline))
12162 (or (not time)
12163 (and (stringp time)
12164 (string-match "^[-+]+[0-9]" time))))
12165 ;; Try to get a default date/time from existing timestamp
12166 (save-excursion
12167 (org-back-to-heading t)
12168 (setq end (save-excursion (outline-next-heading) (point)))
12169 (when (re-search-forward (if (eq what 'scheduled)
12170 org-scheduled-time-regexp
12171 org-deadline-time-regexp)
12172 end t)
12173 (setq ts (match-string 1)
12174 default-time
12175 (apply 'encode-time (org-parse-time-string ts))
12176 default-input (and ts (org-get-compact-tod ts))))))
12177 (when what
12178 (setq time
12179 (if (stringp time)
12180 ;; This is a string (relative or absolute), set proper date
12181 (apply 'encode-time
12182 (org-read-date-analyze
12183 time default-time (decode-time default-time)))
12184 ;; If necessary, get the time from the user
12185 (or time (org-read-date nil 'to-time nil nil
12186 default-time default-input)))))
12188 (when (and org-insert-labeled-timestamps-at-point
12189 (member what '(scheduled deadline)))
12190 (insert
12191 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12192 (org-insert-time-stamp time org-time-was-given
12193 nil nil nil (list org-end-time-was-given))
12194 (setq what nil))
12195 (save-excursion
12196 (save-restriction
12197 (let (col list elt ts buffer-invisibility-spec)
12198 (org-back-to-heading t)
12199 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12200 (goto-char (match-end 1))
12201 (setq col (current-column))
12202 (goto-char (match-end 0))
12203 (if (eobp) (insert "\n") (forward-char 1))
12204 (when (and (not what)
12205 (not (looking-at
12206 (concat "[ \t]*"
12207 org-keyword-time-not-clock-regexp))))
12208 ;; Nothing to add, nothing to remove...... :-)
12209 (throw 'exit nil))
12210 (if (and (not (looking-at org-outline-regexp))
12211 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12212 "[^\r\n]*"))
12213 (not (equal (match-string 1) org-clock-string)))
12214 (narrow-to-region (match-beginning 0) (match-end 0))
12215 (insert-before-markers "\n")
12216 (backward-char 1)
12217 (narrow-to-region (point) (point))
12218 (and org-adapt-indentation (org-indent-to-column col)))
12219 ;; Check if we have to remove something.
12220 (setq list (cons what remove))
12221 (while list
12222 (setq elt (pop list))
12223 (when (or (and (eq elt 'scheduled)
12224 (re-search-forward org-scheduled-time-regexp nil t))
12225 (and (eq elt 'deadline)
12226 (re-search-forward org-deadline-time-regexp nil t))
12227 (and (eq elt 'closed)
12228 (re-search-forward org-closed-time-regexp nil t)))
12229 (replace-match "")
12230 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12231 (and (looking-at "[ \t]+") (replace-match ""))
12232 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12233 (when what
12234 (insert
12235 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12236 (cond ((eq what 'scheduled) org-scheduled-string)
12237 ((eq what 'deadline) org-deadline-string)
12238 ((eq what 'closed) org-closed-string))
12239 " ")
12240 (setq ts (org-insert-time-stamp
12241 time
12242 (or org-time-was-given
12243 (and (eq what 'closed) org-log-done-with-time))
12244 (eq what 'closed)
12245 nil nil (list org-end-time-was-given)))
12246 (insert
12247 (if (not (or (bolp) (eq (char-before) ?\ )
12248 (memq (char-after) '(32 10))
12249 (eobp))) " " ""))
12250 (end-of-line 1))
12251 (goto-char (point-min))
12252 (widen)
12253 (if (and (looking-at "[ \t]*\n")
12254 (equal (char-before) ?\n))
12255 (delete-region (1- (point)) (point-at-eol)))
12256 ts))))))
12258 (defvar org-log-note-marker (make-marker))
12259 (defvar org-log-note-purpose nil)
12260 (defvar org-log-note-state nil)
12261 (defvar org-log-note-previous-state nil)
12262 (defvar org-log-note-how nil)
12263 (defvar org-log-note-extra nil)
12264 (defvar org-log-note-window-configuration nil)
12265 (defvar org-log-note-return-to (make-marker))
12266 (defvar org-log-note-effective-time nil
12267 "Remembered current time so that dynamically scoped
12268 `org-extend-today-until' affects tha timestamps in state change
12269 log")
12271 (defvar org-log-post-message nil
12272 "Message to be displayed after a log note has been stored.
12273 The auto-repeater uses this.")
12275 (defun org-add-note ()
12276 "Add a note to the current entry.
12277 This is done in the same way as adding a state change note."
12278 (interactive)
12279 (org-add-log-setup 'note nil nil 'findpos nil))
12281 (defvar org-property-end-re)
12282 (defun org-add-log-setup (&optional purpose state prev-state
12283 findpos how extra)
12284 "Set up the post command hook to take a note.
12285 If this is about to TODO state change, the new state is expected in STATE.
12286 When FINDPOS is non-nil, find the correct position for the note in
12287 the current entry. If not, assume that it can be inserted at point.
12288 HOW is an indicator what kind of note should be created.
12289 EXTRA is additional text that will be inserted into the notes buffer."
12290 (let* ((org-log-into-drawer (org-log-into-drawer))
12291 (drawer (cond ((stringp org-log-into-drawer)
12292 org-log-into-drawer)
12293 (org-log-into-drawer "LOGBOOK")
12294 (t nil))))
12295 (save-restriction
12296 (save-excursion
12297 (when findpos
12298 (org-back-to-heading t)
12299 (narrow-to-region (point) (save-excursion
12300 (outline-next-heading) (point)))
12301 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12302 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12303 "[^\r\n]*\\)?"))
12304 (goto-char (match-end 0))
12305 (cond
12306 (drawer
12307 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12308 nil t)
12309 (progn
12310 (goto-char (match-end 0))
12311 (or org-log-states-order-reversed
12312 (and (re-search-forward org-property-end-re nil t)
12313 (goto-char (1- (match-beginning 0))))))
12314 (insert "\n:" drawer ":\n:END:")
12315 (beginning-of-line 0)
12316 (org-indent-line-function)
12317 (beginning-of-line 2)
12318 (org-indent-line-function)
12319 (end-of-line 0)))
12320 ((and org-log-state-notes-insert-after-drawers
12321 (save-excursion
12322 (forward-line) (looking-at org-drawer-regexp)))
12323 (forward-line)
12324 (while (looking-at org-drawer-regexp)
12325 (goto-char (match-end 0))
12326 (re-search-forward org-property-end-re (point-max) t)
12327 (forward-line))
12328 (forward-line -1)))
12329 (unless org-log-states-order-reversed
12330 (and (= (char-after) ?\n) (forward-char 1))
12331 (org-skip-over-state-notes)
12332 (skip-chars-backward " \t\n\r")))
12333 (move-marker org-log-note-marker (point))
12334 (setq org-log-note-purpose purpose
12335 org-log-note-state state
12336 org-log-note-previous-state prev-state
12337 org-log-note-how how
12338 org-log-note-extra extra
12339 org-log-note-effective-time (org-current-effective-time))
12340 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12342 (defun org-skip-over-state-notes ()
12343 "Skip past the list of State notes in an entry."
12344 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12345 (when (ignore-errors (goto-char (org-in-item-p)))
12346 (let* ((struct (org-list-struct))
12347 (prevs (org-list-prevs-alist struct)))
12348 (while (looking-at "[ \t]*- State")
12349 (goto-char (or (org-list-get-next-item (point) struct prevs)
12350 (org-list-get-item-end (point) struct)))))))
12352 (defun org-add-log-note (&optional purpose)
12353 "Pop up a window for taking a note, and add this note later at point."
12354 (remove-hook 'post-command-hook 'org-add-log-note)
12355 (setq org-log-note-window-configuration (current-window-configuration))
12356 (delete-other-windows)
12357 (move-marker org-log-note-return-to (point))
12358 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12359 (goto-char org-log-note-marker)
12360 (org-switch-to-buffer-other-window "*Org Note*")
12361 (erase-buffer)
12362 (if (memq org-log-note-how '(time state))
12363 (let (current-prefix-arg) (org-store-log-note))
12364 (let ((org-inhibit-startup t)) (org-mode))
12365 (insert (format "# Insert note for %s.
12366 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12367 (cond
12368 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12369 ((eq org-log-note-purpose 'done) "closed todo item")
12370 ((eq org-log-note-purpose 'state)
12371 (format "state change from \"%s\" to \"%s\""
12372 (or org-log-note-previous-state "")
12373 (or org-log-note-state "")))
12374 ((eq org-log-note-purpose 'reschedule)
12375 "rescheduling")
12376 ((eq org-log-note-purpose 'delschedule)
12377 "no longer scheduled")
12378 ((eq org-log-note-purpose 'redeadline)
12379 "changing deadline")
12380 ((eq org-log-note-purpose 'deldeadline)
12381 "removing deadline")
12382 ((eq org-log-note-purpose 'refile)
12383 "refiling")
12384 ((eq org-log-note-purpose 'note)
12385 "this entry")
12386 (t (error "This should not happen")))))
12387 (if org-log-note-extra (insert org-log-note-extra))
12388 (org-set-local 'org-finish-function 'org-store-log-note)
12389 (run-hooks 'org-log-buffer-setup-hook)))
12391 (defvar org-note-abort nil) ; dynamically scoped
12392 (defun org-store-log-note ()
12393 "Finish taking a log note, and insert it to where it belongs."
12394 (let ((txt (buffer-string))
12395 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12396 lines ind bul)
12397 (kill-buffer (current-buffer))
12398 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12399 (setq txt (replace-match "" t t txt)))
12400 (if (string-match "\\s-+\\'" txt)
12401 (setq txt (replace-match "" t t txt)))
12402 (setq lines (org-split-string txt "\n"))
12403 (when (and note (string-match "\\S-" note))
12404 (setq note
12405 (org-replace-escapes
12406 note
12407 (list (cons "%u" (user-login-name))
12408 (cons "%U" user-full-name)
12409 (cons "%t" (format-time-string
12410 (org-time-stamp-format 'long 'inactive)
12411 org-log-note-effective-time))
12412 (cons "%T" (format-time-string
12413 (org-time-stamp-format 'long nil)
12414 org-log-note-effective-time))
12415 (cons "%d" (format-time-string
12416 (org-time-stamp-format nil 'inactive)
12417 org-log-note-effective-time))
12418 (cons "%D" (format-time-string
12419 (org-time-stamp-format nil nil)
12420 org-log-note-effective-time))
12421 (cons "%s" (if org-log-note-state
12422 (concat "\"" org-log-note-state "\"")
12423 ""))
12424 (cons "%S" (if org-log-note-previous-state
12425 (concat "\"" org-log-note-previous-state "\"")
12426 "\"\"")))))
12427 (if lines (setq note (concat note " \\\\")))
12428 (push note lines))
12429 (when (or current-prefix-arg org-note-abort)
12430 (when org-log-into-drawer
12431 (org-remove-empty-drawer-at
12432 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12433 org-log-note-marker))
12434 (setq lines nil))
12435 (when lines
12436 (with-current-buffer (marker-buffer org-log-note-marker)
12437 (save-excursion
12438 (goto-char org-log-note-marker)
12439 (move-marker org-log-note-marker nil)
12440 (end-of-line 1)
12441 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12442 (setq ind (save-excursion
12443 (if (ignore-errors (goto-char (org-in-item-p)))
12444 (let ((struct (org-list-struct)))
12445 (org-list-get-ind
12446 (org-list-get-top-point struct) struct))
12447 (skip-chars-backward " \r\t\n")
12448 (cond
12449 ((and (org-at-heading-p)
12450 org-adapt-indentation)
12451 (1+ (org-current-level)))
12452 ((org-at-heading-p) 0)
12453 (t (org-get-indentation))))))
12454 (setq bul (org-list-bullet-string "-"))
12455 (org-indent-line-to ind)
12456 (insert bul (pop lines))
12457 (let ((ind-body (+ (length bul) ind)))
12458 (while lines
12459 (insert "\n")
12460 (org-indent-line-to ind-body)
12461 (insert (pop lines))))
12462 (message "Note stored")
12463 (org-back-to-heading t)
12464 (org-cycle-hide-drawers 'children)))))
12465 (set-window-configuration org-log-note-window-configuration)
12466 (with-current-buffer (marker-buffer org-log-note-return-to)
12467 (goto-char org-log-note-return-to))
12468 (move-marker org-log-note-return-to nil)
12469 (and org-log-post-message (message "%s" org-log-post-message)))
12471 (defun org-remove-empty-drawer-at (drawer pos)
12472 "Remove an empty drawer DRAWER at position POS.
12473 POS may also be a marker."
12474 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12475 (save-excursion
12476 (save-restriction
12477 (widen)
12478 (goto-char pos)
12479 (if (org-in-regexp
12480 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12481 (replace-match ""))))))
12483 (defun org-sparse-tree (&optional arg)
12484 "Create a sparse tree, prompt for the details.
12485 This command can create sparse trees. You first need to select the type
12486 of match used to create the tree:
12488 t Show all TODO entries.
12489 T Show entries with a specific TODO keyword.
12490 m Show entries selected by a tags/property match.
12491 p Enter a property name and its value (both with completion on existing
12492 names/values) and show entries with that property.
12493 r Show entries matching a regular expression (`/' can be used as well)
12494 d Show deadlines due within `org-deadline-warning-days'.
12495 b Show deadlines and scheduled items before a date.
12496 a Show deadlines and scheduled items after a date."
12497 (interactive "P")
12498 (let (ans kwd value)
12499 (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")
12500 (setq ans (read-char-exclusive))
12501 (cond
12502 ((equal ans ?d)
12503 (call-interactively 'org-check-deadlines))
12504 ((equal ans ?b)
12505 (call-interactively 'org-check-before-date))
12506 ((equal ans ?a)
12507 (call-interactively 'org-check-after-date))
12508 ((equal ans ?D)
12509 (call-interactively 'org-check-dates-range))
12510 ((equal ans ?t)
12511 (org-show-todo-tree nil))
12512 ((equal ans ?T)
12513 (org-show-todo-tree '(4)))
12514 ((member ans '(?T ?m))
12515 (call-interactively 'org-match-sparse-tree))
12516 ((member ans '(?p ?P))
12517 (setq kwd (org-icompleting-read "Property: "
12518 (mapcar 'list (org-buffer-property-keys))))
12519 (setq value (org-icompleting-read "Value: "
12520 (mapcar 'list (org-property-values kwd))))
12521 (unless (string-match "\\`{.*}\\'" value)
12522 (setq value (concat "\"" value "\"")))
12523 (org-match-sparse-tree arg (concat kwd "=" value)))
12524 ((member ans '(?r ?R ?/))
12525 (call-interactively 'org-occur))
12526 (t (error "No such sparse tree command \"%c\"" ans)))))
12528 (defvar org-occur-highlights nil
12529 "List of overlays used for occur matches.")
12530 (make-variable-buffer-local 'org-occur-highlights)
12531 (defvar org-occur-parameters nil
12532 "Parameters of the active org-occur calls.
12533 This is a list, each call to org-occur pushes as cons cell,
12534 containing the regular expression and the callback, onto the list.
12535 The list can contain several entries if `org-occur' has been called
12536 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12537 will only contain one set of parameters. When the highlights are
12538 removed (for example with `C-c C-c', or with the next edit (depending
12539 on `org-remove-highlights-with-change'), this variable is emptied
12540 as well.")
12541 (make-variable-buffer-local 'org-occur-parameters)
12543 (defun org-occur (regexp &optional keep-previous callback)
12544 "Make a compact tree which shows all matches of REGEXP.
12545 The tree will show the lines where the regexp matches, and all higher
12546 headlines above the match. It will also show the heading after the match,
12547 to make sure editing the matching entry is easy.
12548 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12549 call to `org-occur' will be kept, to allow stacking of calls to this
12550 command.
12551 If CALLBACK is non-nil, it is a function which is called to confirm
12552 that the match should indeed be shown."
12553 (interactive "sRegexp: \nP")
12554 (when (equal regexp "")
12555 (error "Regexp cannot be empty"))
12556 (unless keep-previous
12557 (org-remove-occur-highlights nil nil t))
12558 (push (cons regexp callback) org-occur-parameters)
12559 (let ((cnt 0))
12560 (save-excursion
12561 (goto-char (point-min))
12562 (if (or (not keep-previous) ; do not want to keep
12563 (not org-occur-highlights)) ; no previous matches
12564 ;; hide everything
12565 (org-overview))
12566 (while (re-search-forward regexp nil t)
12567 (when (or (not callback)
12568 (save-match-data (funcall callback)))
12569 (setq cnt (1+ cnt))
12570 (when org-highlight-sparse-tree-matches
12571 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12572 (org-show-context 'occur-tree))))
12573 (when org-remove-highlights-with-change
12574 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12575 nil 'local))
12576 (unless org-sparse-tree-open-archived-trees
12577 (org-hide-archived-subtrees (point-min) (point-max)))
12578 (run-hooks 'org-occur-hook)
12579 (if (org-called-interactively-p 'interactive)
12580 (message "%d match(es) for regexp %s" cnt regexp))
12581 cnt))
12583 (defun org-occur-next-match (&optional n reset)
12584 "Function for `next-error-function' to find sparse tree matches.
12585 N is the number of matches to move, when negative move backwards.
12586 RESET is entirely ignored - this function always goes back to the
12587 starting point when no match is found."
12588 (let* ((limit (if (< n 0) (point-min) (point-max)))
12589 (search-func (if (< n 0)
12590 'previous-single-char-property-change
12591 'next-single-char-property-change))
12592 (n (abs n))
12593 (pos (point))
12595 (catch 'exit
12596 (while (setq p1 (funcall search-func (point) 'org-type))
12597 (when (equal p1 limit)
12598 (goto-char pos)
12599 (error "No more matches"))
12600 (when (equal (get-char-property p1 'org-type) 'org-occur)
12601 (setq n (1- n))
12602 (when (= n 0)
12603 (goto-char p1)
12604 (throw 'exit (point))))
12605 (goto-char p1))
12606 (goto-char p1)
12607 (error "No more matches"))))
12609 (defun org-show-context (&optional key)
12610 "Make sure point and context are visible.
12611 How much context is shown depends upon the variables
12612 `org-show-hierarchy-above', `org-show-following-heading',
12613 `org-show-entry-below' and `org-show-siblings'."
12614 (let ((heading-p (org-at-heading-p t))
12615 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12616 (following-p (org-get-alist-option org-show-following-heading key))
12617 (entry-p (org-get-alist-option org-show-entry-below key))
12618 (siblings-p (org-get-alist-option org-show-siblings key)))
12619 (catch 'exit
12620 ;; Show heading or entry text
12621 (if (and heading-p (not entry-p))
12622 (org-flag-heading nil) ; only show the heading
12623 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12624 (org-show-hidden-entry))) ; show entire entry
12625 (when following-p
12626 ;; Show next sibling, or heading below text
12627 (save-excursion
12628 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12629 (org-flag-heading nil))))
12630 (when siblings-p (org-show-siblings))
12631 (when hierarchy-p
12632 ;; show all higher headings, possibly with siblings
12633 (save-excursion
12634 (while (and (condition-case nil
12635 (progn (org-up-heading-all 1) t)
12636 (error nil))
12637 (not (bobp)))
12638 (org-flag-heading nil)
12639 (when siblings-p (org-show-siblings))))))))
12641 (defvar org-reveal-start-hook nil
12642 "Hook run before revealing a location.")
12644 (defun org-reveal (&optional siblings)
12645 "Show current entry, hierarchy above it, and the following headline.
12646 This can be used to show a consistent set of context around locations
12647 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12648 not t for the search context.
12650 With optional argument SIBLINGS, on each level of the hierarchy all
12651 siblings are shown. This repairs the tree structure to what it would
12652 look like when opened with hierarchical calls to `org-cycle'.
12653 With double optional argument \\[universal-argument] \\[universal-argument], \
12654 go to the parent and show the
12655 entire tree."
12656 (interactive "P")
12657 (run-hooks 'org-reveal-start-hook)
12658 (let ((org-show-hierarchy-above t)
12659 (org-show-following-heading t)
12660 (org-show-siblings (if siblings t org-show-siblings)))
12661 (org-show-context nil))
12662 (when (equal siblings '(16))
12663 (save-excursion
12664 (when (org-up-heading-safe)
12665 (org-show-subtree)
12666 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12668 (defun org-highlight-new-match (beg end)
12669 "Highlight from BEG to END and mark the highlight is an occur headline."
12670 (let ((ov (make-overlay beg end)))
12671 (overlay-put ov 'face 'secondary-selection)
12672 (overlay-put ov 'org-type 'org-occur)
12673 (push ov org-occur-highlights)))
12675 (defun org-remove-occur-highlights (&optional beg end noremove)
12676 "Remove the occur highlights from the buffer.
12677 BEG and END are ignored. If NOREMOVE is nil, remove this function
12678 from the `before-change-functions' in the current buffer."
12679 (interactive)
12680 (unless org-inhibit-highlight-removal
12681 (mapc 'delete-overlay org-occur-highlights)
12682 (setq org-occur-highlights nil)
12683 (setq org-occur-parameters nil)
12684 (unless noremove
12685 (remove-hook 'before-change-functions
12686 'org-remove-occur-highlights 'local))))
12688 ;;;; Priorities
12690 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12691 "Regular expression matching the priority indicator.")
12693 (defvar org-remove-priority-next-time nil)
12695 (defun org-priority-up ()
12696 "Increase the priority of the current item."
12697 (interactive)
12698 (org-priority 'up))
12700 (defun org-priority-down ()
12701 "Decrease the priority of the current item."
12702 (interactive)
12703 (org-priority 'down))
12705 (defun org-priority (&optional action)
12706 "Change the priority of an item by ARG.
12707 ACTION can be `set', `up', `down', or a character."
12708 (interactive)
12709 (unless org-enable-priority-commands
12710 (error "Priority commands are disabled"))
12711 (setq action (or action 'set))
12712 (let (current new news have remove)
12713 (save-excursion
12714 (org-back-to-heading t)
12715 (if (looking-at org-priority-regexp)
12716 (setq current (string-to-char (match-string 2))
12717 have t))
12718 (cond
12719 ((eq action 'remove)
12720 (setq remove t new ?\ ))
12721 ((or (eq action 'set)
12722 (if (featurep 'xemacs) (characterp action) (integerp action)))
12723 (if (not (eq action 'set))
12724 (setq new action)
12725 (message "Priority %c-%c, SPC to remove: "
12726 org-highest-priority org-lowest-priority)
12727 (save-match-data
12728 (setq new (read-char-exclusive))))
12729 (if (and (= (upcase org-highest-priority) org-highest-priority)
12730 (= (upcase org-lowest-priority) org-lowest-priority))
12731 (setq new (upcase new)))
12732 (cond ((equal new ?\ ) (setq remove t))
12733 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12734 (error "Priority must be between `%c' and `%c'"
12735 org-highest-priority org-lowest-priority))))
12736 ((eq action 'up)
12737 (setq new (if have
12738 (1- current) ; normal cycling
12739 ;; last priority was empty
12740 (if (eq last-command this-command)
12741 org-lowest-priority ; wrap around empty to lowest
12742 ;; default
12743 (if org-priority-start-cycle-with-default
12744 org-default-priority
12745 (1- org-default-priority))))))
12746 ((eq action 'down)
12747 (setq new (if have
12748 (1+ current) ; normal cycling
12749 ;; last priority was empty
12750 (if (eq last-command this-command)
12751 org-highest-priority ; wrap around empty to highest
12752 ;; default
12753 (if org-priority-start-cycle-with-default
12754 org-default-priority
12755 (1+ org-default-priority))))))
12756 (t (error "Invalid action")))
12757 (if (or (< (upcase new) org-highest-priority)
12758 (> (upcase new) org-lowest-priority))
12759 (if (and (memq action '(up down))
12760 (not have) (not (eq last-command this-command)))
12761 ;; `new' is from default priority
12762 (error
12763 "The default can not be set, see `org-default-priority' why")
12764 ;; normal cycling: `new' is beyond highest/lowest priority
12765 ;; and is wrapped around to the empty priority
12766 (setq remove t)))
12767 (setq news (format "%c" new))
12768 (if have
12769 (if remove
12770 (replace-match "" t t nil 1)
12771 (replace-match news t t nil 2))
12772 (if remove
12773 (error "No priority cookie found in line")
12774 (let ((case-fold-search nil))
12775 (looking-at org-todo-line-regexp))
12776 (if (match-end 2)
12777 (progn
12778 (goto-char (match-end 2))
12779 (insert " [#" news "]"))
12780 (goto-char (match-beginning 3))
12781 (insert "[#" news "] "))))
12782 (org-preserve-lc (org-set-tags nil 'align)))
12783 (if remove
12784 (message "Priority removed")
12785 (message "Priority of current item set to %s" news))))
12787 (defun org-get-priority (s)
12788 "Find priority cookie and return priority."
12789 (if (functionp org-get-priority-function)
12790 (funcall org-get-priority-function)
12791 (save-match-data
12792 (if (not (string-match org-priority-regexp s))
12793 (* 1000 (- org-lowest-priority org-default-priority))
12794 (* 1000 (- org-lowest-priority
12795 (string-to-char (match-string 2 s))))))))
12797 ;;;; Tags
12799 (defvar org-agenda-archives-mode)
12800 (defvar org-map-continue-from nil
12801 "Position from where mapping should continue.
12802 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12804 (defvar org-scanner-tags nil
12805 "The current tag list while the tags scanner is running.")
12806 (defvar org-trust-scanner-tags nil
12807 "Should `org-get-tags-at' use the tags for the scanner.
12808 This is for internal dynamical scoping only.
12809 When this is non-nil, the function `org-get-tags-at' will return the value
12810 of `org-scanner-tags' instead of building the list by itself. This
12811 can lead to large speed-ups when the tags scanner is used in a file with
12812 many entries, and when the list of tags is retrieved, for example to
12813 obtain a list of properties. Building the tags list for each entry in such
12814 a file becomes an N^2 operation - but with this variable set, it scales
12815 as N.")
12817 (defun org-scan-tags (action matcher &optional todo-only start-level)
12818 "Scan headline tags with inheritance and produce output ACTION.
12820 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12821 or `agenda' to produce an entry list for an agenda view. It can also be
12822 a Lisp form or a function that should be called at each matched headline, in
12823 this case the return value is a list of all return values from these calls.
12825 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12826 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12827 only lines with a TODO keyword are included in the output.
12829 START-LEVEL can be a string with asterisks, reducing the scope to
12830 headlines matching this string."
12831 (require 'org-agenda)
12832 (let* ((re (concat "^"
12833 (if start-level
12834 ;; Get the correct level to match
12835 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12836 org-outline-regexp)
12837 " *\\(\\<\\("
12838 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12839 (org-re
12840 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12841 (props (list 'face 'default
12842 'done-face 'org-agenda-done
12843 'undone-face 'default
12844 'mouse-face 'highlight
12845 'org-not-done-regexp org-not-done-regexp
12846 'org-todo-regexp org-todo-regexp
12847 'org-complex-heading-regexp org-complex-heading-regexp
12848 'help-echo
12849 (format "mouse-2 or RET jump to org file %s"
12850 (abbreviate-file-name
12851 (or (buffer-file-name (buffer-base-buffer))
12852 (buffer-name (buffer-base-buffer)))))))
12853 (case-fold-search nil)
12854 (org-map-continue-from nil)
12855 lspos tags
12856 (tags-alist (list (cons 0 org-file-tags)))
12857 (llast 0) rtn rtn1 level category i txt
12858 todo marker entry priority)
12859 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12860 (setq action (list 'lambda nil action)))
12861 (save-excursion
12862 (goto-char (point-min))
12863 (when (eq action 'sparse-tree)
12864 (org-overview)
12865 (org-remove-occur-highlights))
12866 (while (re-search-forward re nil t)
12867 (setq org-map-continue-from nil)
12868 (catch :skip
12869 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12870 tags (if (match-end 4) (org-match-string-no-properties 4)))
12871 (goto-char (setq lspos (match-beginning 0)))
12872 (setq level (org-reduced-level (funcall outline-level))
12873 category (org-get-category))
12874 (setq i llast llast level)
12875 ;; remove tag lists from same and sublevels
12876 (while (>= i level)
12877 (when (setq entry (assoc i tags-alist))
12878 (setq tags-alist (delete entry tags-alist)))
12879 (setq i (1- i)))
12880 ;; add the next tags
12881 (when tags
12882 (setq tags (org-split-string tags ":")
12883 tags-alist
12884 (cons (cons level tags) tags-alist)))
12885 ;; compile tags for current headline
12886 (setq tags-list
12887 (if org-use-tag-inheritance
12888 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12889 tags)
12890 org-scanner-tags tags-list)
12891 (when org-use-tag-inheritance
12892 (setcdr (car tags-alist)
12893 (mapcar (lambda (x)
12894 (setq x (copy-sequence x))
12895 (org-add-prop-inherited x))
12896 (cdar tags-alist))))
12897 (when (and tags org-use-tag-inheritance
12898 (or (not (eq t org-use-tag-inheritance))
12899 org-tags-exclude-from-inheritance))
12900 ;; selective inheritance, remove uninherited ones
12901 (setcdr (car tags-alist)
12902 (org-remove-uninherited-tags (cdar tags-alist))))
12903 (when (and
12905 ;; eval matcher only when the todo condition is OK
12906 (and (or (not todo-only) (member todo org-not-done-keywords))
12907 (let ((case-fold-search t)) (eval matcher)))
12909 ;; Call the skipper, but return t if it does not skip,
12910 ;; so that the `and' form continues evaluating
12911 (progn
12912 (unless (eq action 'sparse-tree) (org-agenda-skip))
12915 ;; Check if timestamps are deselecting this entry
12916 (or (not todo-only)
12917 (and (member todo org-not-done-keywords)
12918 (or (not org-agenda-tags-todo-honor-ignore-options)
12919 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12921 ;; Extra check for the archive tag
12922 ;; FIXME: Does the skipper already do this????
12924 (not (member org-archive-tag tags-list))
12925 ;; we have an archive tag, should we use this anyway?
12926 (or (not org-agenda-skip-archived-trees)
12927 (and (eq action 'agenda) org-agenda-archives-mode))))
12929 ;; select this headline
12931 (cond
12932 ((eq action 'sparse-tree)
12933 (and org-highlight-sparse-tree-matches
12934 (org-get-heading) (match-end 0)
12935 (org-highlight-new-match
12936 (match-beginning 1) (match-end 1)))
12937 (org-show-context 'tags-tree))
12938 ((eq action 'agenda)
12939 (setq txt (org-agenda-format-item
12941 (concat
12942 (if (eq org-tags-match-list-sublevels 'indented)
12943 (make-string (1- level) ?.) "")
12944 (org-get-heading))
12945 category
12946 tags-list)
12947 priority (org-get-priority txt))
12948 (goto-char lspos)
12949 (setq marker (org-agenda-new-marker))
12950 (org-add-props txt props
12951 'org-marker marker 'org-hd-marker marker 'org-category category
12952 'todo-state todo
12953 'priority priority 'type "tagsmatch")
12954 (push txt rtn))
12955 ((functionp action)
12956 (setq org-map-continue-from nil)
12957 (save-excursion
12958 (setq rtn1 (funcall action))
12959 (push rtn1 rtn)))
12960 (t (error "Invalid action")))
12962 ;; if we are to skip sublevels, jump to end of subtree
12963 (unless org-tags-match-list-sublevels
12964 (org-end-of-subtree t)
12965 (backward-char 1))))
12966 ;; Get the correct position from where to continue
12967 (if org-map-continue-from
12968 (goto-char org-map-continue-from)
12969 (and (= (point) lspos) (end-of-line 1)))))
12970 (when (and (eq action 'sparse-tree)
12971 (not org-sparse-tree-open-archived-trees))
12972 (org-hide-archived-subtrees (point-min) (point-max)))
12973 (nreverse rtn)))
12975 (defun org-remove-uninherited-tags (tags)
12976 "Remove all tags that are not inherited from the list TAGS."
12977 (cond
12978 ((eq org-use-tag-inheritance t)
12979 (if org-tags-exclude-from-inheritance
12980 (org-delete-all org-tags-exclude-from-inheritance tags)
12981 tags))
12982 ((not org-use-tag-inheritance) nil)
12983 ((stringp org-use-tag-inheritance)
12984 (delq nil (mapcar
12985 (lambda (x)
12986 (if (and (string-match org-use-tag-inheritance x)
12987 (not (member x org-tags-exclude-from-inheritance)))
12988 x nil))
12989 tags)))
12990 ((listp org-use-tag-inheritance)
12991 (delq nil (mapcar
12992 (lambda (x)
12993 (if (member x org-use-tag-inheritance) x nil))
12994 tags)))))
12996 (defvar todo-only) ;; dynamically scoped
12998 (defun org-match-sparse-tree (&optional todo-only match)
12999 "Create a sparse tree according to tags string MATCH.
13000 MATCH can contain positive and negative selection of tags, like
13001 \"+WORK+URGENT-WITHBOSS\".
13002 If optional argument TODO-ONLY is non-nil, only select lines that are
13003 also TODO lines."
13004 (interactive "P")
13005 (org-prepare-agenda-buffers (list (current-buffer)))
13006 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13008 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13010 (defvar org-cached-props nil)
13011 (defun org-cached-entry-get (pom property)
13012 (if (or (eq t org-use-property-inheritance)
13013 (and (stringp org-use-property-inheritance)
13014 (string-match org-use-property-inheritance property))
13015 (and (listp org-use-property-inheritance)
13016 (member property org-use-property-inheritance)))
13017 ;; Caching is not possible, check it directly
13018 (org-entry-get pom property 'inherit)
13019 ;; Get all properties, so that we can do complicated checks easily
13020 (cdr (assoc property (or org-cached-props
13021 (setq org-cached-props
13022 (org-entry-properties pom)))))))
13024 (defun org-global-tags-completion-table (&optional files)
13025 "Return the list of all tags in all agenda buffer/files.
13026 Optional FILES argument is a list of files to which can be used
13027 instead of the agenda files."
13028 (save-excursion
13029 (org-uniquify
13030 (delq nil
13031 (apply 'append
13032 (mapcar
13033 (lambda (file)
13034 (set-buffer (find-file-noselect file))
13035 (append (org-get-buffer-tags)
13036 (mapcar (lambda (x) (if (stringp (car-safe x))
13037 (list (car-safe x)) nil))
13038 org-tag-alist)))
13039 (if (and files (car files))
13040 files
13041 (org-agenda-files))))))))
13043 (defun org-make-tags-matcher (match)
13044 "Create the TAGS/TODO matcher form for the selection string MATCH."
13045 ;; todo-only is scoped dynamically into this function, and the function
13046 ;; may change it if the matcher asks for it.
13047 (unless match
13048 ;; Get a new match request, with completion
13049 (let ((org-last-tags-completion-table
13050 (org-global-tags-completion-table)))
13051 (setq match (org-completing-read-no-i
13052 "Match: " 'org-tags-completion-function nil nil nil
13053 'org-tags-history))))
13055 ;; Parse the string and create a lisp form
13056 (let ((match0 match)
13057 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13058 minus tag mm
13059 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13060 orterms term orlist re-p str-p level-p level-op time-p
13061 prop-p pn pv po gv rest)
13062 (if (string-match "/+" match)
13063 ;; match contains also a todo-matching request
13064 (progn
13065 (setq tagsmatch (substring match 0 (match-beginning 0))
13066 todomatch (substring match (match-end 0)))
13067 (if (string-match "^!" todomatch)
13068 (setq todo-only t todomatch (substring todomatch 1)))
13069 (if (string-match "^\\s-*$" todomatch)
13070 (setq todomatch nil)))
13071 ;; only matching tags
13072 (setq tagsmatch match todomatch nil))
13074 ;; Make the tags matcher
13075 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13076 (setq tagsmatcher t)
13077 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13078 (while (setq term (pop orterms))
13079 (while (and (equal (substring term -1) "\\") orterms)
13080 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13081 (while (string-match re term)
13082 (setq rest (substring term (match-end 0))
13083 minus (and (match-end 1)
13084 (equal (match-string 1 term) "-"))
13085 tag (save-match-data (replace-regexp-in-string
13086 "\\\\-" "-"
13087 (match-string 2 term)))
13088 re-p (equal (string-to-char tag) ?{)
13089 level-p (match-end 4)
13090 prop-p (match-end 5)
13091 mm (cond
13092 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13093 (level-p
13094 (setq level-op (org-op-to-function (match-string 3 term)))
13095 `(,level-op level ,(string-to-number
13096 (match-string 4 term))))
13097 (prop-p
13098 (setq pn (match-string 5 term)
13099 po (match-string 6 term)
13100 pv (match-string 7 term)
13101 re-p (equal (string-to-char pv) ?{)
13102 str-p (equal (string-to-char pv) ?\")
13103 time-p (save-match-data
13104 (string-match "^\"[[<].*[]>]\"$" pv))
13105 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13106 (if time-p (setq pv (org-matcher-time pv)))
13107 (setq po (org-op-to-function po (if time-p 'time str-p)))
13108 (cond
13109 ((equal pn "CATEGORY")
13110 (setq gv '(get-text-property (point) 'org-category)))
13111 ((equal pn "TODO")
13112 (setq gv 'todo))
13114 (setq gv `(org-cached-entry-get nil ,pn))))
13115 (if re-p
13116 (if (eq po 'org<>)
13117 `(not (string-match ,pv (or ,gv "")))
13118 `(string-match ,pv (or ,gv "")))
13119 (if str-p
13120 `(,po (or ,gv "") ,pv)
13121 `(,po (string-to-number (or ,gv ""))
13122 ,(string-to-number pv) ))))
13123 (t `(member ,tag tags-list)))
13124 mm (if minus (list 'not mm) mm)
13125 term rest)
13126 (push mm tagsmatcher))
13127 (push (if (> (length tagsmatcher) 1)
13128 (cons 'and tagsmatcher)
13129 (car tagsmatcher))
13130 orlist)
13131 (setq tagsmatcher nil))
13132 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13133 (setq tagsmatcher
13134 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13135 ;; Make the todo matcher
13136 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13137 (setq todomatcher t)
13138 (setq orterms (org-split-string todomatch "|") orlist nil)
13139 (while (setq term (pop orterms))
13140 (while (string-match re term)
13141 (setq minus (and (match-end 1)
13142 (equal (match-string 1 term) "-"))
13143 kwd (match-string 2 term)
13144 re-p (equal (string-to-char kwd) ?{)
13145 term (substring term (match-end 0))
13146 mm (if re-p
13147 `(string-match ,(substring kwd 1 -1) todo)
13148 (list 'equal 'todo kwd))
13149 mm (if minus (list 'not mm) mm))
13150 (push mm todomatcher))
13151 (push (if (> (length todomatcher) 1)
13152 (cons 'and todomatcher)
13153 (car todomatcher))
13154 orlist)
13155 (setq todomatcher nil))
13156 (setq todomatcher (if (> (length orlist) 1)
13157 (cons 'or orlist) (car orlist))))
13159 ;; Return the string and lisp forms of the matcher
13160 (setq matcher (if todomatcher
13161 (list 'and tagsmatcher todomatcher)
13162 tagsmatcher))
13163 (cons match0 matcher)))
13165 (defun org-op-to-function (op &optional stringp)
13166 "Turn an operator into the appropriate function."
13167 (setq op
13168 (cond
13169 ((equal op "<" ) '(< string< org-time<))
13170 ((equal op ">" ) '(> org-string> org-time>))
13171 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13172 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13173 ((member op '("=" "==")) '(= string= org-time=))
13174 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13175 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13177 (defun org<> (a b) (not (= a b)))
13178 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13179 (defun org-string>= (a b) (not (string< a b)))
13180 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13181 (defun org-string<> (a b) (not (string= a b)))
13182 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13183 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13184 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13185 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13186 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13187 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13188 (defun org-2ft (s)
13189 "Convert S to a floating point time.
13190 If S is already a number, just return it. If it is a string, parse
13191 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13192 (cond
13193 ((numberp s) s)
13194 ((stringp s)
13195 (condition-case nil
13196 (float-time (apply 'encode-time (org-parse-time-string s)))
13197 (error 0.)))
13198 (t 0.)))
13200 (defun org-time-today ()
13201 "Time in seconds today at 0:00.
13202 Returns the float number of seconds since the beginning of the
13203 epoch to the beginning of today (00:00)."
13204 (float-time (apply 'encode-time
13205 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13207 (defun org-matcher-time (s)
13208 "Interpret a time comparison value."
13209 (save-match-data
13210 (cond
13211 ((string= s "<now>") (float-time))
13212 ((string= s "<today>") (org-time-today))
13213 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13214 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13215 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13216 (+ (org-time-today)
13217 (* (string-to-number (match-string 1 s))
13218 (cdr (assoc (match-string 2 s)
13219 '(("d" . 86400.0) ("w" . 604800.0)
13220 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13221 (t (org-2ft s)))))
13223 (defun org-match-any-p (re list)
13224 "Does re match any element of list?"
13225 (setq list (mapcar (lambda (x) (string-match re x)) list))
13226 (delq nil list))
13228 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13229 (defvar org-tags-overlay (make-overlay 1 1))
13230 (org-detach-overlay org-tags-overlay)
13232 (defun org-get-local-tags-at (&optional pos)
13233 "Get a list of tags defined in the current headline."
13234 (org-get-tags-at pos 'local))
13236 (defun org-get-local-tags ()
13237 "Get a list of tags defined in the current headline."
13238 (org-get-tags-at nil 'local))
13240 (defun org-get-tags-at (&optional pos local)
13241 "Get a list of all headline tags applicable at POS.
13242 POS defaults to point. If tags are inherited, the list contains
13243 the targets in the same sequence as the headlines appear, i.e.
13244 the tags of the current headline come last.
13245 When LOCAL is non-nil, only return tags from the current headline,
13246 ignore inherited ones."
13247 (interactive)
13248 (if (and org-trust-scanner-tags
13249 (or (not pos) (equal pos (point)))
13250 (not local))
13251 org-scanner-tags
13252 (let (tags ltags lastpos parent)
13253 (save-excursion
13254 (save-restriction
13255 (widen)
13256 (goto-char (or pos (point)))
13257 (save-match-data
13258 (catch 'done
13259 (condition-case nil
13260 (progn
13261 (org-back-to-heading t)
13262 (while (not (equal lastpos (point)))
13263 (setq lastpos (point))
13264 (when (looking-at
13265 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13266 (setq ltags (org-split-string
13267 (org-match-string-no-properties 1) ":"))
13268 (when parent
13269 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13270 (setq tags (append
13271 (if parent
13272 (org-remove-uninherited-tags ltags)
13273 ltags)
13274 tags)))
13275 (or org-use-tag-inheritance (throw 'done t))
13276 (if local (throw 'done t))
13277 (or (org-up-heading-safe) (error nil))
13278 (setq parent t)))
13279 (error nil)))))
13280 (if local
13281 tags
13282 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13284 (defun org-add-prop-inherited (s)
13285 (add-text-properties 0 (length s) '(inherited t) s)
13288 (defun org-toggle-tag (tag &optional onoff)
13289 "Toggle the tag TAG for the current line.
13290 If ONOFF is `on' or `off', don't toggle but set to this state."
13291 (let (res current)
13292 (save-excursion
13293 (org-back-to-heading t)
13294 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13295 (point-at-eol) t)
13296 (progn
13297 (setq current (match-string 1))
13298 (replace-match ""))
13299 (setq current ""))
13300 (setq current (nreverse (org-split-string current ":")))
13301 (cond
13302 ((eq onoff 'on)
13303 (setq res t)
13304 (or (member tag current) (push tag current)))
13305 ((eq onoff 'off)
13306 (or (not (member tag current)) (setq current (delete tag current))))
13307 (t (if (member tag current)
13308 (setq current (delete tag current))
13309 (setq res t)
13310 (push tag current))))
13311 (end-of-line 1)
13312 (if current
13313 (progn
13314 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13315 (org-set-tags nil t))
13316 (delete-horizontal-space))
13317 (run-hooks 'org-after-tags-change-hook))
13318 res))
13320 (defun org-align-tags-here (to-col)
13321 ;; Assumes that this is a headline
13322 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13323 (beginning-of-line 1)
13324 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13325 (< pos (match-beginning 2)))
13326 (progn
13327 (setq tags-l (- (match-end 2) (match-beginning 2)))
13328 (goto-char (match-beginning 1))
13329 (insert " ")
13330 (delete-region (point) (1+ (match-beginning 2)))
13331 (setq ncol (max (current-column)
13332 (1+ col)
13333 (if (> to-col 0)
13334 to-col
13335 (- (abs to-col) tags-l))))
13336 (setq p (point))
13337 (insert (make-string (- ncol (current-column)) ?\ ))
13338 (setq ncol (current-column))
13339 (when indent-tabs-mode (tabify p (point-at-eol)))
13340 (org-move-to-column (min ncol col) t))
13341 (goto-char pos))))
13343 (defun org-set-tags-command (&optional arg just-align)
13344 "Call the set-tags command for the current entry."
13345 (interactive "P")
13346 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13347 (org-set-tags arg just-align)
13348 (save-excursion
13349 (org-back-to-heading t)
13350 (org-set-tags arg just-align))))
13352 (defun org-set-tags-to (data)
13353 "Set the tags of the current entry to DATA, replacing the current tags.
13354 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13355 If DATA is nil or the empty string, any tags will be removed."
13356 (interactive "sTags: ")
13357 (setq data
13358 (cond
13359 ((eq data nil) "")
13360 ((equal data "") "")
13361 ((stringp data)
13362 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13363 ":"))
13364 ((listp data)
13365 (concat ":" (mapconcat 'identity data ":") ":"))
13366 (t nil)))
13367 (when data
13368 (save-excursion
13369 (org-back-to-heading t)
13370 (when (looking-at org-complex-heading-regexp)
13371 (if (match-end 5)
13372 (progn
13373 (goto-char (match-beginning 5))
13374 (insert data)
13375 (delete-region (point) (point-at-eol))
13376 (org-set-tags nil 'align))
13377 (goto-char (point-at-eol))
13378 (insert " " data)
13379 (org-set-tags nil 'align)))
13380 (beginning-of-line 1)
13381 (if (looking-at ".*?\\([ \t]+\\)$")
13382 (delete-region (match-beginning 1) (match-end 1))))))
13384 (defun org-align-all-tags ()
13385 "Align the tags i all headings."
13386 (interactive)
13387 (save-excursion
13388 (or (ignore-errors (org-back-to-heading t))
13389 (outline-next-heading))
13390 (if (org-at-heading-p)
13391 (org-set-tags t)
13392 (message "No headings"))))
13394 (defvar org-indent-indentation-per-level)
13395 (defun org-set-tags (&optional arg just-align)
13396 "Set the tags for the current headline.
13397 With prefix ARG, realign all tags in headings in the current buffer."
13398 (interactive "P")
13399 (let* ((re org-outline-regexp-bol)
13400 (current (unless arg (org-get-tags-string)))
13401 (col (current-column))
13402 (org-setting-tags t)
13403 table current-tags inherited-tags ; computed below when needed
13404 tags p0 c0 c1 rpl di tc level)
13405 (if arg
13406 (save-excursion
13407 (goto-char (point-min))
13408 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13409 (while (re-search-forward re nil t)
13410 (org-set-tags nil t)
13411 (end-of-line 1)))
13412 (message "All tags realigned to column %d" org-tags-column))
13413 (if just-align
13414 (setq tags current)
13415 ;; Get a new set of tags from the user
13416 (save-excursion
13417 (setq table (append org-tag-persistent-alist
13418 (or org-tag-alist (org-get-buffer-tags))
13419 (and
13420 org-complete-tags-always-offer-all-agenda-tags
13421 (org-global-tags-completion-table
13422 (org-agenda-files))))
13423 org-last-tags-completion-table table
13424 current-tags (org-split-string current ":")
13425 inherited-tags (nreverse
13426 (nthcdr (length current-tags)
13427 (nreverse (org-get-tags-at))))
13428 tags
13429 (if (or (eq t org-use-fast-tag-selection)
13430 (and org-use-fast-tag-selection
13431 (delq nil (mapcar 'cdr table))))
13432 (org-fast-tag-selection
13433 current-tags inherited-tags table
13434 (if org-fast-tag-selection-include-todo
13435 org-todo-key-alist))
13436 (let ((org-add-colon-after-tag-completion t))
13437 (org-trim
13438 (org-icompleting-read "Tags: "
13439 'org-tags-completion-function
13440 nil nil current 'org-tags-history))))))
13441 (while (string-match "[-+&]+" tags)
13442 ;; No boolean logic, just a list
13443 (setq tags (replace-match ":" t t tags))))
13445 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13447 (if org-tags-sort-function
13448 (setq tags (mapconcat 'identity
13449 (sort (org-split-string
13450 tags (org-re "[^[:alnum:]_@#%]+"))
13451 org-tags-sort-function) ":")))
13453 (if (string-match "\\`[\t ]*\\'" tags)
13454 (setq tags "")
13455 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13456 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13458 ;; Insert new tags at the correct column
13459 (beginning-of-line 1)
13460 (setq level (or (and (looking-at org-outline-regexp)
13461 (- (match-end 0) (point) 1))
13463 (cond
13464 ((and (equal current "") (equal tags "")))
13465 ((re-search-forward
13466 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13467 (point-at-eol) t)
13468 (if (equal tags "")
13469 (setq rpl "")
13470 (goto-char (match-beginning 0))
13471 (setq c0 (current-column)
13472 ;; compute offset for the case of org-indent-mode active
13473 di (if org-indent-mode
13474 (* (1- org-indent-indentation-per-level) (1- level))
13476 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13477 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13478 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13479 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13480 (replace-match rpl t t)
13481 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13482 tags)
13483 (t (error "Tags alignment failed")))
13484 (org-move-to-column col)
13485 (unless just-align
13486 (run-hooks 'org-after-tags-change-hook)))))
13488 (defun org-change-tag-in-region (beg end tag off)
13489 "Add or remove TAG for each entry in the region.
13490 This works in the agenda, and also in an org-mode buffer."
13491 (interactive
13492 (list (region-beginning) (region-end)
13493 (let ((org-last-tags-completion-table
13494 (if (eq major-mode 'org-mode)
13495 (org-get-buffer-tags)
13496 (org-global-tags-completion-table))))
13497 (org-icompleting-read
13498 "Tag: " 'org-tags-completion-function nil nil nil
13499 'org-tags-history))
13500 (progn
13501 (message "[s]et or [r]emove? ")
13502 (equal (read-char-exclusive) ?r))))
13503 (if (fboundp 'deactivate-mark) (deactivate-mark))
13504 (let ((agendap (equal major-mode 'org-agenda-mode))
13505 l1 l2 m buf pos newhead (cnt 0))
13506 (goto-char end)
13507 (setq l2 (1- (org-current-line)))
13508 (goto-char beg)
13509 (setq l1 (org-current-line))
13510 (loop for l from l1 to l2 do
13511 (org-goto-line l)
13512 (setq m (get-text-property (point) 'org-hd-marker))
13513 (when (or (and (eq major-mode 'org-mode) (org-at-heading-p))
13514 (and agendap m))
13515 (setq buf (if agendap (marker-buffer m) (current-buffer))
13516 pos (if agendap m (point)))
13517 (with-current-buffer buf
13518 (save-excursion
13519 (save-restriction
13520 (goto-char pos)
13521 (setq cnt (1+ cnt))
13522 (org-toggle-tag tag (if off 'off 'on))
13523 (setq newhead (org-get-heading)))))
13524 (and agendap (org-agenda-change-all-lines newhead m))))
13525 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13527 (defun org-tags-completion-function (string predicate &optional flag)
13528 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13529 (confirm (lambda (x) (stringp (car x)))))
13530 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13531 (setq s1 (match-string 1 string)
13532 s2 (match-string 2 string))
13533 (setq s1 "" s2 string))
13534 (cond
13535 ((eq flag nil)
13536 ;; try completion
13537 (setq rtn (try-completion s2 ctable confirm))
13538 (if (stringp rtn)
13539 (setq rtn
13540 (concat s1 s2 (substring rtn (length s2))
13541 (if (and org-add-colon-after-tag-completion
13542 (assoc rtn ctable))
13543 ":" ""))))
13544 rtn)
13545 ((eq flag t)
13546 ;; all-completions
13547 (all-completions s2 ctable confirm)
13549 ((eq flag 'lambda)
13550 ;; exact match?
13551 (assoc s2 ctable)))
13554 (defun org-fast-tag-insert (kwd tags face &optional end)
13555 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13556 (insert (format "%-12s" (concat kwd ":"))
13557 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13558 (or end "")))
13560 (defun org-fast-tag-show-exit (flag)
13561 (save-excursion
13562 (org-goto-line 3)
13563 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13564 (replace-match ""))
13565 (when flag
13566 (end-of-line 1)
13567 (org-move-to-column (- (window-width) 19) t)
13568 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13570 (defun org-set-current-tags-overlay (current prefix)
13571 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13572 (if (featurep 'xemacs)
13573 (org-overlay-display org-tags-overlay (concat prefix s)
13574 'secondary-selection)
13575 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13576 (org-overlay-display org-tags-overlay (concat prefix s)))))
13578 (defvar org-last-tag-selection-key nil)
13579 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13580 "Fast tag selection with single keys.
13581 CURRENT is the current list of tags in the headline, INHERITED is the
13582 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13583 possibly with grouping information. TODO-TABLE is a similar table with
13584 TODO keywords, should these have keys assigned to them.
13585 If the keys are nil, a-z are automatically assigned.
13586 Returns the new tags string, or nil to not change the current settings."
13587 (let* ((fulltable (append table todo-table))
13588 (maxlen (apply 'max (mapcar
13589 (lambda (x)
13590 (if (stringp (car x)) (string-width (car x)) 0))
13591 fulltable)))
13592 (buf (current-buffer))
13593 (expert (eq org-fast-tag-selection-single-key 'expert))
13594 (buffer-tags nil)
13595 (fwidth (+ maxlen 3 1 3))
13596 (ncol (/ (- (window-width) 4) fwidth))
13597 (i-face 'org-done)
13598 (c-face 'org-todo)
13599 tg cnt e c char c1 c2 ntable tbl rtn
13600 ov-start ov-end ov-prefix
13601 (exit-after-next org-fast-tag-selection-single-key)
13602 (done-keywords org-done-keywords)
13603 groups ingroup)
13604 (save-excursion
13605 (beginning-of-line 1)
13606 (if (looking-at
13607 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13608 (setq ov-start (match-beginning 1)
13609 ov-end (match-end 1)
13610 ov-prefix "")
13611 (setq ov-start (1- (point-at-eol))
13612 ov-end (1+ ov-start))
13613 (skip-chars-forward "^\n\r")
13614 (setq ov-prefix
13615 (concat
13616 (buffer-substring (1- (point)) (point))
13617 (if (> (current-column) org-tags-column)
13619 (make-string (- org-tags-column (current-column)) ?\ ))))))
13620 (move-overlay org-tags-overlay ov-start ov-end)
13621 (save-window-excursion
13622 (if expert
13623 (set-buffer (get-buffer-create " *Org tags*"))
13624 (delete-other-windows)
13625 (split-window-vertically)
13626 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13627 (erase-buffer)
13628 (org-set-local 'org-done-keywords done-keywords)
13629 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13630 (org-fast-tag-insert "Current" current c-face "\n\n")
13631 (org-fast-tag-show-exit exit-after-next)
13632 (org-set-current-tags-overlay current ov-prefix)
13633 (setq tbl fulltable char ?a cnt 0)
13634 (while (setq e (pop tbl))
13635 (cond
13636 ((equal (car e) :startgroup)
13637 (push '() groups) (setq ingroup t)
13638 (when (not (= cnt 0))
13639 (setq cnt 0)
13640 (insert "\n"))
13641 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13642 ((equal (car e) :endgroup)
13643 (setq ingroup nil cnt 0)
13644 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13645 ((equal e '(:newline))
13646 (when (not (= cnt 0))
13647 (setq cnt 0)
13648 (insert "\n")
13649 (setq e (car tbl))
13650 (while (equal (car tbl) '(:newline))
13651 (insert "\n")
13652 (setq tbl (cdr tbl)))))
13654 (setq tg (copy-sequence (car e)) c2 nil)
13655 (if (cdr e)
13656 (setq c (cdr e))
13657 ;; automatically assign a character.
13658 (setq c1 (string-to-char
13659 (downcase (substring
13660 tg (if (= (string-to-char tg) ?@) 1 0)))))
13661 (if (or (rassoc c1 ntable) (rassoc c1 table))
13662 (while (or (rassoc char ntable) (rassoc char table))
13663 (setq char (1+ char)))
13664 (setq c2 c1))
13665 (setq c (or c2 char)))
13666 (if ingroup (push tg (car groups)))
13667 (setq tg (org-add-props tg nil 'face
13668 (cond
13669 ((not (assoc tg table))
13670 (org-get-todo-face tg))
13671 ((member tg current) c-face)
13672 ((member tg inherited) i-face)
13673 (t nil))))
13674 (if (and (= cnt 0) (not ingroup)) (insert " "))
13675 (insert "[" c "] " tg (make-string
13676 (- fwidth 4 (length tg)) ?\ ))
13677 (push (cons tg c) ntable)
13678 (when (= (setq cnt (1+ cnt)) ncol)
13679 (insert "\n")
13680 (if ingroup (insert " "))
13681 (setq cnt 0)))))
13682 (setq ntable (nreverse ntable))
13683 (insert "\n")
13684 (goto-char (point-min))
13685 (if (not expert) (org-fit-window-to-buffer))
13686 (setq rtn
13687 (catch 'exit
13688 (while t
13689 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13690 (if (not groups) "no " "")
13691 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13692 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13693 (setq org-last-tag-selection-key c)
13694 (cond
13695 ((= c ?\r) (throw 'exit t))
13696 ((= c ?!)
13697 (setq groups (not groups))
13698 (goto-char (point-min))
13699 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13700 ((= c ?\C-c)
13701 (if (not expert)
13702 (org-fast-tag-show-exit
13703 (setq exit-after-next (not exit-after-next)))
13704 (setq expert nil)
13705 (delete-other-windows)
13706 (set-window-buffer (split-window-vertically) " *Org tags*")
13707 (org-switch-to-buffer-other-window " *Org tags*")
13708 (org-fit-window-to-buffer)))
13709 ((or (= c ?\C-g)
13710 (and (= c ?q) (not (rassoc c ntable))))
13711 (org-detach-overlay org-tags-overlay)
13712 (setq quit-flag t))
13713 ((= c ?\ )
13714 (setq current nil)
13715 (if exit-after-next (setq exit-after-next 'now)))
13716 ((= c ?\t)
13717 (condition-case nil
13718 (setq tg (org-icompleting-read
13719 "Tag: "
13720 (or buffer-tags
13721 (with-current-buffer buf
13722 (org-get-buffer-tags)))))
13723 (quit (setq tg "")))
13724 (when (string-match "\\S-" tg)
13725 (add-to-list 'buffer-tags (list tg))
13726 (if (member tg current)
13727 (setq current (delete tg current))
13728 (push tg current)))
13729 (if exit-after-next (setq exit-after-next 'now)))
13730 ((setq e (rassoc c todo-table) tg (car e))
13731 (with-current-buffer buf
13732 (save-excursion (org-todo tg)))
13733 (if exit-after-next (setq exit-after-next 'now)))
13734 ((setq e (rassoc c ntable) tg (car e))
13735 (if (member tg current)
13736 (setq current (delete tg current))
13737 (loop for g in groups do
13738 (if (member tg g)
13739 (mapc (lambda (x)
13740 (setq current (delete x current)))
13741 g)))
13742 (push tg current))
13743 (if exit-after-next (setq exit-after-next 'now))))
13745 ;; Create a sorted list
13746 (setq current
13747 (sort current
13748 (lambda (a b)
13749 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13750 (if (eq exit-after-next 'now) (throw 'exit t))
13751 (goto-char (point-min))
13752 (beginning-of-line 2)
13753 (delete-region (point) (point-at-eol))
13754 (org-fast-tag-insert "Current" current c-face)
13755 (org-set-current-tags-overlay current ov-prefix)
13756 (while (re-search-forward
13757 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13758 (setq tg (match-string 1))
13759 (add-text-properties
13760 (match-beginning 1) (match-end 1)
13761 (list 'face
13762 (cond
13763 ((member tg current) c-face)
13764 ((member tg inherited) i-face)
13765 (t (get-text-property (match-beginning 1) 'face))))))
13766 (goto-char (point-min)))))
13767 (org-detach-overlay org-tags-overlay)
13768 (if rtn
13769 (mapconcat 'identity current ":")
13770 nil))))
13772 (defun org-get-tags-string ()
13773 "Get the TAGS string in the current headline."
13774 (unless (org-at-heading-p t)
13775 (error "Not on a heading"))
13776 (save-excursion
13777 (beginning-of-line 1)
13778 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13779 (org-match-string-no-properties 1)
13780 "")))
13782 (defun org-get-tags ()
13783 "Get the list of tags specified in the current headline."
13784 (org-split-string (org-get-tags-string) ":"))
13786 (defun org-get-buffer-tags ()
13787 "Get a table of all tags used in the buffer, for completion."
13788 (let (tags)
13789 (save-excursion
13790 (goto-char (point-min))
13791 (while (re-search-forward
13792 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13793 (when (equal (char-after (point-at-bol 0)) ?*)
13794 (mapc (lambda (x) (add-to-list 'tags x))
13795 (org-split-string (org-match-string-no-properties 1) ":")))))
13796 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13797 (mapcar 'list tags)))
13799 ;;;; The mapping API
13801 ;;;###autoload
13802 (defun org-map-entries (func &optional match scope &rest skip)
13803 "Call FUNC at each headline selected by MATCH in SCOPE.
13805 FUNC is a function or a lisp form. The function will be called without
13806 arguments, with the cursor positioned at the beginning of the headline.
13807 The return values of all calls to the function will be collected and
13808 returned as a list.
13810 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13811 does not need to preserve point. After evaluation, the cursor will be
13812 moved to the end of the line (presumably of the headline of the
13813 processed entry) and search continues from there. Under some
13814 circumstances, this may not produce the wanted results. For example,
13815 if you have removed (e.g. archived) the current (sub)tree it could
13816 mean that the next entry will be skipped entirely. In such cases, you
13817 can specify the position from where search should continue by making
13818 FUNC set the variable `org-map-continue-from' to the desired buffer
13819 position.
13821 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13822 Only headlines that are matched by this query will be considered during
13823 the iteration. When MATCH is nil or t, all headlines will be
13824 visited by the iteration.
13826 SCOPE determines the scope of this command. It can be any of:
13828 nil The current buffer, respecting the restriction if any
13829 tree The subtree started with the entry at point
13830 region The entries within the active region, if any
13831 region-start-level
13832 The entries within the active region, but only those at
13833 the same level than the first one.
13834 file The current buffer, without restriction
13835 file-with-archives
13836 The current buffer, and any archives associated with it
13837 agenda All agenda files
13838 agenda-with-archives
13839 All agenda files with any archive files associated with them
13840 \(file1 file2 ...)
13841 If this is a list, all files in the list will be scanned
13843 The remaining args are treated as settings for the skipping facilities of
13844 the scanner. The following items can be given here:
13846 archive skip trees with the archive tag.
13847 comment skip trees with the COMMENT keyword
13848 function or Emacs Lisp form:
13849 will be used as value for `org-agenda-skip-function', so whenever
13850 the function returns t, FUNC will not be called for that
13851 entry and search will continue from the point where the
13852 function leaves it.
13854 If your function needs to retrieve the tags including inherited tags
13855 at the *current* entry, you can use the value of the variable
13856 `org-scanner-tags' which will be much faster than getting the value
13857 with `org-get-tags-at'. If your function gets properties with
13858 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13859 to t around the call to `org-entry-properties' to get the same speedup.
13860 Note that if your function moves around to retrieve tags and properties at
13861 a *different* entry, you cannot use these techniques."
13862 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13863 (not (org-region-active-p)))
13864 (let* ((org-agenda-archives-mode nil) ; just to make sure
13865 (org-agenda-skip-archived-trees (memq 'archive skip))
13866 (org-agenda-skip-comment-trees (memq 'comment skip))
13867 (org-agenda-skip-function
13868 (car (org-delete-all '(comment archive) skip)))
13869 (org-tags-match-list-sublevels t)
13870 (start-level (eq scope 'region-start-level))
13871 matcher file res
13872 org-todo-keywords-for-agenda
13873 org-done-keywords-for-agenda
13874 org-todo-keyword-alist-for-agenda
13875 org-drawers-for-agenda
13876 org-tag-alist-for-agenda)
13878 (cond
13879 ((eq match t) (setq matcher t))
13880 ((eq match nil) (setq matcher t))
13881 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13883 (save-excursion
13884 (save-restriction
13885 (cond ((eq scope 'tree)
13886 (org-back-to-heading t)
13887 (org-narrow-to-subtree)
13888 (setq scope nil))
13889 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13890 (org-region-active-p))
13891 ;; If needed, set start-level to a string like "2"
13892 (when start-level
13893 (save-excursion
13894 (goto-char (region-beginning))
13895 (unless (org-at-heading-p) (outline-next-heading))
13896 (setq start-level (org-current-level))))
13897 (narrow-to-region (region-beginning)
13898 (save-excursion
13899 (goto-char (region-end))
13900 (unless (and (bolp) (org-at-heading-p))
13901 (outline-next-heading))
13902 (point)))
13903 (setq scope nil)))
13905 (if (not scope)
13906 (progn
13907 (org-prepare-agenda-buffers
13908 (list (buffer-file-name (current-buffer))))
13909 (setq res (org-scan-tags func matcher nil start-level)))
13910 ;; Get the right scope
13911 (cond
13912 ((and scope (listp scope) (symbolp (car scope)))
13913 (setq scope (eval scope)))
13914 ((eq scope 'agenda)
13915 (setq scope (org-agenda-files t)))
13916 ((eq scope 'agenda-with-archives)
13917 (setq scope (org-agenda-files t))
13918 (setq scope (org-add-archive-files scope)))
13919 ((eq scope 'file)
13920 (setq scope (list (buffer-file-name))))
13921 ((eq scope 'file-with-archives)
13922 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13923 (org-prepare-agenda-buffers scope)
13924 (while (setq file (pop scope))
13925 (with-current-buffer (org-find-base-buffer-visiting file)
13926 (save-excursion
13927 (save-restriction
13928 (widen)
13929 (goto-char (point-min))
13930 (setq res (append res (org-scan-tags func matcher))))))))))
13931 res)))
13933 ;;;; Properties
13935 ;;; Setting and retrieving properties
13937 (defconst org-special-properties
13938 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13939 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13940 "The special properties valid in Org-mode.
13942 These are properties that are not defined in the property drawer,
13943 but in some other way.")
13945 (defconst org-default-properties
13946 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13947 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13948 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13949 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13950 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13951 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13952 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13953 "Some properties that are used by Org-mode for various purposes.
13954 Being in this list makes sure that they are offered for completion.")
13956 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13957 "Regular expression matching the first line of a property drawer.")
13959 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13960 "Regular expression matching the last line of a property drawer.")
13962 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13963 "Regular expression matching the first line of a property drawer.")
13965 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13966 "Regular expression matching the first line of a property drawer.")
13968 (defconst org-property-drawer-re
13969 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13970 org-property-end-re "\\)\n?")
13971 "Matches an entire property drawer.")
13973 (defconst org-clock-drawer-re
13974 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13975 org-property-end-re "\\)\n?")
13976 "Matches an entire clock drawer.")
13978 (defsubst org-re-property (property)
13979 "Return a regexp matching PROPERTY.
13980 Match group 1 will be set to the value "
13981 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13983 (defun org-property-action ()
13984 "Do an action on properties."
13985 (interactive)
13986 (let (c)
13987 (org-at-property-p)
13988 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13989 (setq c (read-char-exclusive))
13990 (cond
13991 ((equal c ?s)
13992 (call-interactively 'org-set-property))
13993 ((equal c ?d)
13994 (call-interactively 'org-delete-property))
13995 ((equal c ?D)
13996 (call-interactively 'org-delete-property-globally))
13997 ((equal c ?c)
13998 (call-interactively 'org-compute-property-at-point))
13999 (t (error "No such property action %c" c)))))
14001 (defun org-set-effort (&optional value)
14002 "Set the effort property of the current entry.
14003 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14004 allowed value."
14005 (interactive "P")
14006 (if (equal value 0) (setq value 10))
14007 (let* ((completion-ignore-case t)
14008 (prop org-effort-property)
14009 (cur (org-entry-get nil prop))
14010 (allowed (org-property-get-allowed-values nil prop 'table))
14011 (existing (mapcar 'list (org-property-values prop)))
14013 (val (cond
14014 ((stringp value) value)
14015 ((and allowed (integerp value))
14016 (or (car (nth (1- value) allowed))
14017 (car (org-last allowed))))
14018 (allowed
14019 (message "Select 1-9,0, [RET%s]: %s"
14020 (if cur (concat "=" cur) "")
14021 (mapconcat 'car allowed " "))
14022 (setq rpl (read-char-exclusive))
14023 (if (equal rpl ?\r)
14025 (setq rpl (- rpl ?0))
14026 (if (equal rpl 0) (setq rpl 10))
14027 (if (and (> rpl 0) (<= rpl (length allowed)))
14028 (car (nth (1- rpl) allowed))
14029 (org-completing-read "Effort: " allowed nil))))
14031 (let (org-completion-use-ido org-completion-use-iswitchb)
14032 (org-completing-read
14033 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14034 (concat "[" cur "]") "")
14035 ": ")
14036 existing nil nil "" nil cur))))))
14037 (unless (equal (org-entry-get nil prop) val)
14038 (org-entry-put nil prop val))
14039 (message "%s is now %s" prop val)))
14041 (defun org-at-property-p ()
14042 "Is cursor inside a property drawer?"
14043 (save-excursion
14044 (beginning-of-line 1)
14045 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14046 (save-match-data ;; Used by calling procedures
14047 (let ((p (point))
14048 (range (unless (org-before-first-heading-p)
14049 (org-get-property-block))))
14050 (and range (<= (car range) p) (< p (cdr range))))))))
14052 (defun org-get-property-block (&optional beg end force)
14053 "Return the (beg . end) range of the body of the property drawer.
14054 BEG and END can be beginning and end of subtree, if not given
14055 they will be found.
14056 If the drawer does not exist and FORCE is non-nil, create the drawer."
14057 (catch 'exit
14058 (save-excursion
14059 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14060 (end (or end (progn (outline-next-heading) (point)))))
14061 (goto-char beg)
14062 (if (re-search-forward org-property-start-re end t)
14063 (setq beg (1+ (match-end 0)))
14064 (if force
14065 (save-excursion
14066 (org-insert-property-drawer)
14067 (setq end (progn (outline-next-heading) (point))))
14068 (throw 'exit nil))
14069 (goto-char beg)
14070 (if (re-search-forward org-property-start-re end t)
14071 (setq beg (1+ (match-end 0)))))
14072 (if (re-search-forward org-property-end-re end t)
14073 (setq end (match-beginning 0))
14074 (or force (throw 'exit nil))
14075 (goto-char beg)
14076 (setq end beg)
14077 (org-indent-line-function)
14078 (insert ":END:\n"))
14079 (cons beg end)))))
14081 (defun org-entry-properties (&optional pom which specific)
14082 "Get all properties of the entry at point-or-marker POM.
14083 This includes the TODO keyword, the tags, time strings for deadline,
14084 scheduled, and clocking, and any additional properties defined in the
14085 entry. The return value is an alist, keys may occur multiple times
14086 if the property key was used several times.
14087 POM may also be nil, in which case the current entry is used.
14088 If WHICH is nil or `all', get all properties. If WHICH is
14089 `special' or `standard', only get that subclass. If WHICH
14090 is a string only get exactly this property. SPECIFIC can be a string, the
14091 specific property we are interested in. Specifying it can speed
14092 things up because then unnecessary parsing is avoided."
14093 (setq which (or which 'all))
14094 (org-with-point-at pom
14095 (let ((clockstr (substring org-clock-string 0 -1))
14096 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14097 (case-fold-search nil)
14098 beg end range props sum-props key key1 value string clocksum)
14099 (save-excursion
14100 (when (condition-case nil
14101 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14102 (error nil))
14103 (setq beg (point))
14104 (setq sum-props (get-text-property (point) 'org-summaries))
14105 (setq clocksum (get-text-property (point) :org-clock-minutes))
14106 (outline-next-heading)
14107 (setq end (point))
14108 (when (memq which '(all special))
14109 ;; Get the special properties, like TODO and tags
14110 (goto-char beg)
14111 (when (and (or (not specific) (string= specific "TODO"))
14112 (looking-at org-todo-line-regexp) (match-end 2))
14113 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14114 (when (and (or (not specific) (string= specific "PRIORITY"))
14115 (looking-at org-priority-regexp))
14116 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14117 (when (or (not specific) (string= specific "FILE"))
14118 (push (cons "FILE" buffer-file-name) props))
14119 (when (and (or (not specific) (string= specific "TAGS"))
14120 (setq value (org-get-tags-string))
14121 (string-match "\\S-" value))
14122 (push (cons "TAGS" value) props))
14123 (when (and (or (not specific) (string= specific "ALLTAGS"))
14124 (setq value (org-get-tags-at)))
14125 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14126 ":"))
14127 props))
14128 (when (or (not specific) (string= specific "BLOCKED"))
14129 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14130 (when (or (not specific)
14131 (member specific
14132 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14133 "TIMESTAMP" "TIMESTAMP_IA")))
14134 (catch 'match
14135 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14136 (setq key (if (match-end 1)
14137 (substring (org-match-string-no-properties 1)
14138 0 -1))
14139 string (if (equal key clockstr)
14140 (org-no-properties
14141 (org-trim
14142 (buffer-substring
14143 (match-beginning 3) (goto-char
14144 (point-at-eol)))))
14145 (substring (org-match-string-no-properties 3)
14146 1 -1)))
14147 ;; Get the correct property name from the key. This is
14148 ;; necessary if the user has configured time keywords.
14149 (setq key1 (concat key ":"))
14150 (cond
14151 ((not key)
14152 (setq key
14153 (if (= (char-after (match-beginning 3)) ?\[)
14154 "TIMESTAMP_IA" "TIMESTAMP")))
14155 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14156 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14157 ((equal key1 org-closed-string) (setq key "CLOSED"))
14158 ((equal key1 org-clock-string) (setq key "CLOCK")))
14159 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14160 (progn
14161 (push (cons key string) props)
14162 ;; no need to search further if match is found
14163 (throw 'match t))
14164 (when (or (equal key "CLOCK") (not (assoc key props)))
14165 (push (cons key string) props))))))
14168 (when (memq which '(all standard))
14169 ;; Get the standard properties, like :PROP: ...
14170 (setq range (org-get-property-block beg end))
14171 (when range
14172 (goto-char (car range))
14173 (while (re-search-forward
14174 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14175 (cdr range) t)
14176 (setq key (org-match-string-no-properties 1)
14177 value (org-trim (or (org-match-string-no-properties 2) "")))
14178 (unless (member key excluded)
14179 (push (cons key (or value "")) props)))))
14180 (if clocksum
14181 (push (cons "CLOCKSUM"
14182 (org-columns-number-to-string (/ (float clocksum) 60.)
14183 'add_times))
14184 props))
14185 (unless (assoc "CATEGORY" props)
14186 (push (cons "CATEGORY" (org-get-category)) props))
14187 (append sum-props (nreverse props)))))))
14189 (defun org-entry-get (pom property &optional inherit literal-nil)
14190 "Get value of PROPERTY for entry at point-or-marker POM.
14191 If INHERIT is non-nil and the entry does not have the property,
14192 then also check higher levels of the hierarchy.
14193 If INHERIT is the symbol `selective', use inheritance only if the setting
14194 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14195 If the property is present but empty, the return value is the empty string.
14196 If the property is not present at all, nil is returned.
14198 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14199 do not interpret it as the list atom nil. This is used for inheritance
14200 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14201 (org-with-point-at pom
14202 (if (and inherit (if (eq inherit 'selective)
14203 (org-property-inherit-p property)
14205 (org-entry-get-with-inheritance property literal-nil)
14206 (if (member property org-special-properties)
14207 ;; We need a special property. Use `org-entry-properties' to
14208 ;; retrieve it, but specify the wanted property
14209 (cdr (assoc property (org-entry-properties nil 'special property)))
14210 (let ((range (unless (org-before-first-heading-p)
14211 (org-get-property-block)))
14212 (props (list (or (assoc property org-file-properties)
14213 (assoc property org-global-properties)
14214 (assoc property org-global-properties-fixed))))
14215 val)
14216 (flet ((ap (key)
14217 (when (re-search-forward
14218 (org-re-property key) (cdr range) t)
14219 (setq props
14220 (org-update-property-plist
14222 (if (match-end 1)
14223 (org-match-string-no-properties 1) "")
14224 props)))))
14225 (when (and range (goto-char (car range)))
14226 (ap property)
14227 (goto-char (car range))
14228 (while (ap (concat property "+")))
14229 (setq val (cdr (assoc property props)))
14230 (when val (if literal-nil val (org-not-nil val))))))))))
14232 (defun org-property-or-variable-value (var &optional inherit)
14233 "Check if there is a property fixing the value of VAR.
14234 If yes, return this value. If not, return the current value of the variable."
14235 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14236 (if (and prop (stringp prop) (string-match "\\S-" prop))
14237 (read prop)
14238 (symbol-value var))))
14240 (defun org-entry-delete (pom property)
14241 "Delete the property PROPERTY from entry at point-or-marker POM."
14242 (org-with-point-at pom
14243 (if (member property org-special-properties)
14244 nil ; cannot delete these properties.
14245 (let ((range (org-get-property-block)))
14246 (if (and range
14247 (goto-char (car range))
14248 (re-search-forward
14249 (org-re-property property)
14250 (cdr range) t))
14251 (progn
14252 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14254 nil)))))
14256 ;; Multi-values properties are properties that contain multiple values
14257 ;; These values are assumed to be single words, separated by whitespace.
14258 (defun org-entry-add-to-multivalued-property (pom property value)
14259 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14260 (let* ((old (org-entry-get pom property))
14261 (values (and old (org-split-string old "[ \t]"))))
14262 (setq value (org-entry-protect-space value))
14263 (unless (member value values)
14264 (setq values (cons value values))
14265 (org-entry-put pom property
14266 (mapconcat 'identity values " ")))))
14268 (defun org-entry-remove-from-multivalued-property (pom property value)
14269 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14270 (let* ((old (org-entry-get pom property))
14271 (values (and old (org-split-string old "[ \t]"))))
14272 (setq value (org-entry-protect-space value))
14273 (when (member value values)
14274 (setq values (delete value values))
14275 (org-entry-put pom property
14276 (mapconcat 'identity values " ")))))
14278 (defun org-entry-member-in-multivalued-property (pom property value)
14279 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14280 (let* ((old (org-entry-get pom property))
14281 (values (and old (org-split-string old "[ \t]"))))
14282 (setq value (org-entry-protect-space value))
14283 (member value values)))
14285 (defun org-entry-get-multivalued-property (pom property)
14286 "Return a list of values in a multivalued property."
14287 (let* ((value (org-entry-get pom property))
14288 (values (and value (org-split-string value "[ \t]"))))
14289 (mapcar 'org-entry-restore-space values)))
14291 (defun org-entry-put-multivalued-property (pom property &rest values)
14292 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14293 VALUES should be a list of strings. Spaces will be protected."
14294 (org-entry-put pom property
14295 (mapconcat 'org-entry-protect-space values " "))
14296 (let* ((value (org-entry-get pom property))
14297 (values (and value (org-split-string value "[ \t]"))))
14298 (mapcar 'org-entry-restore-space values)))
14300 (defun org-entry-protect-space (s)
14301 "Protect spaces and newline in string S."
14302 (while (string-match " " s)
14303 (setq s (replace-match "%20" t t s)))
14304 (while (string-match "\n" s)
14305 (setq s (replace-match "%0A" t t s)))
14308 (defun org-entry-restore-space (s)
14309 "Restore spaces and newline in string S."
14310 (while (string-match "%20" s)
14311 (setq s (replace-match " " t t s)))
14312 (while (string-match "%0A" s)
14313 (setq s (replace-match "\n" t t s)))
14316 (defvar org-entry-property-inherited-from (make-marker)
14317 "Marker pointing to the entry from where a property was inherited.
14318 Each call to `org-entry-get-with-inheritance' will set this marker to the
14319 location of the entry where the inheritance search matched. If there was
14320 no match, the marker will point nowhere.
14321 Note that also `org-entry-get' calls this function, if the INHERIT flag
14322 is set.")
14324 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14325 "Get entry property, and search higher levels if not present.
14326 The search will stop at the first ancestor which has the property defined.
14327 If the value found is \"nil\", return nil to show that the property
14328 should be considered as undefined (this is the meaning of nil here).
14329 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14330 (move-marker org-entry-property-inherited-from nil)
14331 (let (tmp)
14332 (unless (org-before-first-heading-p)
14333 (save-excursion
14334 (save-restriction
14335 (widen)
14336 (catch 'ex
14337 (while t
14338 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14339 (org-back-to-heading t)
14340 (move-marker org-entry-property-inherited-from (point))
14341 (throw 'ex tmp))
14342 (or (org-up-heading-safe) (throw 'ex nil)))))))
14343 (setq tmp (or tmp
14344 (cdr (assoc property org-file-properties))
14345 (cdr (assoc property org-global-properties))
14346 (cdr (assoc property org-global-properties-fixed))))
14347 (if literal-nil tmp (org-not-nil tmp))))
14349 (defvar org-property-changed-functions nil
14350 "Hook called when the value of a property has changed.
14351 Each hook function should accept two arguments, the name of the property
14352 and the new value.")
14354 (defun org-entry-put (pom property value)
14355 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14356 (org-with-point-at pom
14357 (org-back-to-heading t)
14358 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14359 range)
14360 (cond
14361 ((equal property "TODO")
14362 (when (and (stringp value) (string-match "\\S-" value)
14363 (not (member value org-todo-keywords-1)))
14364 (error "\"%s\" is not a valid TODO state" value))
14365 (if (or (not value)
14366 (not (string-match "\\S-" value)))
14367 (setq value 'none))
14368 (org-todo value)
14369 (org-set-tags nil 'align))
14370 ((equal property "PRIORITY")
14371 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14372 (string-to-char value) ?\ ))
14373 (org-set-tags nil 'align))
14374 ((equal property "SCHEDULED")
14375 (if (re-search-forward org-scheduled-time-regexp end t)
14376 (cond
14377 ((eq value 'earlier) (org-timestamp-change -1 'day))
14378 ((eq value 'later) (org-timestamp-change 1 'day))
14379 (t (call-interactively 'org-schedule)))
14380 (call-interactively 'org-schedule)))
14381 ((equal property "DEADLINE")
14382 (if (re-search-forward org-deadline-time-regexp end t)
14383 (cond
14384 ((eq value 'earlier) (org-timestamp-change -1 'day))
14385 ((eq value 'later) (org-timestamp-change 1 'day))
14386 (t (call-interactively 'org-deadline)))
14387 (call-interactively 'org-deadline)))
14388 ((member property org-special-properties)
14389 (error "The %s property can not yet be set with `org-entry-put'"
14390 property))
14391 (t ; a non-special property
14392 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14393 (setq range (org-get-property-block beg end 'force))
14394 (goto-char (car range))
14395 (if (re-search-forward
14396 (org-re-property property) (cdr range) t)
14397 (progn
14398 (delete-region (match-beginning 0) (match-end 0))
14399 (goto-char (match-beginning 0)))
14400 (goto-char (cdr range))
14401 (insert "\n")
14402 (backward-char 1)
14403 (org-indent-line-function))
14404 (insert ":" property ":")
14405 (and value (insert " " value))
14406 (org-indent-line-function)))))
14407 (run-hook-with-args 'org-property-changed-functions property value)))
14409 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14410 "Get all property keys in the current buffer.
14411 With INCLUDE-SPECIALS, also list the special properties that reflect things
14412 like tags and TODO state.
14413 With INCLUDE-DEFAULTS, also include properties that has special meaning
14414 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14415 and others.
14416 With INCLUDE-COLUMNS, also include property names given in COLUMN
14417 formats in the current buffer."
14418 (let (rtn range cfmt s p)
14419 (save-excursion
14420 (save-restriction
14421 (widen)
14422 (goto-char (point-min))
14423 (while (re-search-forward org-property-start-re nil t)
14424 (setq range (org-get-property-block))
14425 (goto-char (car range))
14426 (while (re-search-forward
14427 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14428 (cdr range) t)
14429 (add-to-list 'rtn (org-match-string-no-properties 1)))
14430 (outline-next-heading))))
14432 (when include-specials
14433 (setq rtn (append org-special-properties rtn)))
14435 (when include-defaults
14436 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14437 (add-to-list 'rtn org-effort-property))
14439 (when include-columns
14440 (save-excursion
14441 (save-restriction
14442 (widen)
14443 (goto-char (point-min))
14444 (while (re-search-forward
14445 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14446 nil t)
14447 (setq cfmt (match-string 2) s 0)
14448 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14449 cfmt s)
14450 (setq s (match-end 0)
14451 p (match-string 1 cfmt))
14452 (unless (or (equal p "ITEM")
14453 (member p org-special-properties))
14454 (add-to-list 'rtn (match-string 1 cfmt))))))))
14456 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14458 (defun org-property-values (key)
14459 "Return a list of all values of property KEY in the current buffer."
14460 (save-excursion
14461 (save-restriction
14462 (widen)
14463 (goto-char (point-min))
14464 (let ((re (org-re-property key))
14465 values)
14466 (while (re-search-forward re nil t)
14467 (add-to-list 'values (org-trim (match-string 1))))
14468 (delete "" values)))))
14470 (defun org-insert-property-drawer ()
14471 "Insert a property drawer into the current entry."
14472 (org-back-to-heading t)
14473 (looking-at org-outline-regexp)
14474 (let ((indent (if org-adapt-indentation
14475 (- (match-end 0) (match-beginning 0))
14477 (beg (point))
14478 (re (concat "^[ \t]*" org-keyword-time-regexp))
14479 end hiddenp)
14480 (outline-next-heading)
14481 (setq end (point))
14482 (goto-char beg)
14483 (while (re-search-forward re end t))
14484 (setq hiddenp (outline-invisible-p))
14485 (end-of-line 1)
14486 (and (equal (char-after) ?\n) (forward-char 1))
14487 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14488 (if (member (match-string 1) '("CLOCK:" ":END:"))
14489 ;; just skip this line
14490 (beginning-of-line 2)
14491 ;; Drawer start, find the end
14492 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14493 (beginning-of-line 1)))
14494 (org-skip-over-state-notes)
14495 (skip-chars-backward " \t\n\r")
14496 (if (eq (char-before) ?*) (forward-char 1))
14497 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14498 (beginning-of-line 0)
14499 (org-indent-to-column indent)
14500 (beginning-of-line 2)
14501 (org-indent-to-column indent)
14502 (beginning-of-line 0)
14503 (if hiddenp
14504 (save-excursion
14505 (org-back-to-heading t)
14506 (hide-entry))
14507 (org-flag-drawer t))))
14509 (defun org-insert-drawer (&optional arg drawer)
14510 "Insert a drawer at point.
14512 Optional argument DRAWER, when non-nil, is a string representing
14513 drawer's name. Otherwise, the user is prompted for a name.
14515 If a region is active, insert the drawer around that region
14516 instead.
14518 Point is left between drawer's boundaries."
14519 (interactive "P")
14520 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14521 "LOGBOOK"))
14522 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14523 ;; internally by Org. They are meant to be inserted
14524 ;; automatically.
14525 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14526 ;; Remove system drawers from list. Note: For some reason,
14527 ;; `org-completing-read' ignores the predicate while
14528 ;; `completing-read' handles it fine.
14529 (drawer (if arg "PROPERTIES"
14530 (or drawer
14531 (completing-read
14532 "Drawer: " org-drawers
14533 (lambda (d) (not (member d system-drawers))))))))
14534 (cond
14535 ;; With C-u, fall back on `org-insert-property-drawer'
14536 (arg (org-insert-property-drawer))
14537 ;; With an active region, insert a drawer at point.
14538 ((not (org-region-active-p))
14539 (progn
14540 (unless (bolp) (insert "\n"))
14541 (insert (format ":%s:\n\n:END:\n" drawer))
14542 (forward-line -2)))
14543 ;; Otherwise, insert the drawer at point
14545 (let ((rbeg (region-beginning))
14546 (rend (copy-marker (region-end))))
14547 (unwind-protect
14548 (progn
14549 (goto-char rbeg)
14550 (beginning-of-line)
14551 (when (save-excursion
14552 (re-search-forward org-outline-regexp-bol rend t))
14553 (error "Drawers cannot contain headlines"))
14554 ;; Position point at the beginning of the first
14555 ;; non-blank line in region. Insert drawer's opening
14556 ;; there, then indent it.
14557 (org-skip-whitespace)
14558 (beginning-of-line)
14559 (insert ":" drawer ":\n")
14560 (forward-line -1)
14561 (indent-for-tab-command)
14562 ;; Move point to the beginning of the first blank line
14563 ;; after the last non-blank line in region. Insert
14564 ;; drawer's closing, then indent it.
14565 (goto-char rend)
14566 (skip-chars-backward " \r\t\n")
14567 (insert "\n:END:")
14568 (indent-for-tab-command)
14569 (unless (eolp) (insert "\n")))
14570 ;; Clear marker, whatever the outcome of insertion is.
14571 (set-marker rend nil)))))))
14573 (defvar org-property-set-functions-alist nil
14574 "Property set function alist.
14575 Each entry should have the following format:
14577 (PROPERTY . READ-FUNCTION)
14579 The read function will be called with the same argument as
14580 `org-completing-read'.")
14582 (defun org-set-property-function (property)
14583 "Get the function that should be used to set PROPERTY.
14584 This is computed according to `org-property-set-functions-alist'."
14585 (or (cdr (assoc property org-property-set-functions-alist))
14586 'org-completing-read))
14588 (defun org-read-property-value (property)
14589 "Read PROPERTY value from user."
14590 (let* ((completion-ignore-case t)
14591 (allowed (org-property-get-allowed-values nil property 'table))
14592 (cur (org-entry-get nil property))
14593 (prompt (concat property " value"
14594 (if (and cur (string-match "\\S-" cur))
14595 (concat " [" cur "]") "") ": "))
14596 (set-function (org-set-property-function property))
14597 (val (if allowed
14598 (funcall set-function prompt allowed nil
14599 (not (get-text-property 0 'org-unrestricted
14600 (caar allowed))))
14601 (let (org-completion-use-ido org-completion-use-iswitchb)
14602 (funcall set-function prompt
14603 (mapcar 'list (org-property-values property))
14604 nil nil "" nil cur)))))
14605 (if (equal val "")
14607 val)))
14609 (defvar org-last-set-property nil)
14610 (defun org-read-property-name ()
14611 "Read a property name."
14612 (let* ((completion-ignore-case t)
14613 (keys (org-buffer-property-keys nil t t))
14614 (default-prop (or (save-excursion
14615 (save-match-data
14616 (beginning-of-line)
14617 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14618 (null (string= (match-string 1) "END"))
14619 (match-string 1))))
14620 org-last-set-property))
14621 (property (org-icompleting-read
14622 (concat "Property"
14623 (if default-prop (concat " [" default-prop "]") "")
14624 ": ")
14625 (mapcar 'list keys)
14626 nil nil nil nil
14627 default-prop
14629 (if (member property keys)
14630 property
14631 (or (cdr (assoc (downcase property)
14632 (mapcar (lambda (x) (cons (downcase x) x))
14633 keys)))
14634 property))))
14636 (defun org-set-property (property value)
14637 "In the current entry, set PROPERTY to VALUE.
14638 When called interactively, this will prompt for a property name, offering
14639 completion on existing and default properties. And then it will prompt
14640 for a value, offering completion either on allowed values (via an inherited
14641 xxx_ALL property) or on existing values in other instances of this property
14642 in the current file."
14643 (interactive (list nil nil))
14644 (let* ((property (or property (org-read-property-name)))
14645 (value (or value (org-read-property-value property)))
14646 (fn (assoc property org-properties-postprocess-alist)))
14647 (setq org-last-set-property property)
14648 ;; Possibly postprocess the inserted value:
14649 (when fn (setq value (funcall (cadr fn) value)))
14650 (unless (equal (org-entry-get nil property) value)
14651 (org-entry-put nil property value))))
14653 (defun org-delete-property (property)
14654 "In the current entry, delete PROPERTY."
14655 (interactive
14656 (let* ((completion-ignore-case t)
14657 (prop (org-icompleting-read "Property: "
14658 (org-entry-properties nil 'standard))))
14659 (list prop)))
14660 (message "Property %s %s" property
14661 (if (org-entry-delete nil property)
14662 "deleted"
14663 "was not present in the entry")))
14665 (defun org-delete-property-globally (property)
14666 "Remove PROPERTY globally, from all entries."
14667 (interactive
14668 (let* ((completion-ignore-case t)
14669 (prop (org-icompleting-read
14670 "Globally remove property: "
14671 (mapcar 'list (org-buffer-property-keys)))))
14672 (list prop)))
14673 (save-excursion
14674 (save-restriction
14675 (widen)
14676 (goto-char (point-min))
14677 (let ((cnt 0))
14678 (while (re-search-forward
14679 (org-re-property property)
14680 nil t)
14681 (setq cnt (1+ cnt))
14682 (replace-match ""))
14683 (message "Property \"%s\" removed from %d entries" property cnt)))))
14685 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14687 (defun org-compute-property-at-point ()
14688 "Compute the property at point.
14689 This looks for an enclosing column format, extracts the operator and
14690 then applies it to the property in the column format's scope."
14691 (interactive)
14692 (unless (org-at-property-p)
14693 (error "Not at a property"))
14694 (let ((prop (org-match-string-no-properties 2)))
14695 (org-columns-get-format-and-top-level)
14696 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14697 (error "No operator defined for property %s" prop))
14698 (org-columns-compute prop)))
14700 (defvar org-property-allowed-value-functions nil
14701 "Hook for functions supplying allowed values for a specific property.
14702 The functions must take a single argument, the name of the property, and
14703 return a flat list of allowed values. If \":ETC\" is one of
14704 the values, this means that these values are intended as defaults for
14705 completion, but that other values should be allowed too.
14706 The functions must return nil if they are not responsible for this
14707 property.")
14709 (defun org-property-get-allowed-values (pom property &optional table)
14710 "Get allowed values for the property PROPERTY.
14711 When TABLE is non-nil, return an alist that can directly be used for
14712 completion."
14713 (let (vals)
14714 (cond
14715 ((equal property "TODO")
14716 (setq vals (org-with-point-at pom
14717 (append org-todo-keywords-1 '("")))))
14718 ((equal property "PRIORITY")
14719 (let ((n org-lowest-priority))
14720 (while (>= n org-highest-priority)
14721 (push (char-to-string n) vals)
14722 (setq n (1- n)))))
14723 ((member property org-special-properties))
14724 ((setq vals (run-hook-with-args-until-success
14725 'org-property-allowed-value-functions property)))
14727 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14728 (when (and vals (string-match "\\S-" vals))
14729 (setq vals (car (read-from-string (concat "(" vals ")"))))
14730 (setq vals (mapcar (lambda (x)
14731 (cond ((stringp x) x)
14732 ((numberp x) (number-to-string x))
14733 ((symbolp x) (symbol-name x))
14734 (t "???")))
14735 vals)))))
14736 (when (member ":ETC" vals)
14737 (setq vals (remove ":ETC" vals))
14738 (org-add-props (car vals) '(org-unrestricted t)))
14739 (if table (mapcar 'list vals) vals)))
14741 (defun org-property-previous-allowed-value (&optional previous)
14742 "Switch to the next allowed value for this property."
14743 (interactive)
14744 (org-property-next-allowed-value t))
14746 (defun org-property-next-allowed-value (&optional previous)
14747 "Switch to the next allowed value for this property."
14748 (interactive)
14749 (unless (org-at-property-p)
14750 (error "Not at a property"))
14751 (let* ((key (match-string 2))
14752 (value (match-string 3))
14753 (allowed (or (org-property-get-allowed-values (point) key)
14754 (and (member value '("[ ]" "[-]" "[X]"))
14755 '("[ ]" "[X]"))))
14756 nval)
14757 (unless allowed
14758 (error "Allowed values for this property have not been defined"))
14759 (if previous (setq allowed (reverse allowed)))
14760 (if (member value allowed)
14761 (setq nval (car (cdr (member value allowed)))))
14762 (setq nval (or nval (car allowed)))
14763 (if (equal nval value)
14764 (error "Only one allowed value for this property"))
14765 (org-at-property-p)
14766 (replace-match (concat " :" key ": " nval) t t)
14767 (org-indent-line-function)
14768 (beginning-of-line 1)
14769 (skip-chars-forward " \t")
14770 (run-hook-with-args 'org-property-changed-functions key nval)))
14772 (defun org-find-olp (path &optional this-buffer)
14773 "Return a marker pointing to the entry at outline path OLP.
14774 If anything goes wrong, throw an error.
14775 You can wrap this call to catch the error like this:
14777 (condition-case msg
14778 (org-mobile-locate-entry (match-string 4))
14779 (error (nth 1 msg)))
14781 The return value will then be either a string with the error message,
14782 or a marker if everything is OK.
14784 If THIS-BUFFER is set, the outline path does not contain a file,
14785 only headings."
14786 (let* ((file (if this-buffer buffer-file-name (pop path)))
14787 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14788 (level 1)
14789 (lmin 1)
14790 (lmax 1)
14791 limit re end found pos heading cnt flevel)
14792 (unless buffer (error "File not found :%s" file))
14793 (with-current-buffer buffer
14794 (save-excursion
14795 (save-restriction
14796 (widen)
14797 (setq limit (point-max))
14798 (goto-char (point-min))
14799 (while (setq heading (pop path))
14800 (setq re (format org-complex-heading-regexp-format
14801 (regexp-quote heading)))
14802 (setq cnt 0 pos (point))
14803 (while (re-search-forward re end t)
14804 (setq level (- (match-end 1) (match-beginning 1)))
14805 (if (and (>= level lmin) (<= level lmax))
14806 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14807 (when (= cnt 0) (error "Heading not found on level %d: %s"
14808 lmax heading))
14809 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14810 lmax heading))
14811 (goto-char found)
14812 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14813 (setq end (save-excursion (org-end-of-subtree t t))))
14814 (when (org-at-heading-p)
14815 (move-marker (make-marker) (point))))))))
14817 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14818 "Find node HEADING in BUFFER.
14819 Return a marker to the heading if it was found, or nil if not.
14820 If POS-ONLY is set, return just the position instead of a marker.
14822 The heading text must match exact, but it may have a TODO keyword,
14823 a priority cookie and tags in the standard locations."
14824 (with-current-buffer (or buffer (current-buffer))
14825 (save-excursion
14826 (save-restriction
14827 (widen)
14828 (goto-char (point-min))
14829 (let (case-fold-search)
14830 (if (re-search-forward
14831 (format org-complex-heading-regexp-format
14832 (regexp-quote heading)) nil t)
14833 (if pos-only
14834 (match-beginning 0)
14835 (move-marker (make-marker) (match-beginning 0)))))))))
14837 (defun org-find-exact-heading-in-directory (heading &optional dir)
14838 "Find Org node headline HEADING in all .org files in directory DIR.
14839 When the target headline is found, return a marker to this location."
14840 (let ((files (directory-files (or dir default-directory)
14841 nil "\\`[^.#].*\\.org\\'"))
14842 file visiting m buffer)
14843 (catch 'found
14844 (while (setq file (pop files))
14845 (message "trying %s" file)
14846 (setq visiting (org-find-base-buffer-visiting file))
14847 (setq buffer (or visiting (find-file-noselect file)))
14848 (setq m (org-find-exact-headline-in-buffer
14849 heading buffer))
14850 (when (and (not m) (not visiting)) (kill-buffer buffer))
14851 (and m (throw 'found m))))))
14853 (defun org-find-entry-with-id (ident)
14854 "Locate the entry that contains the ID property with exact value IDENT.
14855 IDENT can be a string, a symbol or a number, this function will search for
14856 the string representation of it.
14857 Return the position where this entry starts, or nil if there is no such entry."
14858 (interactive "sID: ")
14859 (let ((id (cond
14860 ((stringp ident) ident)
14861 ((symbol-name ident) (symbol-name ident))
14862 ((numberp ident) (number-to-string ident))
14863 (t (error "IDENT %s must be a string, symbol or number" ident))))
14864 (case-fold-search nil))
14865 (save-excursion
14866 (save-restriction
14867 (widen)
14868 (goto-char (point-min))
14869 (when (re-search-forward
14870 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14871 nil t)
14872 (org-back-to-heading t)
14873 (point))))))
14875 ;;;; Timestamps
14877 (defvar org-last-changed-timestamp nil)
14878 (defvar org-last-inserted-timestamp nil
14879 "The last time stamp inserted with `org-insert-time-stamp'.")
14880 (defvar org-time-was-given) ; dynamically scoped parameter
14881 (defvar org-end-time-was-given) ; dynamically scoped parameter
14882 (defvar org-ts-what) ; dynamically scoped parameter
14884 (defun org-time-stamp (arg &optional inactive)
14885 "Prompt for a date/time and insert a time stamp.
14886 If the user specifies a time like HH:MM, or if this command is called
14887 with a prefix argument, the time stamp will contain date and time.
14888 Otherwise, only the date will be included. All parts of a date not
14889 specified by the user will be filled in from the current date/time.
14890 So if you press just return without typing anything, the time stamp
14891 will represent the current date/time. If there is already a timestamp
14892 at the cursor, it will be modified."
14893 (interactive "P")
14894 (let* ((ts nil)
14895 (default-time
14896 ;; Default time is either today, or, when entering a range,
14897 ;; the range start.
14898 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14899 (save-excursion
14900 (re-search-backward
14901 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14902 (- (point) 20) t)))
14903 (apply 'encode-time (org-parse-time-string (match-string 1)))
14904 (current-time)))
14905 (default-input (and ts (org-get-compact-tod ts)))
14906 (repeater (save-excursion
14907 (save-match-data
14908 (beginning-of-line)
14909 (when (re-search-forward
14910 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14911 (save-excursion (progn (end-of-line) (point))) t)
14912 (match-string 0)))))
14913 org-time-was-given org-end-time-was-given time)
14914 (cond
14915 ((and (org-at-timestamp-p t)
14916 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14917 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14918 (insert "--")
14919 (setq time (let ((this-command this-command))
14920 (org-read-date arg 'totime nil nil
14921 default-time default-input inactive)))
14922 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14923 ((org-at-timestamp-p t)
14924 (setq time (let ((this-command this-command))
14925 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14926 (when (org-at-timestamp-p t) ; just to get the match data
14927 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14928 (replace-match "")
14929 (setq org-last-changed-timestamp
14930 (org-insert-time-stamp
14931 time (or org-time-was-given arg)
14932 inactive nil nil (list org-end-time-was-given)))
14933 (when repeater (goto-char (1- (point))) (insert " " repeater)
14934 (setq org-last-changed-timestamp
14935 (concat (substring org-last-inserted-timestamp 0 -1)
14936 " " repeater ">"))))
14937 (message "Timestamp updated"))
14939 (setq time (let ((this-command this-command))
14940 (org-read-date arg 'totime nil nil default-time default-input inactive)))
14941 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14942 nil nil (list org-end-time-was-given))))))
14944 ;; FIXME: can we use this for something else, like computing time differences?
14945 (defun org-get-compact-tod (s)
14946 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14947 (let* ((t1 (match-string 1 s))
14948 (h1 (string-to-number (match-string 2 s)))
14949 (m1 (string-to-number (match-string 3 s)))
14950 (t2 (and (match-end 4) (match-string 5 s)))
14951 (h2 (and t2 (string-to-number (match-string 6 s))))
14952 (m2 (and t2 (string-to-number (match-string 7 s))))
14953 dh dm)
14954 (if (not t2)
14956 (setq dh (- h2 h1) dm (- m2 m1))
14957 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14958 (concat t1 "+" (number-to-string dh)
14959 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14961 (defun org-time-stamp-inactive (&optional arg)
14962 "Insert an inactive time stamp.
14963 An inactive time stamp is enclosed in square brackets instead of angle
14964 brackets. It is inactive in the sense that it does not trigger agenda entries,
14965 does not link to the calendar and cannot be changed with the S-cursor keys.
14966 So these are more for recording a certain time/date."
14967 (interactive "P")
14968 (org-time-stamp arg 'inactive))
14970 (defvar org-date-ovl (make-overlay 1 1))
14971 (overlay-put org-date-ovl 'face 'org-warning)
14972 (org-detach-overlay org-date-ovl)
14974 (defvar org-ans1) ; dynamically scoped parameter
14975 (defvar org-ans2) ; dynamically scoped parameter
14977 (defvar org-plain-time-of-day-regexp) ; defined below
14979 (defvar org-overriding-default-time nil) ; dynamically scoped
14980 (defvar org-read-date-overlay nil)
14981 (defvar org-dcst nil) ; dynamically scoped
14982 (defvar org-read-date-history nil)
14983 (defvar org-read-date-final-answer nil)
14984 (defvar org-read-date-analyze-futurep nil)
14985 (defvar org-read-date-analyze-forced-year nil)
14987 (defun org-read-date (&optional with-time to-time from-string prompt
14988 default-time default-input inactive)
14989 "Read a date, possibly a time, and make things smooth for the user.
14990 The prompt will suggest to enter an ISO date, but you can also enter anything
14991 which will at least partially be understood by `parse-time-string'.
14992 Unrecognized parts of the date will default to the current day, month, year,
14993 hour and minute. If this command is called to replace a timestamp at point,
14994 or to enter the second timestamp of a range, the default time is taken
14995 from the existing stamp. Furthermore, the command prefers the future,
14996 so if you are giving a date where the year is not given, and the day-month
14997 combination is already past in the current year, it will assume you
14998 mean next year. For details, see the manual. A few examples:
15000 3-2-5 --> 2003-02-05
15001 feb 15 --> currentyear-02-15
15002 2/15 --> currentyear-02-15
15003 sep 12 9 --> 2009-09-12
15004 12:45 --> today 12:45
15005 22 sept 0:34 --> currentyear-09-22 0:34
15006 12 --> currentyear-currentmonth-12
15007 Fri --> nearest Friday (today or later)
15008 etc.
15010 Furthermore you can specify a relative date by giving, as the *first* thing
15011 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15012 change in days weeks, months, years.
15013 With a single plus or minus, the date is relative to today. With a double
15014 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15015 +4d --> four days from today
15016 +4 --> same as above
15017 +2w --> two weeks from today
15018 ++5 --> five days from default date
15020 The function understands only English month and weekday abbreviations,
15021 but this can be configured with the variables `parse-time-months' and
15022 `parse-time-weekdays'.
15024 While prompting, a calendar is popped up - you can also select the
15025 date with the mouse (button 1). The calendar shows a period of three
15026 months. To scroll it to other months, use the keys `>' and `<'.
15027 If you don't like the calendar, turn it off with
15028 \(setq org-read-date-popup-calendar nil)
15030 With optional argument TO-TIME, the date will immediately be converted
15031 to an internal time.
15032 With an optional argument WITH-TIME, the prompt will suggest to also
15033 insert a time. Note that when WITH-TIME is not set, you can still
15034 enter a time, and this function will inform the calling routine about
15035 this change. The calling routine may then choose to change the format
15036 used to insert the time stamp into the buffer to include the time.
15037 With optional argument FROM-STRING, read from this string instead from
15038 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15039 the time/date that is used for everything that is not specified by the
15040 user."
15041 (require 'parse-time)
15042 (let* ((org-time-stamp-rounding-minutes
15043 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15044 (org-dcst org-display-custom-times)
15045 (ct (org-current-time))
15046 (def (or org-overriding-default-time default-time ct))
15047 (defdecode (decode-time def))
15048 (dummy (progn
15049 (when (< (nth 2 defdecode) org-extend-today-until)
15050 (setcar (nthcdr 2 defdecode) -1)
15051 (setcar (nthcdr 1 defdecode) 59)
15052 (setq def (apply 'encode-time defdecode)
15053 defdecode (decode-time def)))))
15054 (calendar-frame-setup nil)
15055 (calendar-setup nil)
15056 (calendar-move-hook nil)
15057 (calendar-view-diary-initially-flag nil)
15058 (calendar-view-holidays-initially-flag nil)
15059 (timestr (format-time-string
15060 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15061 (prompt (concat (if prompt (concat prompt " ") "")
15062 (format "Date+time [%s]: " timestr)))
15063 ans (org-ans0 "") org-ans1 org-ans2 final)
15065 (cond
15066 (from-string (setq ans from-string))
15067 (org-read-date-popup-calendar
15068 (save-excursion
15069 (save-window-excursion
15070 (calendar)
15071 (unwind-protect
15072 (progn
15073 (calendar-forward-day (- (time-to-days def)
15074 (calendar-absolute-from-gregorian
15075 (calendar-current-date))))
15076 (org-eval-in-calendar nil t)
15077 (let* ((old-map (current-local-map))
15078 (map (copy-keymap calendar-mode-map))
15079 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15080 (org-defkey map (kbd "RET") 'org-calendar-select)
15081 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15082 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15083 (org-defkey minibuffer-local-map [(meta shift left)]
15084 (lambda () (interactive)
15085 (org-eval-in-calendar '(calendar-backward-month 1))))
15086 (org-defkey minibuffer-local-map [(meta shift right)]
15087 (lambda () (interactive)
15088 (org-eval-in-calendar '(calendar-forward-month 1))))
15089 (org-defkey minibuffer-local-map [(meta shift up)]
15090 (lambda () (interactive)
15091 (org-eval-in-calendar '(calendar-backward-year 1))))
15092 (org-defkey minibuffer-local-map [(meta shift down)]
15093 (lambda () (interactive)
15094 (org-eval-in-calendar '(calendar-forward-year 1))))
15095 (org-defkey minibuffer-local-map [?\e (shift left)]
15096 (lambda () (interactive)
15097 (org-eval-in-calendar '(calendar-backward-month 1))))
15098 (org-defkey minibuffer-local-map [?\e (shift right)]
15099 (lambda () (interactive)
15100 (org-eval-in-calendar '(calendar-forward-month 1))))
15101 (org-defkey minibuffer-local-map [?\e (shift up)]
15102 (lambda () (interactive)
15103 (org-eval-in-calendar '(calendar-backward-year 1))))
15104 (org-defkey minibuffer-local-map [?\e (shift down)]
15105 (lambda () (interactive)
15106 (org-eval-in-calendar '(calendar-forward-year 1))))
15107 (org-defkey minibuffer-local-map [(shift up)]
15108 (lambda () (interactive)
15109 (org-eval-in-calendar '(calendar-backward-week 1))))
15110 (org-defkey minibuffer-local-map [(shift down)]
15111 (lambda () (interactive)
15112 (org-eval-in-calendar '(calendar-forward-week 1))))
15113 (org-defkey minibuffer-local-map [(shift left)]
15114 (lambda () (interactive)
15115 (org-eval-in-calendar '(calendar-backward-day 1))))
15116 (org-defkey minibuffer-local-map [(shift right)]
15117 (lambda () (interactive)
15118 (org-eval-in-calendar '(calendar-forward-day 1))))
15119 (org-defkey minibuffer-local-map ">"
15120 (lambda () (interactive)
15121 (org-eval-in-calendar '(scroll-calendar-left 1))))
15122 (org-defkey minibuffer-local-map "<"
15123 (lambda () (interactive)
15124 (org-eval-in-calendar '(scroll-calendar-right 1))))
15125 (org-defkey minibuffer-local-map "\C-v"
15126 (lambda () (interactive)
15127 (org-eval-in-calendar
15128 '(calendar-scroll-left-three-months 1))))
15129 (org-defkey minibuffer-local-map "\M-v"
15130 (lambda () (interactive)
15131 (org-eval-in-calendar
15132 '(calendar-scroll-right-three-months 1))))
15133 (run-hooks 'org-read-date-minibuffer-setup-hook)
15134 (unwind-protect
15135 (progn
15136 (use-local-map map)
15137 (setq org-read-date-inactive inactive)
15138 (add-hook 'post-command-hook 'org-read-date-display)
15139 (setq org-ans0 (read-string prompt default-input
15140 'org-read-date-history nil))
15141 ;; org-ans0: from prompt
15142 ;; org-ans1: from mouse click
15143 ;; org-ans2: from calendar motion
15144 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15145 (remove-hook 'post-command-hook 'org-read-date-display)
15146 (use-local-map old-map)
15147 (when org-read-date-overlay
15148 (delete-overlay org-read-date-overlay)
15149 (setq org-read-date-overlay nil)))))
15150 (bury-buffer "*Calendar*")))))
15152 (t ; Naked prompt only
15153 (unwind-protect
15154 (setq ans (read-string prompt default-input
15155 'org-read-date-history timestr))
15156 (when org-read-date-overlay
15157 (delete-overlay org-read-date-overlay)
15158 (setq org-read-date-overlay nil)))))
15160 (setq final (org-read-date-analyze ans def defdecode))
15162 (when org-read-date-analyze-forced-year
15163 (message "Year was forced into %s"
15164 (if org-read-date-force-compatible-dates
15165 "compatible range (1970-2037)"
15166 "range representable on this machine"))
15167 (ding))
15169 ;; One round trip to get rid of 34th of August and stuff like that....
15170 (setq final (decode-time (apply 'encode-time final)))
15172 (setq org-read-date-final-answer ans)
15174 (if to-time
15175 (apply 'encode-time final)
15176 (if (and (boundp 'org-time-was-given) org-time-was-given)
15177 (format "%04d-%02d-%02d %02d:%02d"
15178 (nth 5 final) (nth 4 final) (nth 3 final)
15179 (nth 2 final) (nth 1 final))
15180 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15182 (defvar def)
15183 (defvar defdecode)
15184 (defvar with-time)
15185 (defvar org-read-date-inactive)
15186 (defun org-read-date-display ()
15187 "Display the current date prompt interpretation in the minibuffer."
15188 (when org-read-date-display-live
15189 (when org-read-date-overlay
15190 (delete-overlay org-read-date-overlay))
15191 (let ((p (point)))
15192 (end-of-line 1)
15193 (while (not (equal (buffer-substring
15194 (max (point-min) (- (point) 4)) (point))
15195 " "))
15196 (insert " "))
15197 (goto-char p))
15198 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15199 " " (or org-ans1 org-ans2)))
15200 (org-end-time-was-given nil)
15201 (f (org-read-date-analyze ans def defdecode))
15202 (fmts (if org-dcst
15203 org-time-stamp-custom-formats
15204 org-time-stamp-formats))
15205 (fmt (if (or with-time
15206 (and (boundp 'org-time-was-given) org-time-was-given))
15207 (cdr fmts)
15208 (car fmts)))
15209 (txt (format-time-string fmt (apply 'encode-time f)))
15210 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15211 (txt (concat "=> " txt)))
15212 (when (and org-end-time-was-given
15213 (string-match org-plain-time-of-day-regexp txt))
15214 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15215 org-end-time-was-given
15216 (substring txt (match-end 0)))))
15217 (when org-read-date-analyze-futurep
15218 (setq txt (concat txt " (=>F)")))
15219 (setq org-read-date-overlay
15220 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15221 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15223 (defun org-read-date-analyze (ans def defdecode)
15224 "Analyze the combined answer of the date prompt."
15225 ;; FIXME: cleanup and comment
15226 (let ((nowdecode (decode-time (current-time)))
15227 delta deltan deltaw deltadef year month day
15228 hour minute second wday pm h2 m2 tl wday1
15229 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15230 (setq org-read-date-analyze-futurep nil
15231 org-read-date-analyze-forced-year nil)
15232 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15233 (setq ans "+0"))
15235 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15236 (setq ans (replace-match "" t t ans)
15237 deltan (car delta)
15238 deltaw (nth 1 delta)
15239 deltadef (nth 2 delta)))
15241 ;; Check if there is an iso week date in there
15242 ;; If yes, store the info and postpone interpreting it until the rest
15243 ;; of the parsing is done
15244 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15245 (setq iso-year (if (match-end 1)
15246 (org-small-year-to-year
15247 (string-to-number (match-string 1 ans))))
15248 iso-weekday (if (match-end 3)
15249 (string-to-number (match-string 3 ans)))
15250 iso-week (string-to-number (match-string 2 ans)))
15251 (setq ans (replace-match "" t t ans)))
15253 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15254 (when (string-match
15255 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15256 (setq year (if (match-end 2)
15257 (string-to-number (match-string 2 ans))
15258 (progn (setq kill-year t)
15259 (string-to-number (format-time-string "%Y"))))
15260 month (string-to-number (match-string 3 ans))
15261 day (string-to-number (match-string 4 ans)))
15262 (if (< year 100) (setq year (+ 2000 year)))
15263 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15264 t nil ans)))
15266 ;; Help matching dotted european dates
15267 (when (string-match
15268 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15269 (setq year (if (match-end 3)
15270 (string-to-number (match-string 3 ans))
15271 (progn (setq kill-year t)
15272 (string-to-number (format-time-string "%Y"))))
15273 day (string-to-number (match-string 1 ans))
15274 month (string-to-number (match-string 2 ans))
15275 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15276 t nil ans)))
15278 ;; Help matching american dates, like 5/30 or 5/30/7
15279 (when (string-match
15280 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15281 (setq year (if (match-end 4)
15282 (string-to-number (match-string 4 ans))
15283 (progn (setq kill-year t)
15284 (string-to-number (format-time-string "%Y"))))
15285 month (string-to-number (match-string 1 ans))
15286 day (string-to-number (match-string 2 ans)))
15287 (if (< year 100) (setq year (+ 2000 year)))
15288 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15289 t nil ans)))
15290 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15291 ;; If there is a time with am/pm, and *no* time without it, we convert
15292 ;; so that matching will be successful.
15293 (loop for i from 1 to 2 do ; twice, for end time as well
15294 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15295 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15296 (setq hour (string-to-number (match-string 1 ans))
15297 minute (if (match-end 3)
15298 (string-to-number (match-string 3 ans))
15300 pm (equal ?p
15301 (string-to-char (downcase (match-string 4 ans)))))
15302 (if (and (= hour 12) (not pm))
15303 (setq hour 0)
15304 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15305 (setq ans (replace-match (format "%02d:%02d" hour minute)
15306 t t ans))))
15308 ;; Check if a time range is given as a duration
15309 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15310 (setq hour (string-to-number (match-string 1 ans))
15311 h2 (+ hour (string-to-number (match-string 3 ans)))
15312 minute (string-to-number (match-string 2 ans))
15313 m2 (+ minute (if (match-end 5) (string-to-number
15314 (match-string 5 ans))0)))
15315 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15316 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15317 t t ans)))
15319 ;; Check if there is a time range
15320 (when (boundp 'org-end-time-was-given)
15321 (setq org-time-was-given nil)
15322 (when (and (string-match org-plain-time-of-day-regexp ans)
15323 (match-end 8))
15324 (setq org-end-time-was-given (match-string 8 ans))
15325 (setq ans (concat (substring ans 0 (match-beginning 7))
15326 (substring ans (match-end 7))))))
15328 (setq tl (parse-time-string ans)
15329 day (or (nth 3 tl) (nth 3 defdecode))
15330 month (or (nth 4 tl)
15331 (if (and org-read-date-prefer-future
15332 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15333 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15334 (nth 4 defdecode)))
15335 year (or (and (not kill-year) (nth 5 tl))
15336 (if (and org-read-date-prefer-future
15337 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15338 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15339 (nth 5 defdecode)))
15340 hour (or (nth 2 tl) (nth 2 defdecode))
15341 minute (or (nth 1 tl) (nth 1 defdecode))
15342 second (or (nth 0 tl) 0)
15343 wday (nth 6 tl))
15345 (when (and (eq org-read-date-prefer-future 'time)
15346 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15347 (equal day (nth 3 nowdecode))
15348 (equal month (nth 4 nowdecode))
15349 (equal year (nth 5 nowdecode))
15350 (nth 2 tl)
15351 (or (< (nth 2 tl) (nth 2 nowdecode))
15352 (and (= (nth 2 tl) (nth 2 nowdecode))
15353 (nth 1 tl)
15354 (< (nth 1 tl) (nth 1 nowdecode)))))
15355 (setq day (1+ day)
15356 futurep t))
15358 ;; Special date definitions below
15359 (cond
15360 (iso-week
15361 ;; There was an iso week
15362 (require 'cal-iso)
15363 (setq futurep nil)
15364 (setq year (or iso-year year)
15365 day (or iso-weekday wday 1)
15366 wday nil ; to make sure that the trigger below does not match
15367 iso-date (calendar-gregorian-from-absolute
15368 (calendar-absolute-from-iso
15369 (list iso-week day year))))
15370 ; FIXME: Should we also push ISO weeks into the future?
15371 ; (when (and org-read-date-prefer-future
15372 ; (not iso-year)
15373 ; (< (calendar-absolute-from-gregorian iso-date)
15374 ; (time-to-days (current-time))))
15375 ; (setq year (1+ year)
15376 ; iso-date (calendar-gregorian-from-absolute
15377 ; (calendar-absolute-from-iso
15378 ; (list iso-week day year)))))
15379 (setq month (car iso-date)
15380 year (nth 2 iso-date)
15381 day (nth 1 iso-date)))
15382 (deltan
15383 (setq futurep nil)
15384 (unless deltadef
15385 (let ((now (decode-time (current-time))))
15386 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15387 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15388 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15389 ((equal deltaw "m") (setq month (+ month deltan)))
15390 ((equal deltaw "y") (setq year (+ year deltan)))))
15391 ((and wday (not (nth 3 tl)))
15392 (setq futurep nil)
15393 ;; Weekday was given, but no day, so pick that day in the week
15394 ;; on or after the derived date.
15395 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15396 (unless (equal wday wday1)
15397 (setq day (+ day (% (- wday wday1 -7) 7))))))
15398 (if (and (boundp 'org-time-was-given)
15399 (nth 2 tl))
15400 (setq org-time-was-given t))
15401 (if (< year 100) (setq year (+ 2000 year)))
15402 ;; Check of the date is representable
15403 (if org-read-date-force-compatible-dates
15404 (progn
15405 (if (< year 1970)
15406 (setq year 1970 org-read-date-analyze-forced-year t))
15407 (if (> year 2037)
15408 (setq year 2037 org-read-date-analyze-forced-year t)))
15409 (condition-case nil
15410 (ignore (encode-time second minute hour day month year))
15411 (error
15412 (setq year (nth 5 defdecode))
15413 (setq org-read-date-analyze-forced-year t))))
15414 (setq org-read-date-analyze-futurep futurep)
15415 (list second minute hour day month year)))
15417 (defvar parse-time-weekdays)
15419 (defun org-read-date-get-relative (s today default)
15420 "Check string S for special relative date string.
15421 TODAY and DEFAULT are internal times, for today and for a default.
15422 Return shift list (N what def-flag)
15423 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15424 N is the number of WHATs to shift.
15425 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15426 the DEFAULT date rather than TODAY."
15427 (require 'parse-time)
15428 (when (and
15429 (string-match
15430 (concat
15431 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15432 "\\([0-9]+\\)?"
15433 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15434 "\\([ \t]\\|$\\)") s)
15435 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15436 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15437 (string-to-char (substring (match-string 1 s) -1))
15438 ?+))
15439 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15440 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15441 (what (if (match-end 3) (match-string 3 s) "d"))
15442 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15443 (date (if rel default today))
15444 (wday (nth 6 (decode-time date)))
15445 delta)
15446 (if wday1
15447 (progn
15448 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15449 (if (= dir ?-) (setq delta (- delta 7)))
15450 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15451 (list delta "d" rel))
15452 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15454 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15455 "Turn a user-specified date into the internal representation.
15456 The internal representation needed by the calendar is (month day year).
15457 This is a wrapper to handle the brain-dead convention in calendar that
15458 user function argument order change dependent on argument order."
15459 (if (boundp 'calendar-date-style)
15460 (cond
15461 ((eq calendar-date-style 'american)
15462 (list arg1 arg2 arg3))
15463 ((eq calendar-date-style 'european)
15464 (list arg2 arg1 arg3))
15465 ((eq calendar-date-style 'iso)
15466 (list arg2 arg3 arg1)))
15467 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15468 (if (org-bound-and-true-p european-calendar-style)
15469 (list arg2 arg1 arg3)
15470 (list arg1 arg2 arg3)))))
15472 (defun org-eval-in-calendar (form &optional keepdate)
15473 "Eval FORM in the calendar window and return to current window.
15474 Also, store the cursor date in variable org-ans2."
15475 (let ((sf (selected-frame))
15476 (sw (selected-window)))
15477 (select-window (get-buffer-window "*Calendar*" t))
15478 (eval form)
15479 (when (and (not keepdate) (calendar-cursor-to-date))
15480 (let* ((date (calendar-cursor-to-date))
15481 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15482 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15483 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15484 (select-window sw)
15485 (org-select-frame-set-input-focus sf)))
15487 (defun org-calendar-select ()
15488 "Return to `org-read-date' with the date currently selected.
15489 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15490 (interactive)
15491 (when (calendar-cursor-to-date)
15492 (let* ((date (calendar-cursor-to-date))
15493 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15494 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15495 (if (active-minibuffer-window) (exit-minibuffer))))
15497 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15498 "Insert a date stamp for the date given by the internal TIME.
15499 WITH-HM means use the stamp format that includes the time of the day.
15500 INACTIVE means use square brackets instead of angular ones, so that the
15501 stamp will not contribute to the agenda.
15502 PRE and POST are optional strings to be inserted before and after the
15503 stamp.
15504 The command returns the inserted time stamp."
15505 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15506 stamp)
15507 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15508 (insert-before-markers (or pre ""))
15509 (when (listp extra)
15510 (setq extra (car extra))
15511 (if (and (stringp extra)
15512 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15513 (setq extra (format "-%02d:%02d"
15514 (string-to-number (match-string 1 extra))
15515 (string-to-number (match-string 2 extra))))
15516 (setq extra nil)))
15517 (when extra
15518 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15519 (insert-before-markers (setq stamp (format-time-string fmt time)))
15520 (insert-before-markers (or post ""))
15521 (setq org-last-inserted-timestamp stamp)))
15523 (defun org-toggle-time-stamp-overlays ()
15524 "Toggle the use of custom time stamp formats."
15525 (interactive)
15526 (setq org-display-custom-times (not org-display-custom-times))
15527 (unless org-display-custom-times
15528 (let ((p (point-min)) (bmp (buffer-modified-p)))
15529 (while (setq p (next-single-property-change p 'display))
15530 (if (and (get-text-property p 'display)
15531 (eq (get-text-property p 'face) 'org-date))
15532 (remove-text-properties
15533 p (setq p (next-single-property-change p 'display))
15534 '(display t))))
15535 (set-buffer-modified-p bmp)))
15536 (if (featurep 'xemacs)
15537 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15538 (org-restart-font-lock)
15539 (setq org-table-may-need-update t)
15540 (if org-display-custom-times
15541 (message "Time stamps are overlaid with custom format")
15542 (message "Time stamp overlays removed")))
15544 (defun org-display-custom-time (beg end)
15545 "Overlay modified time stamp format over timestamp between BEG and END."
15546 (let* ((ts (buffer-substring beg end))
15547 t1 w1 with-hm tf time str w2 (off 0))
15548 (save-match-data
15549 (setq t1 (org-parse-time-string ts t))
15550 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15551 (setq off (- (match-end 0) (match-beginning 0)))))
15552 (setq end (- end off))
15553 (setq w1 (- end beg)
15554 with-hm (and (nth 1 t1) (nth 2 t1))
15555 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15556 time (org-fix-decoded-time t1)
15557 str (org-add-props
15558 (format-time-string
15559 (substring tf 1 -1) (apply 'encode-time time))
15560 nil 'mouse-face 'highlight)
15561 w2 (length str))
15562 (if (not (= w2 w1))
15563 (add-text-properties (1+ beg) (+ 2 beg)
15564 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15565 (if (featurep 'xemacs)
15566 (progn
15567 (put-text-property beg end 'invisible t)
15568 (put-text-property beg end 'end-glyph (make-glyph str)))
15569 (put-text-property beg end 'display str))))
15571 (defun org-translate-time (string)
15572 "Translate all timestamps in STRING to custom format.
15573 But do this only if the variable `org-display-custom-times' is set."
15574 (when org-display-custom-times
15575 (save-match-data
15576 (let* ((start 0)
15577 (re org-ts-regexp-both)
15578 t1 with-hm inactive tf time str beg end)
15579 (while (setq start (string-match re string start))
15580 (setq beg (match-beginning 0)
15581 end (match-end 0)
15582 t1 (save-match-data
15583 (org-parse-time-string (substring string beg end) t))
15584 with-hm (and (nth 1 t1) (nth 2 t1))
15585 inactive (equal (substring string beg (1+ beg)) "[")
15586 tf (funcall (if with-hm 'cdr 'car)
15587 org-time-stamp-custom-formats)
15588 time (org-fix-decoded-time t1)
15589 str (format-time-string
15590 (concat
15591 (if inactive "[" "<") (substring tf 1 -1)
15592 (if inactive "]" ">"))
15593 (apply 'encode-time time))
15594 string (replace-match str t t string)
15595 start (+ start (length str)))))))
15596 string)
15598 (defun org-fix-decoded-time (time)
15599 "Set 0 instead of nil for the first 6 elements of time.
15600 Don't touch the rest."
15601 (let ((n 0))
15602 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15604 (defun org-days-to-time (timestamp-string)
15605 "Difference between TIMESTAMP-STRING and now in days."
15606 (- (time-to-days (org-time-string-to-time timestamp-string))
15607 (time-to-days (current-time))))
15609 (defun org-deadline-close (timestamp-string &optional ndays)
15610 "Is the time in TIMESTAMP-STRING close to the current date?"
15611 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15612 (and (< (org-days-to-time timestamp-string) ndays)
15613 (not (org-entry-is-done-p))))
15615 (defun org-get-wdays (ts)
15616 "Get the deadline lead time appropriate for timestring TS."
15617 (cond
15618 ((<= org-deadline-warning-days 0)
15619 ;; 0 or negative, enforce this value no matter what
15620 (- org-deadline-warning-days))
15621 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15622 ;; lead time is specified.
15623 (floor (* (string-to-number (match-string 1 ts))
15624 (cdr (assoc (match-string 2 ts)
15625 '(("d" . 1) ("w" . 7)
15626 ("m" . 30.4) ("y" . 365.25)))))))
15627 ;; go for the default.
15628 (t org-deadline-warning-days)))
15630 (defun org-calendar-select-mouse (ev)
15631 "Return to `org-read-date' with the date currently selected.
15632 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15633 (interactive "e")
15634 (mouse-set-point ev)
15635 (when (calendar-cursor-to-date)
15636 (let* ((date (calendar-cursor-to-date))
15637 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15638 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15639 (if (active-minibuffer-window) (exit-minibuffer))))
15641 (defun org-check-deadlines (ndays)
15642 "Check if there are any deadlines due or past due.
15643 A deadline is considered due if it happens within `org-deadline-warning-days'
15644 days from today's date. If the deadline appears in an entry marked DONE,
15645 it is not shown. The prefix arg NDAYS can be used to test that many
15646 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15647 (interactive "P")
15648 (let* ((org-warn-days
15649 (cond
15650 ((equal ndays '(4)) 100000)
15651 (ndays (prefix-numeric-value ndays))
15652 (t (abs org-deadline-warning-days))))
15653 (case-fold-search nil)
15654 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15655 (callback
15656 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15658 (message "%d deadlines past-due or due within %d days"
15659 (org-occur regexp nil callback)
15660 org-warn-days)))
15662 (defun org-check-before-date (date)
15663 "Check if there are deadlines or scheduled entries before DATE."
15664 (interactive (list (org-read-date)))
15665 (let ((case-fold-search nil)
15666 (regexp (concat "\\<\\(" org-deadline-string
15667 "\\|" org-scheduled-string
15668 "\\) *<\\([^>]+\\)>"))
15669 (callback
15670 (lambda () (time-less-p
15671 (org-time-string-to-time (match-string 2))
15672 (org-time-string-to-time date)))))
15673 (message "%d entries before %s"
15674 (org-occur regexp nil callback) date)))
15676 (defun org-check-after-date (date)
15677 "Check if there are deadlines or scheduled entries after DATE."
15678 (interactive (list (org-read-date)))
15679 (let ((case-fold-search nil)
15680 (regexp (concat "\\<\\(" org-deadline-string
15681 "\\|" org-scheduled-string
15682 "\\) *<\\([^>]+\\)>"))
15683 (callback
15684 (lambda () (not
15685 (time-less-p
15686 (org-time-string-to-time (match-string 2))
15687 (org-time-string-to-time date))))))
15688 (message "%d entries after %s"
15689 (org-occur regexp nil callback) date)))
15691 (defun org-check-dates-range (start-date end-date)
15692 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15693 (interactive (list (org-read-date nil nil nil "Range starts")
15694 (org-read-date nil nil nil "Range end")))
15695 (let ((case-fold-search nil)
15696 (regexp (concat "\\<\\(" org-deadline-string
15697 "\\|" org-scheduled-string
15698 "\\) *<\\([^>]+\\)>"))
15699 (callback
15700 (lambda ()
15701 (let ((match (match-string 2)))
15702 (and
15703 (not (time-less-p
15704 (org-time-string-to-time match)
15705 (org-time-string-to-time start-date)))
15706 (time-less-p
15707 (org-time-string-to-time match)
15708 (org-time-string-to-time end-date)))))))
15709 (message "%d entries between %s and %s"
15710 (org-occur regexp nil callback) start-date end-date)))
15712 (defun org-evaluate-time-range (&optional to-buffer)
15713 "Evaluate a time range by computing the difference between start and end.
15714 Normally the result is just printed in the echo area, but with prefix arg
15715 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15716 If the time range is actually in a table, the result is inserted into the
15717 next column.
15718 For time difference computation, a year is assumed to be exactly 365
15719 days in order to avoid rounding problems."
15720 (interactive "P")
15722 (org-clock-update-time-maybe)
15723 (save-excursion
15724 (unless (org-at-date-range-p t)
15725 (goto-char (point-at-bol))
15726 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15727 (if (not (org-at-date-range-p t))
15728 (error "Not at a time-stamp range, and none found in current line")))
15729 (let* ((ts1 (match-string 1))
15730 (ts2 (match-string 2))
15731 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15732 (match-end (match-end 0))
15733 (time1 (org-time-string-to-time ts1))
15734 (time2 (org-time-string-to-time ts2))
15735 (t1 (org-float-time time1))
15736 (t2 (org-float-time time2))
15737 (diff (abs (- t2 t1)))
15738 (negative (< (- t2 t1) 0))
15739 ;; (ys (floor (* 365 24 60 60)))
15740 (ds (* 24 60 60))
15741 (hs (* 60 60))
15742 (fy "%dy %dd %02d:%02d")
15743 (fy1 "%dy %dd")
15744 (fd "%dd %02d:%02d")
15745 (fd1 "%dd")
15746 (fh "%02d:%02d")
15747 y d h m align)
15748 (if havetime
15749 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15751 d (floor (/ diff ds)) diff (mod diff ds)
15752 h (floor (/ diff hs)) diff (mod diff hs)
15753 m (floor (/ diff 60)))
15754 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15756 d (floor (+ (/ diff ds) 0.5))
15757 h 0 m 0))
15758 (if (not to-buffer)
15759 (message "%s" (org-make-tdiff-string y d h m))
15760 (if (org-at-table-p)
15761 (progn
15762 (goto-char match-end)
15763 (setq align t)
15764 (and (looking-at " *|") (goto-char (match-end 0))))
15765 (goto-char match-end))
15766 (if (looking-at
15767 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15768 (replace-match ""))
15769 (if negative (insert " -"))
15770 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15771 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15772 (insert " " (format fh h m))))
15773 (if align (org-table-align))
15774 (message "Time difference inserted")))))
15776 (defun org-make-tdiff-string (y d h m)
15777 (let ((fmt "")
15778 (l nil))
15779 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15780 l (push y l)))
15781 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15782 l (push d l)))
15783 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15784 l (push h l)))
15785 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15786 l (push m l)))
15787 (apply 'format fmt (nreverse l))))
15789 (defun org-time-string-to-time (s &optional buffer pos)
15790 (condition-case errdata
15791 (apply 'encode-time (org-parse-time-string s))
15792 (error (error "Bad timestamp `%s'%s\nError was: %s"
15793 s (if (not (and buffer pos))
15795 (format " at %d in buffer `%s'" pos buffer))
15796 (cdr errdata)))))
15798 (defun org-time-string-to-seconds (s)
15799 (org-float-time (org-time-string-to-time s)))
15801 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15802 "Convert a time stamp to an absolute day number.
15803 If there is a specifier for a cyclic time stamp, get the closest date to
15804 DAYNR.
15805 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15806 The variable date is bound by the calendar when this is called."
15807 (cond
15808 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15809 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15810 daynr
15811 (+ daynr 1000)))
15812 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15813 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15814 (time-to-days (current-time))) (match-string 0 s)
15815 prefer show-all))
15816 (t (time-to-days
15817 (condition-case errdata
15818 (apply 'encode-time (org-parse-time-string s))
15819 (error (error "Bad timestamp `%s'%s\nError was: %s"
15820 s (if (not (and buffer pos))
15822 (format " at %d in buffer `%s'" pos buffer))
15823 (cdr errdata))))))))
15825 (defun org-days-to-iso-week (days)
15826 "Return the iso week number."
15827 (require 'cal-iso)
15828 (car (calendar-iso-from-absolute days)))
15830 (defun org-small-year-to-year (year)
15831 "Convert 2-digit years into 4-digit years.
15832 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15833 The year 2000 cannot be abbreviated. Any year larger than 99
15834 is returned unchanged."
15835 (if (< year 38)
15836 (setq year (+ 2000 year))
15837 (if (< year 100)
15838 (setq year (+ 1900 year))))
15839 year)
15841 (defun org-time-from-absolute (d)
15842 "Return the time corresponding to date D.
15843 D may be an absolute day number, or a calendar-type list (month day year)."
15844 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15845 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15847 (defun org-calendar-holiday ()
15848 "List of holidays, for Diary display in Org-mode."
15849 (require 'holidays)
15850 (let ((hl (funcall
15851 (if (fboundp 'calendar-check-holidays)
15852 'calendar-check-holidays 'check-calendar-holidays) date)))
15853 (if hl (mapconcat 'identity hl "; "))))
15855 (defun org-diary-sexp-entry (sexp entry date)
15856 "Process a SEXP diary ENTRY for DATE."
15857 (require 'diary-lib)
15858 (let ((result (if calendar-debug-sexp
15859 (let ((stack-trace-on-error t))
15860 (eval (car (read-from-string sexp))))
15861 (condition-case nil
15862 (eval (car (read-from-string sexp)))
15863 (error
15864 (beep)
15865 (message "Bad sexp at line %d in %s: %s"
15866 (org-current-line)
15867 (buffer-file-name) sexp)
15868 (sleep-for 2))))))
15869 (cond ((stringp result) (split-string result "; "))
15870 ((and (consp result)
15871 (not (consp (cdr result)))
15872 (stringp (cdr result))) (cdr result))
15873 ((and (consp result)
15874 (stringp (car result))) result)
15875 (result entry)
15876 (t nil))))
15878 (defun org-diary-to-ical-string (frombuf)
15879 "Get iCalendar entries from diary entries in buffer FROMBUF.
15880 This uses the icalendar.el library."
15881 (let* ((tmpdir (if (featurep 'xemacs)
15882 (temp-directory)
15883 temporary-file-directory))
15884 (tmpfile (make-temp-name
15885 (expand-file-name "orgics" tmpdir)))
15886 buf rtn b e)
15887 (with-current-buffer frombuf
15888 (icalendar-export-region (point-min) (point-max) tmpfile)
15889 (setq buf (find-buffer-visiting tmpfile))
15890 (set-buffer buf)
15891 (goto-char (point-min))
15892 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15893 (setq b (match-beginning 0)))
15894 (goto-char (point-max))
15895 (if (re-search-backward "^END:VEVENT" nil t)
15896 (setq e (match-end 0)))
15897 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15898 (kill-buffer buf)
15899 (delete-file tmpfile)
15900 rtn))
15902 (defun org-closest-date (start current change prefer show-all)
15903 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15904 When PREFER is `past', return a date that is either CURRENT or past.
15905 When PREFER is `future', return a date that is either CURRENT or future.
15906 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15907 ;; Make the proper lists from the dates
15908 (catch 'exit
15909 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15910 dn dw sday cday n1 n2 n0
15911 d m y y1 y2 date1 date2 nmonths nm ny m2)
15913 (setq start (org-date-to-gregorian start)
15914 current (org-date-to-gregorian
15915 (if show-all
15916 current
15917 (time-to-days (current-time))))
15918 sday (calendar-absolute-from-gregorian start)
15919 cday (calendar-absolute-from-gregorian current))
15921 (if (<= cday sday) (throw 'exit sday))
15923 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15924 (setq dn (string-to-number (match-string 1 change))
15925 dw (cdr (assoc (match-string 2 change) a1)))
15926 (error "Invalid change specifier: %s" change))
15927 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15928 (cond
15929 ((eq dw 'day)
15930 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15931 n2 (+ n1 dn)))
15932 ((eq dw 'year)
15933 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15934 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15935 (setq date1 (list m d y1)
15936 n1 (calendar-absolute-from-gregorian date1)
15937 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15938 n2 (calendar-absolute-from-gregorian date2)))
15939 ((eq dw 'month)
15940 ;; approx number of month between the two dates
15941 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15942 ;; How often does dn fit in there?
15943 (setq d (nth 1 start) m (car start) y (nth 2 start)
15944 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15945 m (+ m nm)
15946 ny (floor (/ m 12))
15947 y (+ y ny)
15948 m (- m (* ny 12)))
15949 (while (> m 12) (setq m (- m 12) y (1+ y)))
15950 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15951 (setq m2 (+ m dn) y2 y)
15952 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15953 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15954 (while (<= n2 cday)
15955 (setq n1 n2 m m2 y y2)
15956 (setq m2 (+ m dn) y2 y)
15957 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15958 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15959 ;; Make sure n1 is the earlier date
15960 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15961 (if show-all
15962 (cond
15963 ((eq prefer 'past) (if (= cday n2) n2 n1))
15964 ((eq prefer 'future) (if (= cday n1) n1 n2))
15965 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15966 (cond
15967 ((eq prefer 'past) (if (= cday n2) n2 n1))
15968 ((eq prefer 'future) (if (= cday n1) n1 n2))
15969 (t (if (= cday n1) n1 n2)))))))
15971 (defun org-date-to-gregorian (date)
15972 "Turn any specification of DATE into a Gregorian date for the calendar."
15973 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15974 ((and (listp date) (= (length date) 3)) date)
15975 ((stringp date)
15976 (setq date (org-parse-time-string date))
15977 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15978 ((listp date)
15979 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15981 (defun org-parse-time-string (s &optional nodefault)
15982 "Parse the standard Org-mode time string.
15983 This should be a lot faster than the normal `parse-time-string'.
15984 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15985 hour and minute fields will be nil if not given."
15986 (if (string-match org-ts-regexp0 s)
15987 (list 0
15988 (if (or (match-beginning 8) (not nodefault))
15989 (string-to-number (or (match-string 8 s) "0")))
15990 (if (or (match-beginning 7) (not nodefault))
15991 (string-to-number (or (match-string 7 s) "0")))
15992 (string-to-number (match-string 4 s))
15993 (string-to-number (match-string 3 s))
15994 (string-to-number (match-string 2 s))
15995 nil nil nil)
15996 (error "Not a standard Org-mode time string: %s" s)))
15998 (defun org-timestamp-up (&optional arg)
15999 "Increase the date item at the cursor by one.
16000 If the cursor is on the year, change the year. If it is on the month,
16001 the day or the time, change that.
16002 With prefix ARG, change by that many units."
16003 (interactive "p")
16004 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16006 (defun org-timestamp-down (&optional arg)
16007 "Decrease the date item at the cursor by one.
16008 If the cursor is on the year, change the year. If it is on the month,
16009 the day or the time, change that.
16010 With prefix ARG, change by that many units."
16011 (interactive "p")
16012 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16014 (defun org-timestamp-up-day (&optional arg)
16015 "Increase the date in the time stamp by one day.
16016 With prefix ARG, change that many days."
16017 (interactive "p")
16018 (if (and (not (org-at-timestamp-p t))
16019 (org-at-heading-p))
16020 (org-todo 'up)
16021 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16023 (defun org-timestamp-down-day (&optional arg)
16024 "Decrease the date in the time stamp by one day.
16025 With prefix ARG, change that many days."
16026 (interactive "p")
16027 (if (and (not (org-at-timestamp-p t))
16028 (org-at-heading-p))
16029 (org-todo 'down)
16030 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16032 (defun org-at-timestamp-p (&optional inactive-ok)
16033 "Determine if the cursor is in or at a timestamp."
16034 (interactive)
16035 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16036 (pos (point))
16037 (ans (or (looking-at tsr)
16038 (save-excursion
16039 (skip-chars-backward "^[<\n\r\t")
16040 (if (> (point) (point-min)) (backward-char 1))
16041 (and (looking-at tsr)
16042 (> (- (match-end 0) pos) -1))))))
16043 (and ans
16044 (boundp 'org-ts-what)
16045 (setq org-ts-what
16046 (cond
16047 ((= pos (match-beginning 0)) 'bracket)
16048 ;; Point is considered to be "on the bracket" whether
16049 ;; it's really on it or right after it.
16050 ((or (= pos (1- (match-end 0)))
16051 (= pos (match-end 0))) 'bracket)
16052 ((org-pos-in-match-range pos 2) 'year)
16053 ((org-pos-in-match-range pos 3) 'month)
16054 ((org-pos-in-match-range pos 7) 'hour)
16055 ((org-pos-in-match-range pos 8) 'minute)
16056 ((or (org-pos-in-match-range pos 4)
16057 (org-pos-in-match-range pos 5)) 'day)
16058 ((and (> pos (or (match-end 8) (match-end 5)))
16059 (< pos (match-end 0)))
16060 (- pos (or (match-end 8) (match-end 5))))
16061 (t 'day))))
16062 ans))
16064 (defun org-toggle-timestamp-type ()
16065 "Toggle the type (<active> or [inactive]) of a time stamp."
16066 (interactive)
16067 (when (org-at-timestamp-p t)
16068 (let ((beg (match-beginning 0)) (end (match-end 0))
16069 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16070 (save-excursion
16071 (goto-char beg)
16072 (while (re-search-forward "[][<>]" end t)
16073 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16074 t t)))
16075 (message "Timestamp is now %sactive"
16076 (if (equal (char-after beg) ?<) "" "in")))))
16078 (defun org-timestamp-change (n &optional what updown)
16079 "Change the date in the time stamp at point.
16080 The date will be changed by N times WHAT. WHAT can be `day', `month',
16081 `year', `minute', `second'. If WHAT is not given, the cursor position
16082 in the timestamp determines what will be changed."
16083 (let ((origin (point)) origin-cat
16084 with-hm inactive
16085 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16086 org-ts-what
16087 extra rem
16088 ts time time0)
16089 (if (not (org-at-timestamp-p t))
16090 (error "Not at a timestamp"))
16091 (if (and (not what) (eq org-ts-what 'bracket))
16092 (org-toggle-timestamp-type)
16093 ;; Point isn't on brackets. Remember the part of the time-stamp
16094 ;; the point was in. Indeed, size of time-stamps may change,
16095 ;; but point must be kept in the same category nonetheless.
16096 (setq origin-cat org-ts-what)
16097 (if (and (not what) (not (eq org-ts-what 'day))
16098 org-display-custom-times
16099 (get-text-property (point) 'display)
16100 (not (get-text-property (1- (point)) 'display)))
16101 (setq org-ts-what 'day))
16102 (setq org-ts-what (or what org-ts-what)
16103 inactive (= (char-after (match-beginning 0)) ?\[)
16104 ts (match-string 0))
16105 (replace-match "")
16106 (if (string-match
16107 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
16109 (setq extra (match-string 1 ts)))
16110 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16111 (setq with-hm t))
16112 (setq time0 (org-parse-time-string ts))
16113 (when (and updown
16114 (eq org-ts-what 'minute)
16115 (not current-prefix-arg))
16116 ;; This looks like s-up and s-down. Change by one rounding step.
16117 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16118 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16119 (setcar (cdr time0) (+ (nth 1 time0)
16120 (if (> n 0) (- rem) (- dm rem))))))
16121 (setq time
16122 (encode-time (or (car time0) 0)
16123 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16124 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16125 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16126 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16127 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16128 (nthcdr 6 time0)))
16129 (when (and (member org-ts-what '(hour minute))
16130 extra
16131 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16132 (setq extra (org-modify-ts-extra
16133 extra
16134 (if (eq org-ts-what 'hour) 2 5)
16135 n dm)))
16136 (when (integerp org-ts-what)
16137 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16138 (if (eq what 'calendar)
16139 (let ((cal-date (org-get-date-from-calendar)))
16140 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16141 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16142 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16143 (setcar time0 (or (car time0) 0))
16144 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16145 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16146 (setq time (apply 'encode-time time0))))
16147 ;; Insert the new time-stamp, and ensure point stays in the same
16148 ;; category as before (i.e. not after the last position in that
16149 ;; category).
16150 (let ((pos (point)))
16151 ;; Stay before inserted string. `save-excursion' is of no use.
16152 (setq org-last-changed-timestamp
16153 (org-insert-time-stamp time with-hm inactive nil nil extra))
16154 (goto-char pos))
16155 (save-match-data
16156 (looking-at org-ts-regexp3)
16157 (goto-char (cond
16158 ;; `day' category ends before `hour' if any, or at
16159 ;; the end of the day name.
16160 ((eq origin-cat 'day)
16161 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16162 ((eq origin-cat 'hour) (min (match-end 7) origin))
16163 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16164 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16165 ;; `year' and `month' have both fixed size: point
16166 ;; couldn't have moved into another part.
16167 (t origin))))
16168 ;; Update clock if on a CLOCK line.
16169 (org-clock-update-time-maybe)
16170 ;; Try to recenter the calendar window, if any.
16171 (if (and org-calendar-follow-timestamp-change
16172 (get-buffer-window "*Calendar*" t)
16173 (memq org-ts-what '(day month year)))
16174 (org-recenter-calendar (time-to-days time))))))
16176 (defun org-modify-ts-extra (s pos n dm)
16177 "Change the different parts of the lead-time and repeat fields in timestamp."
16178 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16179 ng h m new rem)
16180 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16181 (cond
16182 ((or (org-pos-in-match-range pos 2)
16183 (org-pos-in-match-range pos 3))
16184 (setq m (string-to-number (match-string 3 s))
16185 h (string-to-number (match-string 2 s)))
16186 (if (org-pos-in-match-range pos 2)
16187 (setq h (+ h n))
16188 (setq n (* dm (org-no-warnings (signum n))))
16189 (when (not (= 0 (setq rem (% m dm))))
16190 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16191 (setq m (+ m n)))
16192 (if (< m 0) (setq m (+ m 60) h (1- h)))
16193 (if (> m 59) (setq m (- m 60) h (1+ h)))
16194 (setq h (min 24 (max 0 h)))
16195 (setq ng 1 new (format "-%02d:%02d" h m)))
16196 ((org-pos-in-match-range pos 6)
16197 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16198 ((org-pos-in-match-range pos 5)
16199 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16201 ((org-pos-in-match-range pos 9)
16202 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16203 ((org-pos-in-match-range pos 8)
16204 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16206 (when ng
16207 (setq s (concat
16208 (substring s 0 (match-beginning ng))
16210 (substring s (match-end ng))))))
16213 (defun org-recenter-calendar (date)
16214 "If the calendar is visible, recenter it to DATE."
16215 (let ((cwin (get-buffer-window "*Calendar*" t)))
16216 (when cwin
16217 (let ((calendar-move-hook nil))
16218 (with-selected-window cwin
16219 (calendar-goto-date (if (listp date) date
16220 (calendar-gregorian-from-absolute date))))))))
16222 (defun org-goto-calendar (&optional arg)
16223 "Go to the Emacs calendar at the current date.
16224 If there is a time stamp in the current line, go to that date.
16225 A prefix ARG can be used to force the current date."
16226 (interactive "P")
16227 (let ((tsr org-ts-regexp) diff
16228 (calendar-move-hook nil)
16229 (calendar-view-holidays-initially-flag nil)
16230 (calendar-view-diary-initially-flag nil))
16231 (if (or (org-at-timestamp-p)
16232 (save-excursion
16233 (beginning-of-line 1)
16234 (looking-at (concat ".*" tsr))))
16235 (let ((d1 (time-to-days (current-time)))
16236 (d2 (time-to-days
16237 (org-time-string-to-time (match-string 1)))))
16238 (setq diff (- d2 d1))))
16239 (calendar)
16240 (calendar-goto-today)
16241 (if (and diff (not arg)) (calendar-forward-day diff))))
16243 (defun org-get-date-from-calendar ()
16244 "Return a list (month day year) of date at point in calendar."
16245 (with-current-buffer "*Calendar*"
16246 (save-match-data
16247 (calendar-cursor-to-date))))
16249 (defun org-date-from-calendar ()
16250 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16251 If there is already a time stamp at the cursor position, update it."
16252 (interactive)
16253 (if (org-at-timestamp-p t)
16254 (org-timestamp-change 0 'calendar)
16255 (let ((cal-date (org-get-date-from-calendar)))
16256 (org-insert-time-stamp
16257 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16259 (defun org-minutes-to-hh:mm-string (m)
16260 "Compute H:MM from a number of minutes."
16261 (let ((h (/ m 60)))
16262 (setq m (- m (* 60 h)))
16263 (format org-time-clocksum-format h m)))
16265 (defun org-hh:mm-string-to-minutes (s)
16266 "Convert a string H:MM to a number of minutes.
16267 If the string is just a number, interpret it as minutes.
16268 In fact, the first hh:mm or number in the string will be taken,
16269 there can be extra stuff in the string.
16270 If no number is found, the return value is 0."
16271 (cond
16272 ((integerp s) s)
16273 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16274 (+ (* (string-to-number (match-string 1 s)) 60)
16275 (string-to-number (match-string 2 s))))
16276 ((string-match "\\([0-9]+\\)" s)
16277 (string-to-number (match-string 1 s)))
16278 (t 0)))
16280 (defcustom org-effort-durations
16281 `(("h" . 60)
16282 ("d" . ,(* 60 8))
16283 ("w" . ,(* 60 8 5))
16284 ("m" . ,(* 60 8 5 4))
16285 ("y" . ,(* 60 8 5 40)))
16286 "Conversion factor to minutes for an effort modifier.
16288 Each entry has the form (MODIFIER . MINUTES).
16290 In an effort string, a number followed by MODIFIER is multiplied
16291 by the specified number of MINUTES to obtain an effort in
16292 minutes.
16294 For example, if the value of this variable is ((\"hours\" . 60)), then an
16295 effort string \"2hours\" is equivalent to 120 minutes."
16296 :group 'org-agenda
16297 :version "24.1"
16298 :type '(alist :key-type (string :tag "Modifier")
16299 :value-type (number :tag "Minutes")))
16301 (defun org-duration-string-to-minutes (s)
16302 "Convert a duration string S to minutes.
16304 A bare number is interpreted as minutes, modifiers can be set by
16305 customizing `org-effort-durations' (which see).
16307 Entries containing a colon are interpreted as H:MM by
16308 `org-hh:mm-string-to-minutes'."
16309 (let ((result 0)
16310 (re (concat "\\([0-9]+\\) *\\("
16311 (regexp-opt (mapcar 'car org-effort-durations))
16312 "\\)")))
16313 (while (string-match re s)
16314 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16315 (string-to-number (match-string 1 s))))
16316 (setq s (replace-match "" nil t s)))
16317 (incf result (org-hh:mm-string-to-minutes s))
16318 result))
16320 ;;;; Files
16322 (defun org-save-all-org-buffers ()
16323 "Save all Org-mode buffers without user confirmation."
16324 (interactive)
16325 (message "Saving all Org-mode buffers...")
16326 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16327 (when (featurep 'org-id) (org-id-locations-save))
16328 (message "Saving all Org-mode buffers... done"))
16330 (defun org-revert-all-org-buffers ()
16331 "Revert all Org-mode buffers.
16332 Prompt for confirmation when there are unsaved changes.
16333 Be sure you know what you are doing before letting this function
16334 overwrite your changes.
16336 This function is useful in a setup where one tracks org files
16337 with a version control system, to revert on one machine after pulling
16338 changes from another. I believe the procedure must be like this:
16340 1. M-x org-save-all-org-buffers
16341 2. Pull changes from the other machine, resolve conflicts
16342 3. M-x org-revert-all-org-buffers"
16343 (interactive)
16344 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16345 (error "Abort"))
16346 (save-excursion
16347 (save-window-excursion
16348 (mapc
16349 (lambda (b)
16350 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16351 (with-current-buffer b buffer-file-name))
16352 (org-pop-to-buffer-same-window b)
16353 (revert-buffer t 'no-confirm)))
16354 (buffer-list))
16355 (when (and (featurep 'org-id) org-id-track-globally)
16356 (org-id-locations-load)))))
16358 ;;;; Agenda files
16360 ;;;###autoload
16361 (defun org-switchb (&optional arg)
16362 "Switch between Org buffers.
16363 With one prefix argument, restrict available buffers to files.
16364 With two prefix arguments, restrict available buffers to agenda files.
16366 Defaults to `iswitchb' for buffer name completion.
16367 Set `org-completion-use-ido' to make it use ido instead."
16368 (interactive "P")
16369 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16370 ((equal arg '(16)) (org-buffer-list 'agenda))
16371 (t (org-buffer-list))))
16372 (org-completion-use-iswitchb org-completion-use-iswitchb)
16373 (org-completion-use-ido org-completion-use-ido))
16374 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16375 (setq org-completion-use-iswitchb t))
16376 (org-pop-to-buffer-same-window
16377 (org-icompleting-read "Org buffer: "
16378 (mapcar 'list (mapcar 'buffer-name blist))
16379 nil t))))
16381 ;;; Define some older names previously used for this functionality
16382 ;;;###autoload
16383 (defalias 'org-ido-switchb 'org-switchb)
16384 ;;;###autoload
16385 (defalias 'org-iswitchb 'org-switchb)
16387 (defun org-buffer-list (&optional predicate exclude-tmp)
16388 "Return a list of Org buffers.
16389 PREDICATE can be `export', `files' or `agenda'.
16391 export restrict the list to Export buffers.
16392 files restrict the list to buffers visiting Org files.
16393 agenda restrict the list to buffers visiting agenda files.
16395 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16396 (let* ((bfn nil)
16397 (agenda-files (and (eq predicate 'agenda)
16398 (mapcar 'file-truename (org-agenda-files t))))
16399 (filter
16400 (cond
16401 ((eq predicate 'files)
16402 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16403 ((eq predicate 'export)
16404 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16405 ((eq predicate 'agenda)
16406 (lambda (b)
16407 (with-current-buffer b
16408 (and (eq major-mode 'org-mode)
16409 (setq bfn (buffer-file-name b))
16410 (member (file-truename bfn) agenda-files)))))
16411 (t (lambda (b) (with-current-buffer b
16412 (or (eq major-mode 'org-mode)
16413 (string-match "\*Org .*Export"
16414 (buffer-name b)))))))))
16415 (delq nil
16416 (mapcar
16417 (lambda(b)
16418 (if (and (funcall filter b)
16419 (or (not exclude-tmp)
16420 (not (string-match "tmp" (buffer-name b)))))
16422 nil))
16423 (buffer-list)))))
16425 (defun org-agenda-files (&optional unrestricted archives)
16426 "Get the list of agenda files.
16427 Optional UNRESTRICTED means return the full list even if a restriction
16428 is currently in place.
16429 When ARCHIVES is t, include all archive files that are really being
16430 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16431 `org-agenda-archives-mode' is t."
16432 (let ((files
16433 (cond
16434 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16435 ((stringp org-agenda-files) (org-read-agenda-file-list))
16436 ((listp org-agenda-files) org-agenda-files)
16437 (t (error "Invalid value of `org-agenda-files'")))))
16438 (setq files (apply 'append
16439 (mapcar (lambda (f)
16440 (if (file-directory-p f)
16441 (directory-files
16442 f t org-agenda-file-regexp)
16443 (list f)))
16444 files)))
16445 (when org-agenda-skip-unavailable-files
16446 (setq files (delq nil
16447 (mapcar (function
16448 (lambda (file)
16449 (and (file-readable-p file) file)))
16450 files))))
16451 (when (or (eq archives t)
16452 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16453 (setq files (org-add-archive-files files)))
16454 files))
16456 (defun org-agenda-file-p (&optional file)
16457 "Return non-nil, if FILE is an agenda file.
16458 If FILE is omitted, use the file associated with the current
16459 buffer."
16460 (member (or file (buffer-file-name))
16461 (org-agenda-files t)))
16463 (defun org-edit-agenda-file-list ()
16464 "Edit the list of agenda files.
16465 Depending on setup, this either uses customize to edit the variable
16466 `org-agenda-files', or it visits the file that is holding the list. In the
16467 latter case, the buffer is set up in a way that saving it automatically kills
16468 the buffer and restores the previous window configuration."
16469 (interactive)
16470 (if (stringp org-agenda-files)
16471 (let ((cw (current-window-configuration)))
16472 (find-file org-agenda-files)
16473 (org-set-local 'org-window-configuration cw)
16474 (org-add-hook 'after-save-hook
16475 (lambda ()
16476 (set-window-configuration
16477 (prog1 org-window-configuration
16478 (kill-buffer (current-buffer))))
16479 (org-install-agenda-files-menu)
16480 (message "New agenda file list installed"))
16481 nil 'local)
16482 (message "%s" (substitute-command-keys
16483 "Edit list and finish with \\[save-buffer]")))
16484 (customize-variable 'org-agenda-files)))
16486 (defun org-store-new-agenda-file-list (list)
16487 "Set new value for the agenda file list and save it correctly."
16488 (if (stringp org-agenda-files)
16489 (let ((fe (org-read-agenda-file-list t)) b u)
16490 (while (setq b (find-buffer-visiting org-agenda-files))
16491 (kill-buffer b))
16492 (with-temp-file org-agenda-files
16493 (insert
16494 (mapconcat
16495 (lambda (f) ;; Keep un-expanded entries.
16496 (if (setq u (assoc f fe))
16497 (cdr u)
16499 list "\n")
16500 "\n")))
16501 (let ((org-mode-hook nil) (org-inhibit-startup t)
16502 (org-insert-mode-line-in-empty-file nil))
16503 (setq org-agenda-files list)
16504 (customize-save-variable 'org-agenda-files org-agenda-files))))
16506 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16507 "Read the list of agenda files from a file.
16508 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16509 filenames, used by `org-store-new-agenda-file-list' to write back
16510 un-expanded file names."
16511 (when (file-directory-p org-agenda-files)
16512 (error "`org-agenda-files' cannot be a single directory"))
16513 (when (stringp org-agenda-files)
16514 (with-temp-buffer
16515 (insert-file-contents org-agenda-files)
16516 (mapcar
16517 (lambda (f)
16518 (let ((e (expand-file-name (substitute-in-file-name f)
16519 org-directory)))
16520 (if pair-with-expansion
16521 (cons e f)
16522 e)))
16523 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16525 ;;;###autoload
16526 (defun org-cycle-agenda-files ()
16527 "Cycle through the files in `org-agenda-files'.
16528 If the current buffer visits an agenda file, find the next one in the list.
16529 If the current buffer does not, find the first agenda file."
16530 (interactive)
16531 (let* ((fs (org-agenda-files t))
16532 (files (append fs (list (car fs))))
16533 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16534 file)
16535 (unless files (error "No agenda files"))
16536 (catch 'exit
16537 (while (setq file (pop files))
16538 (if (equal (file-truename file) tcf)
16539 (when (car files)
16540 (find-file (car files))
16541 (throw 'exit t))))
16542 (find-file (car fs)))
16543 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16545 (defun org-agenda-file-to-front (&optional to-end)
16546 "Move/add the current file to the top of the agenda file list.
16547 If the file is not present in the list, it is added to the front. If it is
16548 present, it is moved there. With optional argument TO-END, add/move to the
16549 end of the list."
16550 (interactive "P")
16551 (let ((org-agenda-skip-unavailable-files nil)
16552 (file-alist (mapcar (lambda (x)
16553 (cons (file-truename x) x))
16554 (org-agenda-files t)))
16555 (ctf (file-truename buffer-file-name))
16556 x had)
16557 (setq x (assoc ctf file-alist) had x)
16559 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16560 (if to-end
16561 (setq file-alist (append (delq x file-alist) (list x)))
16562 (setq file-alist (cons x (delq x file-alist))))
16563 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16564 (org-install-agenda-files-menu)
16565 (message "File %s to %s of agenda file list"
16566 (if had "moved" "added") (if to-end "end" "front"))))
16568 (defun org-remove-file (&optional file)
16569 "Remove current file from the list of files in variable `org-agenda-files'.
16570 These are the files which are being checked for agenda entries.
16571 Optional argument FILE means use this file instead of the current."
16572 (interactive)
16573 (let* ((org-agenda-skip-unavailable-files nil)
16574 (file (or file buffer-file-name))
16575 (true-file (file-truename file))
16576 (afile (abbreviate-file-name file))
16577 (files (delq nil (mapcar
16578 (lambda (x)
16579 (if (equal true-file
16580 (file-truename x))
16581 nil x))
16582 (org-agenda-files t)))))
16583 (if (not (= (length files) (length (org-agenda-files t))))
16584 (progn
16585 (org-store-new-agenda-file-list files)
16586 (org-install-agenda-files-menu)
16587 (message "Removed file: %s" afile))
16588 (message "File was not in list: %s (not removed)" afile))))
16590 (defun org-file-menu-entry (file)
16591 (vector file (list 'find-file file) t))
16593 (defun org-check-agenda-file (file)
16594 "Make sure FILE exists. If not, ask user what to do."
16595 (when (not (file-exists-p file))
16596 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16597 (abbreviate-file-name file))
16598 (let ((r (downcase (read-char-exclusive))))
16599 (cond
16600 ((equal r ?r)
16601 (org-remove-file file)
16602 (throw 'nextfile t))
16603 (t (error "Abort"))))))
16605 (defun org-get-agenda-file-buffer (file)
16606 "Get a buffer visiting FILE. If the buffer needs to be created, add
16607 it to the list of buffers which might be released later."
16608 (let ((buf (org-find-base-buffer-visiting file)))
16609 (if buf
16610 buf ; just return it
16611 ;; Make a new buffer and remember it
16612 (setq buf (find-file-noselect file))
16613 (if buf (push buf org-agenda-new-buffers))
16614 buf)))
16616 (defun org-release-buffers (blist)
16617 "Release all buffers in list, asking the user for confirmation when needed.
16618 When a buffer is unmodified, it is just killed. When modified, it is saved
16619 \(if the user agrees) and then killed."
16620 (let (buf file)
16621 (while (setq buf (pop blist))
16622 (setq file (buffer-file-name buf))
16623 (when (and (buffer-modified-p buf)
16624 file
16625 (y-or-n-p (format "Save file %s? " file)))
16626 (with-current-buffer buf (save-buffer)))
16627 (kill-buffer buf))))
16629 (defun org-prepare-agenda-buffers (files)
16630 "Create buffers for all agenda files, protect archived trees and comments."
16631 (interactive)
16632 (let ((pa '(:org-archived t))
16633 (pc '(:org-comment t))
16634 (pall '(:org-archived t :org-comment t))
16635 (inhibit-read-only t)
16636 (rea (concat ":" org-archive-tag ":"))
16637 bmp file re)
16638 (save-excursion
16639 (save-restriction
16640 (while (setq file (pop files))
16641 (catch 'nextfile
16642 (if (bufferp file)
16643 (set-buffer file)
16644 (org-check-agenda-file file)
16645 (set-buffer (org-get-agenda-file-buffer file)))
16646 (widen)
16647 (setq bmp (buffer-modified-p))
16648 (org-refresh-category-properties)
16649 (setq org-todo-keywords-for-agenda
16650 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16651 (setq org-done-keywords-for-agenda
16652 (append org-done-keywords-for-agenda org-done-keywords))
16653 (setq org-todo-keyword-alist-for-agenda
16654 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16655 (setq org-drawers-for-agenda
16656 (append org-drawers-for-agenda org-drawers))
16657 (setq org-tag-alist-for-agenda
16658 (append org-tag-alist-for-agenda org-tag-alist))
16660 (save-excursion
16661 (remove-text-properties (point-min) (point-max) pall)
16662 (when org-agenda-skip-archived-trees
16663 (goto-char (point-min))
16664 (while (re-search-forward rea nil t)
16665 (if (org-at-heading-p t)
16666 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16667 (goto-char (point-min))
16668 (setq re (format org-heading-keyword-regexp-format
16669 org-comment-string))
16670 (while (re-search-forward re nil t)
16671 (add-text-properties
16672 (match-beginning 0) (org-end-of-subtree t) pc)))
16673 (set-buffer-modified-p bmp)))))
16674 (setq org-todo-keywords-for-agenda
16675 (org-uniquify org-todo-keywords-for-agenda))
16676 (setq org-todo-keyword-alist-for-agenda
16677 (org-uniquify org-todo-keyword-alist-for-agenda)
16678 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16680 ;;;; Embedded LaTeX
16682 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16683 "Keymap for the minor `org-cdlatex-mode'.")
16685 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16686 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16687 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16688 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16689 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16691 (defvar org-cdlatex-texmathp-advice-is-done nil
16692 "Flag remembering if we have applied the advice to texmathp already.")
16694 (define-minor-mode org-cdlatex-mode
16695 "Toggle the minor `org-cdlatex-mode'.
16696 This mode supports entering LaTeX environment and math in LaTeX fragments
16697 in Org-mode.
16698 \\{org-cdlatex-mode-map}"
16699 nil " OCDL" nil
16700 (when org-cdlatex-mode
16701 (require 'cdlatex)
16702 (run-hooks 'cdlatex-mode-hook)
16703 (cdlatex-compute-tables))
16704 (unless org-cdlatex-texmathp-advice-is-done
16705 (setq org-cdlatex-texmathp-advice-is-done t)
16706 (defadvice texmathp (around org-math-always-on activate)
16707 "Always return t in org-mode buffers.
16708 This is because we want to insert math symbols without dollars even outside
16709 the LaTeX math segments. If Orgmode thinks that point is actually inside
16710 an embedded LaTeX fragment, let texmathp do its job.
16711 \\[org-cdlatex-mode-map]"
16712 (interactive)
16713 (let (p)
16714 (cond
16715 ((not (eq major-mode 'org-mode)) ad-do-it)
16716 ((eq this-command 'cdlatex-math-symbol)
16717 (setq ad-return-value t
16718 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16720 (let ((p (org-inside-LaTeX-fragment-p)))
16721 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16722 (setq ad-return-value t
16723 texmathp-why '("Org-mode embedded math" . 0))
16724 (if p ad-do-it)))))))))
16726 (defun turn-on-org-cdlatex ()
16727 "Unconditionally turn on `org-cdlatex-mode'."
16728 (org-cdlatex-mode 1))
16730 (defun org-inside-LaTeX-fragment-p ()
16731 "Test if point is inside a LaTeX fragment.
16732 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16733 sequence appearing also before point.
16734 Even though the matchers for math are configurable, this function assumes
16735 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16736 delimiters are skipped when they have been removed by customization.
16737 The return value is nil, or a cons cell with the delimiter and the
16738 position of this delimiter.
16740 This function does a reasonably good job, but can locally be fooled by
16741 for example currency specifications. For example it will assume being in
16742 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16743 fragments that are properly closed, but during editing, we have to live
16744 with the uncertainty caused by missing closing delimiters. This function
16745 looks only before point, not after."
16746 (catch 'exit
16747 (let ((pos (point))
16748 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16749 (lim (progn
16750 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16751 (point)))
16752 dd-on str (start 0) m re)
16753 (goto-char pos)
16754 (when dodollar
16755 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16756 re (nth 1 (assoc "$" org-latex-regexps)))
16757 (while (string-match re str start)
16758 (cond
16759 ((= (match-end 0) (length str))
16760 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16761 ((= (match-end 0) (- (length str) 5))
16762 (throw 'exit nil))
16763 (t (setq start (match-end 0))))))
16764 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16765 (goto-char pos)
16766 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16767 (and (match-beginning 2) (throw 'exit nil))
16768 ;; count $$
16769 (while (re-search-backward "\\$\\$" lim t)
16770 (setq dd-on (not dd-on)))
16771 (goto-char pos)
16772 (if dd-on (cons "$$" m))))))
16774 (defun org-inside-latex-macro-p ()
16775 "Is point inside a LaTeX macro or its arguments?"
16776 (save-match-data
16777 (org-in-regexp
16778 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16780 (defun org-try-cdlatex-tab ()
16781 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16782 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16783 - inside a LaTeX fragment, or
16784 - after the first word in a line, where an abbreviation expansion could
16785 insert a LaTeX environment."
16786 (when org-cdlatex-mode
16787 (cond
16788 ;; Before any word on the line: No expansion possible.
16789 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16790 ;; Just after first word on the line: Expand it. Make sure it
16791 ;; cannot happen on headlines, though.
16792 ((save-excursion
16793 (skip-chars-backward "a-zA-Z0-9*")
16794 (skip-chars-backward " \t")
16795 (and (bolp) (not (org-at-heading-p))))
16796 (cdlatex-tab) t)
16797 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16799 (defun org-cdlatex-underscore-caret (&optional arg)
16800 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16801 Revert to the normal definition outside of these fragments."
16802 (interactive "P")
16803 (if (org-inside-LaTeX-fragment-p)
16804 (call-interactively 'cdlatex-sub-superscript)
16805 (let (org-cdlatex-mode)
16806 (call-interactively (key-binding (vector last-input-event))))))
16808 (defun org-cdlatex-math-modify (&optional arg)
16809 "Execute `cdlatex-math-modify' in LaTeX fragments.
16810 Revert to the normal definition outside of these fragments."
16811 (interactive "P")
16812 (if (org-inside-LaTeX-fragment-p)
16813 (call-interactively 'cdlatex-math-modify)
16814 (let (org-cdlatex-mode)
16815 (call-interactively (key-binding (vector last-input-event))))))
16817 (defvar org-latex-fragment-image-overlays nil
16818 "List of overlays carrying the images of latex fragments.")
16819 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16821 (defun org-remove-latex-fragment-image-overlays ()
16822 "Remove all overlays with LaTeX fragment images in current buffer."
16823 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16824 (setq org-latex-fragment-image-overlays nil))
16826 (defun org-preview-latex-fragment (&optional subtree)
16827 "Preview the LaTeX fragment at point, or all locally or globally.
16828 If the cursor is in a LaTeX fragment, create the image and overlay
16829 it over the source code. If there is no fragment at point, display
16830 all fragments in the current text, from one headline to the next. With
16831 prefix SUBTREE, display all fragments in the current subtree. With a
16832 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16833 the cursor is before the first headline,
16834 display all fragments in the buffer.
16835 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16836 (interactive "P")
16837 (unless buffer-file-name
16838 (error "Can't preview LaTeX fragment in a non-file buffer"))
16839 (org-remove-latex-fragment-image-overlays)
16840 (save-excursion
16841 (save-restriction
16842 (let (beg end at msg)
16843 (cond
16844 ((or (equal subtree '(16))
16845 (not (save-excursion
16846 (re-search-backward org-outline-regexp-bol nil t))))
16847 (setq beg (point-min) end (point-max)
16848 msg "Creating images for buffer...%s"))
16849 ((equal subtree '(4))
16850 (org-back-to-heading)
16851 (setq beg (point) end (org-end-of-subtree t)
16852 msg "Creating images for subtree...%s"))
16854 (if (setq at (org-inside-LaTeX-fragment-p))
16855 (goto-char (max (point-min) (- (cdr at) 2)))
16856 (org-back-to-heading))
16857 (setq beg (point) end (progn (outline-next-heading) (point))
16858 msg (if at "Creating image...%s"
16859 "Creating images for entry...%s"))))
16860 (message msg "")
16861 (narrow-to-region beg end)
16862 (goto-char beg)
16863 (org-format-latex
16864 (concat "ltxpng/" (file-name-sans-extension
16865 (file-name-nondirectory
16866 buffer-file-name)))
16867 default-directory 'overlays msg at 'forbuffer 'dvipng)
16868 (message msg "done. Use `C-c C-c' to remove images.")))))
16870 (defvar org-latex-regexps
16871 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16872 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16873 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16874 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16875 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16876 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16877 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16878 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16879 "Regular expressions for matching embedded LaTeX.")
16881 (defvar org-export-have-math nil) ;; dynamic scoping
16882 (defun org-format-latex (prefix &optional dir overlays msg at
16883 forbuffer processing-type)
16884 "Replace LaTeX fragments with links to an image, and produce images.
16885 Some of the options can be changed using the variable
16886 `org-format-latex-options'."
16887 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16888 (let* ((prefixnodir (file-name-nondirectory prefix))
16889 (absprefix (expand-file-name prefix dir))
16890 (todir (file-name-directory absprefix))
16891 (opt org-format-latex-options)
16892 (matchers (plist-get opt :matchers))
16893 (re-list org-latex-regexps)
16894 (org-format-latex-header-extra
16895 (plist-get (org-infile-export-plist) :latex-header-extra))
16896 (cnt 0) txt hash link beg end re e checkdir
16897 executables-checked string
16898 m n block-type block linkfile movefile ov)
16899 ;; Check the different regular expressions
16900 (while (setq e (pop re-list))
16901 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16902 block (if block-type "\n\n" ""))
16903 (when (member m matchers)
16904 (goto-char (point-min))
16905 (while (re-search-forward re nil t)
16906 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16907 (not (get-text-property (match-beginning n)
16908 'org-protected))
16909 (or (not overlays)
16910 (not (eq (get-char-property (match-beginning n)
16911 'org-overlay-type)
16912 'org-latex-overlay))))
16913 (setq org-export-have-math t)
16914 (cond
16915 ((eq processing-type 'verbatim)
16916 ;; Leave the text verbatim, just protect it
16917 (add-text-properties (match-beginning n) (match-end n)
16918 '(org-protected t)))
16919 ((eq processing-type 'mathjax)
16920 ;; Prepare for MathJax processing
16921 (setq string (match-string n))
16922 (if (member m '("$" "$1"))
16923 (save-excursion
16924 (delete-region (match-beginning n) (match-end n))
16925 (goto-char (match-beginning n))
16926 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16927 "\\)")
16928 '(org-protected t))))
16929 (add-text-properties (match-beginning n) (match-end n)
16930 '(org-protected t))))
16931 ((eq processing-type 'dvipng)
16932 ;; Process to an image
16933 (setq txt (match-string n)
16934 beg (match-beginning n) end (match-end n)
16935 cnt (1+ cnt))
16936 (let (print-length print-level) ; make sure full list is printed
16937 (setq hash (sha1 (prin1-to-string
16938 (list org-format-latex-header
16939 org-format-latex-header-extra
16940 org-export-latex-default-packages-alist
16941 org-export-latex-packages-alist
16942 org-format-latex-options
16943 forbuffer txt)))
16944 linkfile (format "%s_%s.png" prefix hash)
16945 movefile (format "%s_%s.png" absprefix hash)))
16946 (setq link (concat block "[[file:" linkfile "]]" block))
16947 (if msg (message msg cnt))
16948 (goto-char beg)
16949 (unless checkdir ; make sure the directory exists
16950 (setq checkdir t)
16951 (or (file-directory-p todir) (make-directory todir t)))
16953 (unless executables-checked
16954 (org-check-external-command
16955 "latex" "needed to convert LaTeX fragments to images")
16956 (org-check-external-command
16957 "dvipng" "needed to convert LaTeX fragments to images")
16958 (setq executables-checked t))
16960 (unless (file-exists-p movefile)
16961 (org-create-formula-image
16962 txt movefile opt forbuffer))
16963 (if overlays
16964 (progn
16965 (mapc (lambda (o)
16966 (if (eq (overlay-get o 'org-overlay-type)
16967 'org-latex-overlay)
16968 (delete-overlay o)))
16969 (overlays-in beg end))
16970 (setq ov (make-overlay beg end))
16971 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16972 (if (featurep 'xemacs)
16973 (progn
16974 (overlay-put ov 'invisible t)
16975 (overlay-put
16976 ov 'end-glyph
16977 (make-glyph (vector 'png :file movefile))))
16978 (overlay-put
16979 ov 'display
16980 (list 'image :type 'png :file movefile :ascent 'center)))
16981 (push ov org-latex-fragment-image-overlays)
16982 (goto-char end))
16983 (delete-region beg end)
16984 (insert (org-add-props link
16985 (list 'org-latex-src
16986 (replace-regexp-in-string
16987 "\"" "" txt)
16988 'org-latex-src-embed-type
16989 (if block-type 'paragraph 'character))))))
16990 ((eq processing-type 'mathml)
16991 ;; Process to MathML
16992 (unless executables-checked
16993 (unless (save-match-data (org-format-latex-mathml-available-p))
16994 (error "LaTeX to MathML converter not configured"))
16995 (setq executables-checked t))
16996 (setq txt (match-string n)
16997 beg (match-beginning n) end (match-end n)
16998 cnt (1+ cnt))
16999 (if msg (message msg cnt))
17000 (goto-char beg)
17001 (delete-region beg end)
17002 (insert (org-format-latex-as-mathml
17003 txt block-type prefix dir)))
17005 (error "Unknown conversion type %s for latex fragments"
17006 processing-type)))))))))
17008 (defun org-create-math-formula (latex-frag &optional mathml-file)
17009 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17010 Use `org-latex-to-mathml-convert-command'. If the conversion is
17011 sucessful, return the portion between \"<math...> </math>\"
17012 elements otherwise return nil. When MATHML-FILE is specified,
17013 write the results in to that file. When invoked as an
17014 interactive command, prompt for LATEX-FRAG, with initial value
17015 set to the current active region and echo the results for user
17016 inspection."
17017 (interactive (list (let ((frag (when (region-active-p)
17018 (buffer-substring-no-properties
17019 (region-beginning) (region-end)))))
17020 (read-string "LaTeX Fragment: " frag nil frag))))
17021 (unless latex-frag (error "Invalid latex-frag"))
17022 (let* ((tmp-in-file (file-relative-name
17023 (make-temp-name (expand-file-name "ltxmathml-in"))))
17024 (ignore (write-region latex-frag nil tmp-in-file))
17025 (tmp-out-file (file-relative-name
17026 (make-temp-name (expand-file-name "ltxmathml-out"))))
17027 (cmd (format-spec
17028 org-latex-to-mathml-convert-command
17029 `((?j . ,(shell-quote-argument
17030 (expand-file-name org-latex-to-mathml-jar-file)))
17031 (?I . ,(shell-quote-argument tmp-in-file))
17032 (?o . ,(shell-quote-argument tmp-out-file)))))
17033 mathml shell-command-output)
17034 (when (org-called-interactively-p 'any)
17035 (unless (org-format-latex-mathml-available-p)
17036 (error "LaTeX to MathML converter not configured")))
17037 (message "Running %s" cmd)
17038 (setq shell-command-output (shell-command-to-string cmd))
17039 (setq mathml
17040 (when (file-readable-p tmp-out-file)
17041 (with-current-buffer (find-file-noselect tmp-out-file t)
17042 (goto-char (point-min))
17043 (when (re-search-forward
17044 (concat
17045 (regexp-quote
17046 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17047 "\\(.\\|\n\\)*"
17048 (regexp-quote "</math>")) nil t)
17049 (prog1 (match-string 0) (kill-buffer))))))
17050 (cond
17051 (mathml
17052 (setq mathml
17053 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17054 (when mathml-file
17055 (write-region mathml nil mathml-file))
17056 (when (org-called-interactively-p 'any)
17057 (message mathml)))
17058 ((message "LaTeX to MathML conversion failed")
17059 (message shell-command-output)))
17060 (delete-file tmp-in-file)
17061 (when (file-exists-p tmp-out-file)
17062 (delete-file tmp-out-file))
17063 mathml))
17065 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17066 prefix &optional dir)
17067 "Use `org-create-math-formula' but check local cache first."
17068 (let* ((absprefix (expand-file-name prefix dir))
17069 (print-length nil) (print-level nil)
17070 (formula-id (concat
17071 "formula-"
17072 (sha1
17073 (prin1-to-string
17074 (list latex-frag
17075 org-latex-to-mathml-convert-command)))))
17076 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17077 (formula-cache-dir (file-name-directory formula-cache)))
17079 (unless (file-directory-p formula-cache-dir)
17080 (make-directory formula-cache-dir t))
17082 (unless (file-exists-p formula-cache)
17083 (org-create-math-formula latex-frag formula-cache))
17085 (if (file-exists-p formula-cache)
17086 ;; Successful conversion. Return the link to MathML file.
17087 (org-add-props
17088 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17089 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17090 'org-latex-src-embed-type (if latex-frag-type
17091 'paragraph 'character)))
17092 ;; Failed conversion. Return the LaTeX fragment verbatim
17093 (add-text-properties
17094 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17095 latex-frag)))
17097 ;; This function borrows from Ganesh Swami's latex2png.el
17098 (defun org-create-formula-image (string tofile options buffer)
17099 "This calls dvipng."
17100 (require 'org-latex)
17101 (let* ((tmpdir (if (featurep 'xemacs)
17102 (temp-directory)
17103 temporary-file-directory))
17104 (texfilebase (make-temp-name
17105 (expand-file-name "orgtex" tmpdir)))
17106 (texfile (concat texfilebase ".tex"))
17107 (dvifile (concat texfilebase ".dvi"))
17108 (pngfile (concat texfilebase ".png"))
17109 (fnh (if (featurep 'xemacs)
17110 (font-height (get-face-font 'default))
17111 (face-attribute 'default :height nil)))
17112 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17113 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17114 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17115 "Black"))
17116 (bg (or (plist-get options (if buffer :background :html-background))
17117 "Transparent")))
17118 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17119 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17120 (with-temp-file texfile
17121 (insert (org-splice-latex-header
17122 org-format-latex-header
17123 org-export-latex-default-packages-alist
17124 org-export-latex-packages-alist t
17125 org-format-latex-header-extra))
17126 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17127 (require 'org-latex)
17128 (org-export-latex-fix-inputenc))
17129 (let ((dir default-directory))
17130 (condition-case nil
17131 (progn
17132 (cd tmpdir)
17133 (call-process "latex" nil nil nil texfile))
17134 (error nil))
17135 (cd dir))
17136 (if (not (file-exists-p dvifile))
17137 (progn (message "Failed to create dvi file from %s" texfile) nil)
17138 (condition-case nil
17139 (call-process "dvipng" nil nil nil
17140 "-fg" fg "-bg" bg
17141 "-D" dpi
17142 ;;"-x" scale "-y" scale
17143 "-T" "tight"
17144 "-o" pngfile
17145 dvifile)
17146 (error nil))
17147 (if (not (file-exists-p pngfile))
17148 (if org-format-latex-signal-error
17149 (error "Failed to create png file from %s" texfile)
17150 (message "Failed to create png file from %s" texfile)
17151 nil)
17152 ;; Use the requested file name and clean up
17153 (copy-file pngfile tofile 'replace)
17154 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17155 (delete-file (concat texfilebase e)))
17156 pngfile))))
17158 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17159 "Fill a LaTeX header template TPL.
17160 In the template, the following place holders will be recognized:
17162 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17163 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17164 [PACKAGES] \\usepackage statements for PKG
17165 [NO-PACKAGES] do not include PKG
17166 [EXTRA] the string EXTRA
17167 [NO-EXTRA] do not include EXTRA
17169 For backward compatibility, if both the positive and the negative place
17170 holder is missing, the positive one (without the \"NO-\") will be
17171 assumed to be present at the end of the template.
17172 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17173 EXTRA is a string.
17174 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17175 (let (rpl (end ""))
17176 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17177 (setq rpl (if (or (match-end 1) (not def-pkg))
17178 "" (org-latex-packages-to-string def-pkg snippets-p t))
17179 tpl (replace-match rpl t t tpl))
17180 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17182 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17183 (setq rpl (if (or (match-end 1) (not pkg))
17184 "" (org-latex-packages-to-string pkg snippets-p t))
17185 tpl (replace-match rpl t t tpl))
17186 (if pkg (setq end
17187 (concat end "\n"
17188 (org-latex-packages-to-string pkg snippets-p)))))
17190 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17191 (setq rpl (if (or (match-end 1) (not extra))
17192 "" (concat extra "\n"))
17193 tpl (replace-match rpl t t tpl))
17194 (if (and extra (string-match "\\S-" extra))
17195 (setq end (concat end "\n" extra))))
17197 (if (string-match "\\S-" end)
17198 (concat tpl "\n" end)
17199 tpl)))
17201 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17202 "Turn an alist of packages into a string with the \\usepackage macros."
17203 (setq pkg (mapconcat (lambda(p)
17204 (cond
17205 ((stringp p) p)
17206 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17207 (format "%% Package %s omitted" (cadr p)))
17208 ((equal "" (car p))
17209 (format "\\usepackage{%s}" (cadr p)))
17211 (format "\\usepackage[%s]{%s}"
17212 (car p) (cadr p)))))
17214 "\n"))
17215 (if newline (concat pkg "\n") pkg))
17217 (defun org-dvipng-color (attr)
17218 "Return an rgb color specification for dvipng."
17219 (apply 'format "rgb %s %s %s"
17220 (mapcar 'org-normalize-color
17221 (color-values (face-attribute 'default attr nil)))))
17223 (defun org-normalize-color (value)
17224 "Return string to be used as color value for an RGB component."
17225 (format "%g" (/ value 65535.0)))
17227 ;; Image display
17230 (defvar org-inline-image-overlays nil)
17231 (make-variable-buffer-local 'org-inline-image-overlays)
17233 (defun org-toggle-inline-images (&optional include-linked)
17234 "Toggle the display of inline images.
17235 INCLUDE-LINKED is passed to `org-display-inline-images'."
17236 (interactive "P")
17237 (if org-inline-image-overlays
17238 (progn
17239 (org-remove-inline-images)
17240 (message "Inline image display turned off"))
17241 (org-display-inline-images include-linked)
17242 (if org-inline-image-overlays
17243 (message "%d images displayed inline"
17244 (length org-inline-image-overlays))
17245 (message "No images to display inline"))))
17247 (defun org-display-inline-images (&optional include-linked refresh beg end)
17248 "Display inline images.
17249 Normally only links without a description part are inlined, because this
17250 is how it will work for export. When INCLUDE-LINKED is set, also links
17251 with a description part will be inlined. This can be nice for a quick
17252 look at those images, but it does not reflect what exported files will look
17253 like.
17254 When REFRESH is set, refresh existing images between BEG and END.
17255 This will create new image displays only if necessary.
17256 BEG and END default to the buffer boundaries."
17257 (interactive "P")
17258 (unless refresh
17259 (org-remove-inline-images)
17260 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17261 (save-excursion
17262 (save-restriction
17263 (widen)
17264 (setq beg (or beg (point-min)) end (or end (point-max)))
17265 (goto-char (point-min))
17266 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17267 (substring (org-image-file-name-regexp) 0 -2)
17268 "\\)\\]" (if include-linked "" "\\]")))
17269 old file ov img)
17270 (while (re-search-forward re end t)
17271 (setq old (get-char-property-and-overlay (match-beginning 1)
17272 'org-image-overlay))
17273 (setq file (expand-file-name
17274 (concat (or (match-string 3) "") (match-string 4))))
17275 (when (file-exists-p file)
17276 (if (and (car-safe old) refresh)
17277 (image-refresh (overlay-get (cdr old) 'display))
17278 (setq img (save-match-data (create-image file)))
17279 (when img
17280 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17281 (overlay-put ov 'display img)
17282 (overlay-put ov 'face 'default)
17283 (overlay-put ov 'org-image-overlay t)
17284 (overlay-put ov 'modification-hooks
17285 (list 'org-display-inline-modification-hook))
17286 (push ov org-inline-image-overlays)))))))))
17288 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17289 "Remove inline-display overlay if a corresponding region is modified."
17290 (let ((inhibit-modification-hooks t))
17291 (when (and ov after)
17292 (delete ov org-inline-image-overlays)
17293 (delete-overlay ov))))
17295 (defun org-remove-inline-images ()
17296 "Remove inline display of images."
17297 (interactive)
17298 (mapc 'delete-overlay org-inline-image-overlays)
17299 (setq org-inline-image-overlays nil))
17301 ;;;; Key bindings
17303 ;; Outline functions from `outline-mode-prefix-map'
17304 ;; that can be remapped in Org:
17305 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17306 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17307 (define-key org-mode-map [remap outline-forward-same-level]
17308 'org-forward-same-level)
17309 (define-key org-mode-map [remap outline-backward-same-level]
17310 'org-backward-same-level)
17311 (define-key org-mode-map [remap show-branches]
17312 'org-kill-note-or-show-branches)
17313 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17314 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17315 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17317 ;; Outline functions from `outline-mode-prefix-map'
17318 ;; that can not be remapped in Org:
17319 ;; - the column "key binding" shows whether the Outline function is still
17320 ;; available in Org mode on the same key that it has been bound to in
17321 ;; Outline mode:
17322 ;; - "overridden": key used for a different functionality in Org mode
17323 ;; - else: key still bound to the same Outline function in Org mode
17324 ;; | Outline function | key binding | Org replacement |
17325 ;; |------------------------------------+-------------+-----------------------|
17326 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17327 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17328 ;; | `show-children' | `C-c C-i' | visibility cycling |
17329 ;; | `hide-subtree' | overridden | visibility cycling |
17330 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17331 ;; | `hide-body' | overridden | no replacement |
17332 ;; | `show-all' | overridden | no replacement |
17333 ;; | `hide-entry' | overridden | visibility cycling |
17334 ;; | `show-entry' | overridden | no replacement |
17335 ;; | `hide-leaves' | overridden | no replacement |
17336 ;; | `hide-sublevels' | overridden | no replacement |
17337 ;; | `hide-other' | overridden | no replacement |
17338 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17339 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17341 ;; Make `C-c C-x' a prefix key
17342 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17344 ;; TAB key with modifiers
17345 (org-defkey org-mode-map "\C-i" 'org-cycle)
17346 (org-defkey org-mode-map [(tab)] 'org-cycle)
17347 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17348 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17349 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17350 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17351 ;; The following line is necessary under Suse GNU/Linux
17352 (unless (featurep 'xemacs)
17353 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17354 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17355 (define-key org-mode-map [backtab] 'org-shifttab)
17357 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17358 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17359 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17361 ;; Cursor keys with modifiers
17362 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17363 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17364 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17365 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17367 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17368 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17369 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17370 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17372 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17373 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17374 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17375 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17377 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17378 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17379 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17380 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17382 ;; Babel keys
17383 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17384 (mapc (lambda (pair)
17385 (define-key org-babel-map (car pair) (cdr pair)))
17386 org-babel-key-bindings)
17388 ;;; Extra keys for tty access.
17389 ;; We only set them when really needed because otherwise the
17390 ;; menus don't show the simple keys
17392 (when (or org-use-extra-keys
17393 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17394 (not window-system))
17395 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17396 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17397 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17398 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17399 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17400 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17401 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17402 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17403 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17404 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17405 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17406 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17407 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17408 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17409 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17410 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17411 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17412 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17413 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17414 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17415 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17416 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17417 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17418 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17419 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17420 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17421 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17422 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17424 ;; All the other keys
17426 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17427 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17428 (if (boundp 'narrow-map)
17429 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17430 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17431 (if (boundp 'narrow-map)
17432 (org-defkey narrow-map "b" 'org-narrow-to-block)
17433 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17434 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17435 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17436 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17437 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17438 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17439 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17440 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17441 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17442 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17443 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17444 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17445 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17446 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17447 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17448 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17449 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17450 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17451 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17452 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17453 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17454 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17455 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17456 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17457 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17458 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17459 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17460 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17461 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17462 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17463 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17464 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17465 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17466 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17467 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17468 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17469 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17470 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17471 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17472 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17473 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17474 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17475 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17476 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17477 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17478 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17479 (org-defkey org-mode-map "\C-c^" 'org-sort)
17480 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17481 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17482 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17483 (org-defkey org-mode-map "\C-m" 'org-return)
17484 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17485 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17486 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17487 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17488 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17489 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17490 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17491 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17492 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17493 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17494 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17495 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17496 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17497 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17498 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17499 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17500 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17501 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17502 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17503 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17504 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17505 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17506 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17508 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17509 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17510 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17511 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17513 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17514 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17515 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17516 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17517 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17518 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17519 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17520 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17521 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17522 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17523 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17524 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17525 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17526 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17527 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17528 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17529 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17530 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17532 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17533 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17534 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17535 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17536 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17538 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17540 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17542 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17543 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17545 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17548 (when (featurep 'xemacs)
17549 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17552 (defconst org-speed-commands-default
17554 ("Outline Navigation")
17555 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17556 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17557 ("f" . (org-speed-move-safe 'org-forward-same-level))
17558 ("b" . (org-speed-move-safe 'org-backward-same-level))
17559 ("u" . (org-speed-move-safe 'outline-up-heading))
17560 ("j" . org-goto)
17561 ("g" . (org-refile t))
17562 ("Outline Visibility")
17563 ("c" . org-cycle)
17564 ("C" . org-shifttab)
17565 (" " . org-display-outline-path)
17566 ("Outline Structure Editing")
17567 ("U" . org-shiftmetaup)
17568 ("D" . org-shiftmetadown)
17569 ("r" . org-metaright)
17570 ("l" . org-metaleft)
17571 ("R" . org-shiftmetaright)
17572 ("L" . org-shiftmetaleft)
17573 ("i" . (progn (forward-char 1) (call-interactively
17574 'org-insert-heading-respect-content)))
17575 ("^" . org-sort)
17576 ("w" . org-refile)
17577 ("a" . org-archive-subtree-default-with-confirmation)
17578 ("." . org-mark-subtree)
17579 ("Clock Commands")
17580 ("I" . org-clock-in)
17581 ("O" . org-clock-out)
17582 ("Meta Data Editing")
17583 ("t" . org-todo)
17584 ("0" . (org-priority ?\ ))
17585 ("1" . (org-priority ?A))
17586 ("2" . (org-priority ?B))
17587 ("3" . (org-priority ?C))
17588 (";" . org-set-tags-command)
17589 ("e" . org-set-effort)
17590 ("Agenda Views etc")
17591 ("v" . org-agenda)
17592 ("/" . org-sparse-tree)
17593 ("Misc")
17594 ("o" . org-open-at-point)
17595 ("?" . org-speed-command-help)
17596 ("<" . (org-agenda-set-restriction-lock 'subtree))
17597 (">" . (org-agenda-remove-restriction-lock))
17599 "The default speed commands.")
17601 (defun org-print-speed-command (e)
17602 (if (> (length (car e)) 1)
17603 (progn
17604 (princ "\n")
17605 (princ (car e))
17606 (princ "\n")
17607 (princ (make-string (length (car e)) ?-))
17608 (princ "\n"))
17609 (princ (car e))
17610 (princ " ")
17611 (if (symbolp (cdr e))
17612 (princ (symbol-name (cdr e)))
17613 (prin1 (cdr e)))
17614 (princ "\n")))
17616 (defun org-speed-command-help ()
17617 "Show the available speed commands."
17618 (interactive)
17619 (if (not org-use-speed-commands)
17620 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17621 (with-output-to-temp-buffer "*Help*"
17622 (princ "User-defined Speed commands\n===========================\n")
17623 (mapc 'org-print-speed-command org-speed-commands-user)
17624 (princ "\n")
17625 (princ "Built-in Speed commands\n=======================\n")
17626 (mapc 'org-print-speed-command org-speed-commands-default))
17627 (with-current-buffer "*Help*"
17628 (setq truncate-lines t))))
17630 (defun org-speed-move-safe (cmd)
17631 "Execute CMD, but make sure that the cursor always ends up in a headline.
17632 If not, return to the original position and throw an error."
17633 (interactive)
17634 (let ((pos (point)))
17635 (call-interactively cmd)
17636 (unless (and (bolp) (org-at-heading-p))
17637 (goto-char pos)
17638 (error "Boundary reached while executing %s" cmd))))
17640 (defvar org-self-insert-command-undo-counter 0)
17642 (defvar org-table-auto-blank-field) ; defined in org-table.el
17643 (defvar org-speed-command nil)
17645 (defun org-speed-command-default-hook (keys)
17646 "Hook for activating single-letter speed commands.
17647 `org-speed-commands-default' specifies a minimal command set.
17648 Use `org-speed-commands-user' for further customization."
17649 (when (or (and (bolp) (looking-at org-outline-regexp))
17650 (and (functionp org-use-speed-commands)
17651 (funcall org-use-speed-commands)))
17652 (cdr (assoc keys (append org-speed-commands-user
17653 org-speed-commands-default)))))
17655 (defun org-babel-speed-command-hook (keys)
17656 "Hook for activating single-letter code block commands."
17657 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17658 (cdr (assoc keys org-babel-key-bindings))))
17660 (defcustom org-speed-command-hook
17661 '(org-speed-command-default-hook org-babel-speed-command-hook)
17662 "Hook for activating speed commands at strategic locations.
17663 Hook functions are called in sequence until a valid handler is
17664 found.
17666 Each hook takes a single argument, a user-pressed command key
17667 which is also a `self-insert-command' from the global map.
17669 Within the hook, examine the cursor position and the command key
17670 and return nil or a valid handler as appropriate. Handler could
17671 be one of an interactive command, a function, or a form.
17673 Set `org-use-speed-commands' to non-nil value to enable this
17674 hook. The default setting is `org-speed-command-default-hook'."
17675 :group 'org-structure
17676 :version "24.1"
17677 :type 'hook)
17679 (defun org-self-insert-command (N)
17680 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17681 If the cursor is in a table looking at whitespace, the whitespace is
17682 overwritten, and the table is not marked as requiring realignment."
17683 (interactive "p")
17684 (org-check-before-invisible-edit 'insert)
17685 (cond
17686 ((and org-use-speed-commands
17687 (setq org-speed-command
17688 (run-hook-with-args-until-success
17689 'org-speed-command-hook (this-command-keys))))
17690 (cond
17691 ((commandp org-speed-command)
17692 (setq this-command org-speed-command)
17693 (call-interactively org-speed-command))
17694 ((functionp org-speed-command)
17695 (funcall org-speed-command))
17696 ((and org-speed-command (listp org-speed-command))
17697 (eval org-speed-command))
17698 (t (let (org-use-speed-commands)
17699 (call-interactively 'org-self-insert-command)))))
17700 ((and
17701 (org-table-p)
17702 (progn
17703 ;; check if we blank the field, and if that triggers align
17704 (and (featurep 'org-table) org-table-auto-blank-field
17705 (member last-command
17706 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17707 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17708 ;; got extra space, this field does not determine column width
17709 (let (org-table-may-need-update) (org-table-blank-field))
17710 ;; no extra space, this field may determine column width
17711 (org-table-blank-field)))
17713 (eq N 1)
17714 (looking-at "[^|\n]* |"))
17715 (let (org-table-may-need-update)
17716 (goto-char (1- (match-end 0)))
17717 (delete-char -1)
17718 (goto-char (match-beginning 0))
17719 (self-insert-command N)))
17721 (setq org-table-may-need-update t)
17722 (self-insert-command N)
17723 (org-fix-tags-on-the-fly)
17724 (if org-self-insert-cluster-for-undo
17725 (if (not (eq last-command 'org-self-insert-command))
17726 (setq org-self-insert-command-undo-counter 1)
17727 (if (>= org-self-insert-command-undo-counter 20)
17728 (setq org-self-insert-command-undo-counter 1)
17729 (and (> org-self-insert-command-undo-counter 0)
17730 buffer-undo-list (listp buffer-undo-list)
17731 (not (cadr buffer-undo-list)) ; remove nil entry
17732 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17733 (setq org-self-insert-command-undo-counter
17734 (1+ org-self-insert-command-undo-counter))))))))
17736 (defun org-check-before-invisible-edit (kind)
17737 "Check is editing if kind KIND would be dangerous with invisible text around.
17738 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17739 ;; First, try to get out of here as quickly as possible, to reduce overhead
17740 (if (and org-catch-invisible-edits
17741 (or (not (boundp 'visible-mode)) (not visible-mode))
17742 (or (get-char-property (point) 'invisible)
17743 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17744 ;; OK, we need to take a closer look
17745 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17746 (invisible-before-point (if (bobp) nil (get-char-property
17747 (1- (point)) 'invisible)))
17748 (border-and-ok-direction
17750 ;; Check if we are acting predictably before invisible text
17751 (and invisible-at-point (not invisible-before-point)
17752 (memq kind '(insert delete-backward)))
17753 ;; Check if we are acting predictably after invisible text
17754 ;; This works not well, and I have turned it off. It seems
17755 ;; better to always show and stop after invisible text.
17756 ;; (and (not invisible-at-point) invisible-before-point
17757 ;; (memq kind '(insert delete)))
17760 (when (or (memq invisible-at-point '(outline org-hide-block))
17761 (memq invisible-before-point '(outline org-hide-block)))
17762 (if (eq org-catch-invisible-edits 'error)
17763 (error "Editing in invisible areas is prohibited - make visible first"))
17764 ;; Make the area visible
17765 (save-excursion
17766 (if invisible-before-point
17767 (goto-char (previous-single-char-property-change
17768 (point) 'invisible)))
17769 (org-cycle))
17770 (cond
17771 ((eq org-catch-invisible-edits 'show)
17772 ;; That's it, we do the edit after showing
17773 (message
17774 "Unfolding invisible region around point before editing")
17775 (sit-for 1))
17776 ((and (eq org-catch-invisible-edits 'smart)
17777 border-and-ok-direction)
17778 (message "Unfolding invisible region around point before editing"))
17780 ;; Don't do the edit, make the user repeat it in full visibility
17781 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17783 (defun org-fix-tags-on-the-fly ()
17784 (when (and (equal (char-after (point-at-bol)) ?*)
17785 (org-at-heading-p))
17786 (org-align-tags-here org-tags-column)))
17788 (defun org-delete-backward-char (N)
17789 "Like `delete-backward-char', insert whitespace at field end in tables.
17790 When deleting backwards, in tables this function will insert whitespace in
17791 front of the next \"|\" separator, to keep the table aligned. The table will
17792 still be marked for re-alignment if the field did fill the entire column,
17793 because, in this case the deletion might narrow the column."
17794 (interactive "p")
17795 (org-check-before-invisible-edit 'delete-backward)
17796 (if (and (org-table-p)
17797 (eq N 1)
17798 (string-match "|" (buffer-substring (point-at-bol) (point)))
17799 (looking-at ".*?|"))
17800 (let ((pos (point))
17801 (noalign (looking-at "[^|\n\r]* |"))
17802 (c org-table-may-need-update))
17803 (backward-delete-char N)
17804 (if (not overwrite-mode)
17805 (progn
17806 (skip-chars-forward "^|")
17807 (insert " ")
17808 (goto-char (1- pos))))
17809 ;; noalign: if there were two spaces at the end, this field
17810 ;; does not determine the width of the column.
17811 (if noalign (setq org-table-may-need-update c)))
17812 (backward-delete-char N)
17813 (org-fix-tags-on-the-fly)))
17815 (defun org-delete-char (N)
17816 "Like `delete-char', but insert whitespace at field end in tables.
17817 When deleting characters, in tables this function will insert whitespace in
17818 front of the next \"|\" separator, to keep the table aligned. The table will
17819 still be marked for re-alignment if the field did fill the entire column,
17820 because, in this case the deletion might narrow the column."
17821 (interactive "p")
17822 (org-check-before-invisible-edit 'delete)
17823 (if (and (org-table-p)
17824 (not (bolp))
17825 (not (= (char-after) ?|))
17826 (eq N 1))
17827 (if (looking-at ".*?|")
17828 (let ((pos (point))
17829 (noalign (looking-at "[^|\n\r]* |"))
17830 (c org-table-may-need-update))
17831 (replace-match (concat
17832 (substring (match-string 0) 1 -1)
17833 " |"))
17834 (goto-char pos)
17835 ;; noalign: if there were two spaces at the end, this field
17836 ;; does not determine the width of the column.
17837 (if noalign (setq org-table-may-need-update c)))
17838 (delete-char N))
17839 (delete-char N)
17840 (org-fix-tags-on-the-fly)))
17842 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17843 (put 'org-self-insert-command 'delete-selection t)
17844 (put 'orgtbl-self-insert-command 'delete-selection t)
17845 (put 'org-delete-char 'delete-selection 'supersede)
17846 (put 'org-delete-backward-char 'delete-selection 'supersede)
17847 (put 'org-yank 'delete-selection 'yank)
17849 ;; Make `flyspell-mode' delay after some commands
17850 (put 'org-self-insert-command 'flyspell-delayed t)
17851 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17852 (put 'org-delete-char 'flyspell-delayed t)
17853 (put 'org-delete-backward-char 'flyspell-delayed t)
17855 ;; Make pabbrev-mode expand after org-mode commands
17856 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17857 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17859 ;; How to do this: Measure non-white length of current string
17860 ;; If equal to column width, we should realign.
17862 (defun org-remap (map &rest commands)
17863 "In MAP, remap the functions given in COMMANDS.
17864 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17865 (let (new old)
17866 (while commands
17867 (setq old (pop commands) new (pop commands))
17868 (if (fboundp 'command-remapping)
17869 (org-defkey map (vector 'remap old) new)
17870 (substitute-key-definition old new map global-map)))))
17872 (when (eq org-enable-table-editor 'optimized)
17873 ;; If the user wants maximum table support, we need to hijack
17874 ;; some standard editing functions
17875 (org-remap org-mode-map
17876 'self-insert-command 'org-self-insert-command
17877 'delete-char 'org-delete-char
17878 'delete-backward-char 'org-delete-backward-char)
17879 (org-defkey org-mode-map "|" 'org-force-self-insert))
17881 (defvar org-ctrl-c-ctrl-c-hook nil
17882 "Hook for functions attaching themselves to `C-c C-c'.
17884 This can be used to add additional functionality to the C-c C-c
17885 key which executes context-dependent commands. This hook is run
17886 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17887 run after the last test.
17889 Each function will be called with no arguments. The function
17890 must check if the context is appropriate for it to act. If yes,
17891 it should do its thing and then return a non-nil value. If the
17892 context is wrong, just do nothing and return nil.")
17894 (defvar org-ctrl-c-ctrl-c-final-hook nil
17895 "Hook for functions attaching themselves to `C-c C-c'.
17897 This can be used to add additional functionality to the C-c C-c
17898 key which executes context-dependent commands. This hook is run
17899 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17900 before the first test.
17902 Each function will be called with no arguments. The function
17903 must check if the context is appropriate for it to act. If yes,
17904 it should do its thing and then return a non-nil value. If the
17905 context is wrong, just do nothing and return nil.")
17907 (defvar org-tab-first-hook nil
17908 "Hook for functions to attach themselves to TAB.
17909 See `org-ctrl-c-ctrl-c-hook' for more information.
17910 This hook runs as the first action when TAB is pressed, even before
17911 `org-cycle' messes around with the `outline-regexp' to cater for
17912 inline tasks and plain list item folding.
17913 If any function in this hook returns t, any other actions that
17914 would have been caused by TAB (such as table field motion or visibility
17915 cycling) will not occur.")
17917 (defvar org-tab-after-check-for-table-hook nil
17918 "Hook for functions to attach themselves to TAB.
17919 See `org-ctrl-c-ctrl-c-hook' for more information.
17920 This hook runs after it has been established that the cursor is not in a
17921 table, but before checking if the cursor is in a headline or if global cycling
17922 should be done.
17923 If any function in this hook returns t, not other actions like visibility
17924 cycling will be done.")
17926 (defvar org-tab-after-check-for-cycling-hook nil
17927 "Hook for functions to attach themselves to TAB.
17928 See `org-ctrl-c-ctrl-c-hook' for more information.
17929 This hook runs after it has been established that not table field motion and
17930 not visibility should be done because of current context. This is probably
17931 the place where a package like yasnippets can hook in.")
17933 (defvar org-tab-before-tab-emulation-hook nil
17934 "Hook for functions to attach themselves to TAB.
17935 See `org-ctrl-c-ctrl-c-hook' for more information.
17936 This hook runs after every other options for TAB have been exhausted, but
17937 before indentation and \t insertion takes place.")
17939 (defvar org-metaleft-hook nil
17940 "Hook for functions attaching themselves to `M-left'.
17941 See `org-ctrl-c-ctrl-c-hook' for more information.")
17942 (defvar org-metaright-hook nil
17943 "Hook for functions attaching themselves to `M-right'.
17944 See `org-ctrl-c-ctrl-c-hook' for more information.")
17945 (defvar org-metaup-hook nil
17946 "Hook for functions attaching themselves to `M-up'.
17947 See `org-ctrl-c-ctrl-c-hook' for more information.")
17948 (defvar org-metadown-hook nil
17949 "Hook for functions attaching themselves to `M-down'.
17950 See `org-ctrl-c-ctrl-c-hook' for more information.")
17951 (defvar org-shiftmetaleft-hook nil
17952 "Hook for functions attaching themselves to `M-S-left'.
17953 See `org-ctrl-c-ctrl-c-hook' for more information.")
17954 (defvar org-shiftmetaright-hook nil
17955 "Hook for functions attaching themselves to `M-S-right'.
17956 See `org-ctrl-c-ctrl-c-hook' for more information.")
17957 (defvar org-shiftmetaup-hook nil
17958 "Hook for functions attaching themselves to `M-S-up'.
17959 See `org-ctrl-c-ctrl-c-hook' for more information.")
17960 (defvar org-shiftmetadown-hook nil
17961 "Hook for functions attaching themselves to `M-S-down'.
17962 See `org-ctrl-c-ctrl-c-hook' for more information.")
17963 (defvar org-metareturn-hook nil
17964 "Hook for functions attaching themselves to `M-RET'.
17965 See `org-ctrl-c-ctrl-c-hook' for more information.")
17966 (defvar org-shiftup-hook nil
17967 "Hook for functions attaching themselves to `S-up'.
17968 See `org-ctrl-c-ctrl-c-hook' for more information.")
17969 (defvar org-shiftup-final-hook nil
17970 "Hook for functions attaching themselves to `S-up'.
17971 This one runs after all other options except shift-select have been excluded.
17972 See `org-ctrl-c-ctrl-c-hook' for more information.")
17973 (defvar org-shiftdown-hook nil
17974 "Hook for functions attaching themselves to `S-down'.
17975 See `org-ctrl-c-ctrl-c-hook' for more information.")
17976 (defvar org-shiftdown-final-hook nil
17977 "Hook for functions attaching themselves to `S-down'.
17978 This one runs after all other options except shift-select have been excluded.
17979 See `org-ctrl-c-ctrl-c-hook' for more information.")
17980 (defvar org-shiftleft-hook nil
17981 "Hook for functions attaching themselves to `S-left'.
17982 See `org-ctrl-c-ctrl-c-hook' for more information.")
17983 (defvar org-shiftleft-final-hook nil
17984 "Hook for functions attaching themselves to `S-left'.
17985 This one runs after all other options except shift-select have been excluded.
17986 See `org-ctrl-c-ctrl-c-hook' for more information.")
17987 (defvar org-shiftright-hook nil
17988 "Hook for functions attaching themselves to `S-right'.
17989 See `org-ctrl-c-ctrl-c-hook' for more information.")
17990 (defvar org-shiftright-final-hook nil
17991 "Hook for functions attaching themselves to `S-right'.
17992 This one runs after all other options except shift-select have been excluded.
17993 See `org-ctrl-c-ctrl-c-hook' for more information.")
17995 (defun org-modifier-cursor-error ()
17996 "Throw an error, a modified cursor command was applied in wrong context."
17997 (error "This command is active in special context like tables, headlines or items"))
17999 (defun org-shiftselect-error ()
18000 "Throw an error because Shift-Cursor command was applied in wrong context."
18001 (if (and (boundp 'shift-select-mode) shift-select-mode)
18002 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18003 (error "This command works only in special context like headlines or timestamps")))
18005 (defun org-call-for-shift-select (cmd)
18006 (let ((this-command-keys-shift-translated t))
18007 (call-interactively cmd)))
18009 (defun org-shifttab (&optional arg)
18010 "Global visibility cycling or move to previous table field.
18011 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18012 on context.
18013 See the individual commands for more information."
18014 (interactive "P")
18015 (cond
18016 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18017 ((integerp arg)
18018 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18019 (message "Content view to level: %d" arg)
18020 (org-content (prefix-numeric-value arg2))
18021 (setq org-cycle-global-status 'overview)))
18022 (t (call-interactively 'org-global-cycle))))
18024 (defun org-shiftmetaleft ()
18025 "Promote subtree or delete table column.
18026 Calls `org-promote-subtree', `org-outdent-item',
18027 or `org-table-delete-column', depending on context.
18028 See the individual commands for more information."
18029 (interactive)
18030 (cond
18031 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18032 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18033 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18034 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
18035 (t (org-modifier-cursor-error))))
18037 (defun org-shiftmetaright ()
18038 "Demote subtree or insert table column.
18039 Calls `org-demote-subtree', `org-indent-item',
18040 or `org-table-insert-column', depending on context.
18041 See the individual commands for more information."
18042 (interactive)
18043 (cond
18044 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18045 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18046 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18047 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
18048 (t (org-modifier-cursor-error))))
18050 (defun org-shiftmetaup (&optional arg)
18051 "Move subtree up or kill table row.
18052 Calls `org-move-subtree-up' or `org-table-kill-row' or
18053 `org-move-item-up' depending on context. See the individual commands
18054 for more information."
18055 (interactive "P")
18056 (cond
18057 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18058 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18059 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18060 ((org-at-item-p) (call-interactively 'org-move-item-up))
18061 (t (org-modifier-cursor-error))))
18063 (defun org-shiftmetadown (&optional arg)
18064 "Move subtree down or insert table row.
18065 Calls `org-move-subtree-down' or `org-table-insert-row' or
18066 `org-move-item-down', depending on context. See the individual
18067 commands for more information."
18068 (interactive "P")
18069 (cond
18070 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18071 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18072 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18073 ((org-at-item-p) (call-interactively 'org-move-item-down))
18074 (t (org-modifier-cursor-error))))
18076 (defsubst org-hidden-tree-error ()
18077 (error
18078 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18080 (defun org-metaleft (&optional arg)
18081 "Promote heading or move table column to left.
18082 Calls `org-do-promote' or `org-table-move-column', depending on context.
18083 With no specific context, calls the Emacs default `backward-word'.
18084 See the individual commands for more information."
18085 (interactive "P")
18086 (cond
18087 ((run-hook-with-args-until-success 'org-metaleft-hook))
18088 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18089 ((org-with-limited-levels
18090 (or (org-at-heading-p)
18091 (and (org-region-active-p)
18092 (save-excursion
18093 (goto-char (region-beginning))
18094 (org-at-heading-p)))))
18095 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18096 (call-interactively 'org-do-promote))
18097 ;; At an inline task.
18098 ((org-at-heading-p)
18099 (call-interactively 'org-inlinetask-promote))
18100 ((or (org-at-item-p)
18101 (and (org-region-active-p)
18102 (save-excursion
18103 (goto-char (region-beginning))
18104 (org-at-item-p))))
18105 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18106 (call-interactively 'org-outdent-item))
18107 (t (call-interactively 'backward-word))))
18109 (defun org-metaright (&optional arg)
18110 "Demote a subtree, a list item or move table column to right.
18111 In front of a drawer or a block keyword, indent it correctly.
18112 With no specific context, calls the Emacs default `forward-word'.
18113 See the individual commands for more information."
18114 (interactive "P")
18115 (cond
18116 ((run-hook-with-args-until-success 'org-metaright-hook))
18117 ((org-at-table-p) (call-interactively 'org-table-move-column))
18118 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18119 ((org-at-block-p) (call-interactively 'org-indent-block))
18120 ((org-with-limited-levels
18121 (or (org-at-heading-p)
18122 (and (org-region-active-p)
18123 (save-excursion
18124 (goto-char (region-beginning))
18125 (org-at-heading-p)))))
18126 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18127 (call-interactively 'org-do-demote))
18128 ;; At an inline task.
18129 ((org-at-heading-p)
18130 (call-interactively 'org-inlinetask-demote))
18131 ((or (org-at-item-p)
18132 (and (org-region-active-p)
18133 (save-excursion
18134 (goto-char (region-beginning))
18135 (org-at-item-p))))
18136 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18137 (call-interactively 'org-indent-item))
18138 (t (call-interactively 'forward-word))))
18140 (defun org-check-for-hidden (what)
18141 "Check if there are hidden headlines/items in the current visual line.
18142 WHAT can be either `headlines' or `items'. If the current line is
18143 an outline or item heading and it has a folded subtree below it,
18144 this function returns t, nil otherwise."
18145 (let ((re (cond
18146 ((eq what 'headlines) org-outline-regexp-bol)
18147 ((eq what 'items) (org-item-beginning-re))
18148 (t (error "This should not happen"))))
18149 beg end)
18150 (save-excursion
18151 (catch 'exit
18152 (unless (org-region-active-p)
18153 (setq beg (point-at-bol))
18154 (beginning-of-line 2)
18155 (while (and (not (eobp)) ;; this is like `next-line'
18156 (get-char-property (1- (point)) 'invisible))
18157 (beginning-of-line 2))
18158 (setq end (point))
18159 (goto-char beg)
18160 (goto-char (point-at-eol))
18161 (setq end (max end (point)))
18162 (while (re-search-forward re end t)
18163 (if (get-char-property (match-beginning 0) 'invisible)
18164 (throw 'exit t))))
18165 nil))))
18167 (defun org-metaup (&optional arg)
18168 "Move subtree up or move table row up.
18169 Calls `org-move-subtree-up' or `org-table-move-row' or
18170 `org-move-item-up', depending on context. See the individual commands
18171 for more information."
18172 (interactive "P")
18173 (cond
18174 ((run-hook-with-args-until-success 'org-metaup-hook))
18175 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18176 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18177 ((org-at-item-p) (call-interactively 'org-move-item-up))
18178 (t (transpose-lines 1) (beginning-of-line -1))))
18180 (defun org-metadown (&optional arg)
18181 "Move subtree down or move table row down.
18182 Calls `org-move-subtree-down' or `org-table-move-row' or
18183 `org-move-item-down', depending on context. See the individual
18184 commands for more information."
18185 (interactive "P")
18186 (cond
18187 ((run-hook-with-args-until-success 'org-metadown-hook))
18188 ((org-at-table-p) (call-interactively 'org-table-move-row))
18189 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18190 ((org-at-item-p) (call-interactively 'org-move-item-down))
18191 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18193 (defun org-shiftup (&optional arg)
18194 "Increase item in timestamp or increase priority of current headline.
18195 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18196 depending on context. See the individual commands for more information."
18197 (interactive "P")
18198 (cond
18199 ((run-hook-with-args-until-success 'org-shiftup-hook))
18200 ((and org-support-shift-select (org-region-active-p))
18201 (org-call-for-shift-select 'previous-line))
18202 ((org-at-timestamp-p t)
18203 (call-interactively (if org-edit-timestamp-down-means-later
18204 'org-timestamp-down 'org-timestamp-up)))
18205 ((and (not (eq org-support-shift-select 'always))
18206 org-enable-priority-commands
18207 (org-at-heading-p))
18208 (call-interactively 'org-priority-up))
18209 ((and (not org-support-shift-select) (org-at-item-p))
18210 (call-interactively 'org-previous-item))
18211 ((org-clocktable-try-shift 'up arg))
18212 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18213 (org-support-shift-select
18214 (org-call-for-shift-select 'previous-line))
18215 (t (org-shiftselect-error))))
18217 (defun org-shiftdown (&optional arg)
18218 "Decrease item in timestamp or decrease priority of current headline.
18219 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18220 depending on context. See the individual commands for more information."
18221 (interactive "P")
18222 (cond
18223 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18224 ((and org-support-shift-select (org-region-active-p))
18225 (org-call-for-shift-select 'next-line))
18226 ((org-at-timestamp-p t)
18227 (call-interactively (if org-edit-timestamp-down-means-later
18228 'org-timestamp-up 'org-timestamp-down)))
18229 ((and (not (eq org-support-shift-select 'always))
18230 org-enable-priority-commands
18231 (org-at-heading-p))
18232 (call-interactively 'org-priority-down))
18233 ((and (not org-support-shift-select) (org-at-item-p))
18234 (call-interactively 'org-next-item))
18235 ((org-clocktable-try-shift 'down arg))
18236 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18237 (org-support-shift-select
18238 (org-call-for-shift-select 'next-line))
18239 (t (org-shiftselect-error))))
18241 (defun org-shiftright (&optional arg)
18242 "Cycle the thing at point or in the current line, depending on context.
18243 Depending on context, this does one of the following:
18245 - switch a timestamp at point one day into the future
18246 - on a headline, switch to the next TODO keyword.
18247 - on an item, switch entire list to the next bullet type
18248 - on a property line, switch to the next allowed value
18249 - on a clocktable definition line, move time block into the future"
18250 (interactive "P")
18251 (cond
18252 ((run-hook-with-args-until-success 'org-shiftright-hook))
18253 ((and org-support-shift-select (org-region-active-p))
18254 (org-call-for-shift-select 'forward-char))
18255 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18256 ((and (not (eq org-support-shift-select 'always))
18257 (org-at-heading-p))
18258 (let ((org-inhibit-logging
18259 (not org-treat-S-cursor-todo-selection-as-state-change))
18260 (org-inhibit-blocking
18261 (not org-treat-S-cursor-todo-selection-as-state-change)))
18262 (org-call-with-arg 'org-todo 'right)))
18263 ((or (and org-support-shift-select
18264 (not (eq org-support-shift-select 'always))
18265 (org-at-item-bullet-p))
18266 (and (not org-support-shift-select) (org-at-item-p)))
18267 (org-call-with-arg 'org-cycle-list-bullet nil))
18268 ((and (not (eq org-support-shift-select 'always))
18269 (org-at-property-p))
18270 (call-interactively 'org-property-next-allowed-value))
18271 ((org-clocktable-try-shift 'right arg))
18272 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18273 (org-support-shift-select
18274 (org-call-for-shift-select 'forward-char))
18275 (t (org-shiftselect-error))))
18277 (defun org-shiftleft (&optional arg)
18278 "Cycle the thing at point or in the current line, depending on context.
18279 Depending on context, this does one of the following:
18281 - switch a timestamp at point one day into the past
18282 - on a headline, switch to the previous TODO keyword.
18283 - on an item, switch entire list to the previous bullet type
18284 - on a property line, switch to the previous allowed value
18285 - on a clocktable definition line, move time block into the past"
18286 (interactive "P")
18287 (cond
18288 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18289 ((and org-support-shift-select (org-region-active-p))
18290 (org-call-for-shift-select 'backward-char))
18291 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18292 ((and (not (eq org-support-shift-select 'always))
18293 (org-at-heading-p))
18294 (let ((org-inhibit-logging
18295 (not org-treat-S-cursor-todo-selection-as-state-change))
18296 (org-inhibit-blocking
18297 (not org-treat-S-cursor-todo-selection-as-state-change)))
18298 (org-call-with-arg 'org-todo 'left)))
18299 ((or (and org-support-shift-select
18300 (not (eq org-support-shift-select 'always))
18301 (org-at-item-bullet-p))
18302 (and (not org-support-shift-select) (org-at-item-p)))
18303 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18304 ((and (not (eq org-support-shift-select 'always))
18305 (org-at-property-p))
18306 (call-interactively 'org-property-previous-allowed-value))
18307 ((org-clocktable-try-shift 'left arg))
18308 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18309 (org-support-shift-select
18310 (org-call-for-shift-select 'backward-char))
18311 (t (org-shiftselect-error))))
18313 (defun org-shiftcontrolright ()
18314 "Switch to next TODO set."
18315 (interactive)
18316 (cond
18317 ((and org-support-shift-select (org-region-active-p))
18318 (org-call-for-shift-select 'forward-word))
18319 ((and (not (eq org-support-shift-select 'always))
18320 (org-at-heading-p))
18321 (org-call-with-arg 'org-todo 'nextset))
18322 (org-support-shift-select
18323 (org-call-for-shift-select 'forward-word))
18324 (t (org-shiftselect-error))))
18326 (defun org-shiftcontrolleft ()
18327 "Switch to previous TODO set."
18328 (interactive)
18329 (cond
18330 ((and org-support-shift-select (org-region-active-p))
18331 (org-call-for-shift-select 'backward-word))
18332 ((and (not (eq org-support-shift-select 'always))
18333 (org-at-heading-p))
18334 (org-call-with-arg 'org-todo 'previousset))
18335 (org-support-shift-select
18336 (org-call-for-shift-select 'backward-word))
18337 (t (org-shiftselect-error))))
18339 (defun org-shiftcontrolup ()
18340 "Change timestamps synchronously up in CLOCK log lines."
18341 (interactive)
18342 (cond ((and (not org-support-shift-select)
18343 (org-at-clock-log-p)
18344 (org-at-timestamp-p t))
18345 (org-clock-timestamps-up))
18346 (t (org-shiftselect-error))))
18348 (defun org-shiftcontroldown ()
18349 "Change timestamps synchronously down in CLOCK log lines."
18350 (interactive)
18351 (cond ((and (not org-support-shift-select)
18352 (org-at-clock-log-p)
18353 (org-at-timestamp-p t))
18354 (org-clock-timestamps-down))
18355 (t (org-shiftselect-error))))
18357 (defun org-ctrl-c-ret ()
18358 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18359 (interactive)
18360 (cond
18361 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18362 (t (call-interactively 'org-insert-heading))))
18364 (defun org-find-visible ()
18365 (let ((s (point)))
18366 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18367 (get-char-property s 'invisible)))
18369 (defun org-find-invisible ()
18370 (let ((s (point)))
18371 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18372 (not (get-char-property s 'invisible))))
18375 (defun org-copy-visible (beg end)
18376 "Copy the visible parts of the region."
18377 (interactive "r")
18378 (let (snippets s)
18379 (save-excursion
18380 (save-restriction
18381 (narrow-to-region beg end)
18382 (setq s (goto-char (point-min)))
18383 (while (not (= (point) (point-max)))
18384 (goto-char (org-find-invisible))
18385 (push (buffer-substring s (point)) snippets)
18386 (setq s (goto-char (org-find-visible))))))
18387 (kill-new (apply 'concat (nreverse snippets)))))
18389 (defun org-copy-special ()
18390 "Copy region in table or copy current subtree.
18391 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18392 See the individual commands for more information."
18393 (interactive)
18394 (call-interactively
18395 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18397 (defun org-cut-special ()
18398 "Cut region in table or cut current subtree.
18399 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18400 See the individual commands for more information."
18401 (interactive)
18402 (call-interactively
18403 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18405 (defun org-paste-special (arg)
18406 "Paste rectangular region into table, or past subtree relative to level.
18407 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18408 See the individual commands for more information."
18409 (interactive "P")
18410 (if (org-at-table-p)
18411 (org-table-paste-rectangle)
18412 (org-paste-subtree arg)))
18414 (defun org-edit-special (&optional arg)
18415 "Call a special editor for the stuff at point.
18416 When at a table, call the formula editor with `org-table-edit-formulas'.
18417 When at the first line of an src example, call `org-edit-src-code'.
18418 When in an #+include line, visit the include file. Otherwise call
18419 `ffap' to visit the file at point."
18420 (interactive)
18421 ;; possibly prep session before editing source
18422 (when arg
18423 (let* ((info (org-babel-get-src-block-info))
18424 (lang (nth 0 info))
18425 (params (nth 2 info))
18426 (session (cdr (assoc :session params))))
18427 (when (and info session) ;; we are in a source-code block with a session
18428 (funcall
18429 (intern (concat "org-babel-prep-session:" lang)) session params))))
18430 (cond ;; proceed with `org-edit-special'
18431 ((save-excursion
18432 (beginning-of-line 1)
18433 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18434 (find-file (org-trim (match-string 1))))
18435 ((org-edit-src-code))
18436 ((org-edit-fixed-width-region))
18437 ((org-at-table.el-p)
18438 (org-edit-src-code))
18439 ((or (org-at-table-p)
18440 (save-excursion
18441 (beginning-of-line 1)
18442 (looking-at "[ \t]*#\\+TBLFM:")))
18443 (call-interactively 'org-table-edit-formulas))
18444 (t (call-interactively 'ffap))))
18446 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18447 (defun org-ctrl-c-ctrl-c (&optional arg)
18448 "Set tags in headline, or update according to changed information at point.
18450 This command does many different things, depending on context:
18452 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18453 this is what we do.
18455 - If the cursor is on a statistics cookie, update it.
18457 - If the cursor is in a headline, prompt for tags and insert them
18458 into the current line, aligned to `org-tags-column'. When called
18459 with prefix arg, realign all tags in the current buffer.
18461 - If the cursor is in one of the special #+KEYWORD lines, this
18462 triggers scanning the buffer for these lines and updating the
18463 information.
18465 - If the cursor is inside a table, realign the table. This command
18466 works even if the automatic table editor has been turned off.
18468 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18469 the entire table.
18471 - If the cursor is at a footnote reference or definition, jump to
18472 the corresponding definition or references, respectively.
18474 - If the cursor is a the beginning of a dynamic block, update it.
18476 - If the current buffer is a capture buffer, close note and file it.
18478 - If the cursor is on a <<<target>>>, update radio targets and
18479 corresponding links in this buffer.
18481 - If the cursor is on a numbered item in a plain list, renumber the
18482 ordered list.
18484 - If the cursor is on a checkbox, toggle it.
18486 - If the cursor is on a code block, evaluate it. The variable
18487 `org-confirm-babel-evaluate' can be used to control prompting
18488 before code block evaluation, by default every code block
18489 evaluation requires confirmation. Code block evaluation can be
18490 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18491 (interactive "P")
18492 (let ((org-enable-table-editor t))
18493 (cond
18494 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18495 org-occur-highlights
18496 org-latex-fragment-image-overlays)
18497 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18498 (org-remove-occur-highlights)
18499 (org-remove-latex-fragment-image-overlays)
18500 (message "Temporary highlights/overlays removed from current buffer"))
18501 ((and (local-variable-p 'org-finish-function (current-buffer))
18502 (fboundp org-finish-function))
18503 (funcall org-finish-function))
18504 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18505 ((org-in-regexp org-ts-regexp-both)
18506 (org-timestamp-change 0 'day))
18507 ((or (looking-at org-property-start-re)
18508 (org-at-property-p))
18509 (call-interactively 'org-property-action))
18510 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18511 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18512 (or (org-at-heading-p) (org-at-item-p)))
18513 (call-interactively 'org-update-statistics-cookies))
18514 ((org-at-heading-p) (call-interactively 'org-set-tags))
18515 ((org-at-table.el-p)
18516 (message "Use C-c ' to edit table.el tables"))
18517 ((org-at-table-p)
18518 (org-table-maybe-eval-formula)
18519 (if arg
18520 (call-interactively 'org-table-recalculate)
18521 (org-table-maybe-recalculate-line))
18522 (call-interactively 'org-table-align)
18523 (orgtbl-send-table 'maybe))
18524 ((or (org-footnote-at-reference-p)
18525 (org-footnote-at-definition-p))
18526 (call-interactively 'org-footnote-action))
18527 ((org-at-item-checkbox-p)
18528 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18529 ;; list only if at top item.
18530 (let* ((cbox (match-string 1))
18531 (struct (org-list-struct))
18532 (old-struct (copy-tree struct))
18533 (parents (org-list-parents-alist struct))
18534 (orderedp (org-entry-get nil "ORDERED"))
18535 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18536 block-item)
18537 ;; Use a light version of `org-toggle-checkbox' to avoid
18538 ;; computing list structure twice.
18539 (let ((new-box (cond
18540 ((equal arg '(16)) "[-]")
18541 ((equal arg '(4)) nil)
18542 ((equal "[X]" cbox) "[ ]")
18543 (t "[X]"))))
18544 (if (and firstp arg)
18545 ;; If at first item of sub-list, remove check-box from
18546 ;; every item at the same level.
18547 (mapc
18548 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18549 (org-list-get-all-items
18550 (point-at-bol) struct (org-list-prevs-alist struct)))
18551 (org-list-set-checkbox (point-at-bol) struct new-box)))
18552 ;; Replicate `org-list-write-struct', while grabbing a return
18553 ;; value from `org-list-struct-fix-box'.
18554 (org-list-struct-fix-ind struct parents 2)
18555 (org-list-struct-fix-item-end struct)
18556 (let ((prevs (org-list-prevs-alist struct)))
18557 (org-list-struct-fix-bul struct prevs)
18558 (org-list-struct-fix-ind struct parents)
18559 (setq block-item
18560 (org-list-struct-fix-box struct parents prevs orderedp)))
18561 (org-list-struct-apply-struct struct old-struct)
18562 (org-update-checkbox-count-maybe)
18563 (when block-item
18564 (message
18565 "Checkboxes were removed due to unchecked box at line %d"
18566 (org-current-line block-item)))
18567 (when firstp (org-list-send-list 'maybe))))
18568 ((org-at-item-p)
18569 ;; Cursor at an item: repair list. Do checkbox related actions
18570 ;; only if function was called with an argument. Send list only
18571 ;; if at top item.
18572 (let* ((struct (org-list-struct))
18573 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18574 old-struct)
18575 (when arg
18576 (setq old-struct (copy-tree struct))
18577 (if firstp
18578 ;; If at first item of sub-list, add check-box to every
18579 ;; item at the same level.
18580 (mapc
18581 (lambda (pos)
18582 (unless (org-list-get-checkbox pos struct)
18583 (org-list-set-checkbox pos struct "[ ]")))
18584 (org-list-get-all-items
18585 (point-at-bol) struct (org-list-prevs-alist struct)))
18586 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18587 (org-list-write-struct
18588 struct (org-list-parents-alist struct) old-struct)
18589 (when arg (org-update-checkbox-count-maybe))
18590 (when firstp (org-list-send-list 'maybe))))
18591 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18592 ;; Dynamic block
18593 (beginning-of-line 1)
18594 (save-excursion (org-update-dblock)))
18595 ((save-excursion
18596 (beginning-of-line 1)
18597 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18598 (cond
18599 ((equal (match-string 1) "TBLFM")
18600 ;; Recalculate the table before this line
18601 (save-excursion
18602 (beginning-of-line 1)
18603 (skip-chars-backward " \r\n\t")
18604 (if (org-at-table-p)
18605 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18607 (let ((org-inhibit-startup-visibility-stuff t)
18608 (org-startup-align-all-tables nil))
18609 (when (boundp 'org-table-coordinate-overlays)
18610 (mapc 'delete-overlay org-table-coordinate-overlays)
18611 (setq org-table-coordinate-overlays nil))
18612 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18613 (message "Local setup has been refreshed"))))
18614 ((org-clock-update-time-maybe))
18616 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18617 (error "C-c C-c can do nothing useful at this location"))))))
18619 (defun org-mode-restart ()
18620 "Restart Org-mode, to scan again for special lines.
18621 Also updates the keyword regular expressions."
18622 (interactive)
18623 (org-mode)
18624 (message "Org-mode restarted"))
18626 (defun org-kill-note-or-show-branches ()
18627 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18628 (interactive)
18629 (if (not org-finish-function)
18630 (progn
18631 (hide-subtree)
18632 (call-interactively 'show-branches))
18633 (let ((org-note-abort t))
18634 (funcall org-finish-function))))
18636 (defun org-return (&optional indent)
18637 "Goto next table row or insert a newline.
18638 Calls `org-table-next-row' or `newline', depending on context.
18639 See the individual commands for more information."
18640 (interactive)
18641 (cond
18642 ((or (bobp) (org-in-src-block-p))
18643 (if indent (newline-and-indent) (newline)))
18644 ((org-at-table-p)
18645 (org-table-justify-field-maybe)
18646 (call-interactively 'org-table-next-row))
18647 ;; when `newline-and-indent' is called within a list, make sure
18648 ;; text moved stays inside the item.
18649 ((and (org-in-item-p) indent)
18650 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18651 (progn
18652 (save-match-data (newline))
18653 (org-indent-line-to (length (match-string 0))))
18654 (let ((ind (org-get-indentation)))
18655 (newline)
18656 (if (org-looking-back org-list-end-re)
18657 (org-indent-line-function)
18658 (org-indent-line-to ind)))))
18659 ((and org-return-follows-link
18660 (let ((tprop (get-text-property (point) 'face)))
18661 (or (eq tprop 'org-link)
18662 (and (listp tprop) (memq 'org-link tprop)))))
18663 (call-interactively 'org-open-at-point))
18664 ((and (org-at-heading-p)
18665 (looking-at
18666 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18667 (org-show-entry)
18668 (end-of-line 1)
18669 (newline))
18670 (t (if indent (newline-and-indent) (newline)))))
18672 (defun org-return-indent ()
18673 "Goto next table row or insert a newline and indent.
18674 Calls `org-table-next-row' or `newline-and-indent', depending on
18675 context. See the individual commands for more information."
18676 (interactive)
18677 (org-return t))
18679 (defun org-ctrl-c-star ()
18680 "Compute table, or change heading status of lines.
18681 Calls `org-table-recalculate' or `org-toggle-heading',
18682 depending on context."
18683 (interactive)
18684 (cond
18685 ((org-at-table-p)
18686 (call-interactively 'org-table-recalculate))
18688 ;; Convert all lines in region to list items
18689 (call-interactively 'org-toggle-heading))))
18691 (defun org-ctrl-c-minus ()
18692 "Insert separator line in table or modify bullet status of line.
18693 Also turns a plain line or a region of lines into list items.
18694 Calls `org-table-insert-hline', `org-toggle-item', or
18695 `org-cycle-list-bullet', depending on context."
18696 (interactive)
18697 (cond
18698 ((org-at-table-p)
18699 (call-interactively 'org-table-insert-hline))
18700 ((org-region-active-p)
18701 (call-interactively 'org-toggle-item))
18702 ((org-in-item-p)
18703 (call-interactively 'org-cycle-list-bullet))
18705 (call-interactively 'org-toggle-item))))
18707 (defun org-toggle-item (arg)
18708 "Convert headings or normal lines to items, items to normal lines.
18709 If there is no active region, only the current line is considered.
18711 If the first non blank line in the region is an headline, convert
18712 all headlines to items, shifting text accordingly.
18714 If it is an item, convert all items to normal lines.
18716 If it is normal text, change region into an item. With a prefix
18717 argument ARG, change each line in region into an item."
18718 (interactive "P")
18719 (let ((shift-text
18720 (function
18721 ;; Shift text in current section to IND, from point to END.
18722 ;; The function leaves point to END line.
18723 (lambda (ind end)
18724 (let ((min-i 1000) (end (copy-marker end)))
18725 ;; First determine the minimum indentation (MIN-I) of
18726 ;; the text.
18727 (save-excursion
18728 (catch 'exit
18729 (while (< (point) end)
18730 (let ((i (org-get-indentation)))
18731 (cond
18732 ;; Skip blank lines and inline tasks.
18733 ((looking-at "^[ \t]*$"))
18734 ((looking-at org-outline-regexp-bol))
18735 ;; We can't find less than 0 indentation.
18736 ((zerop i) (throw 'exit (setq min-i 0)))
18737 ((< i min-i) (setq min-i i))))
18738 (forward-line))))
18739 ;; Then indent each line so that a line indented to
18740 ;; MIN-I becomes indented to IND. Ignore blank lines
18741 ;; and inline tasks in the process.
18742 (let ((delta (- ind min-i)))
18743 (while (< (point) end)
18744 (unless (or (looking-at "^[ \t]*$")
18745 (looking-at org-outline-regexp-bol))
18746 (org-indent-line-to (+ (org-get-indentation) delta)))
18747 (forward-line)))))))
18748 (skip-blanks
18749 (function
18750 ;; Return beginning of first non-blank line, starting from
18751 ;; line at POS.
18752 (lambda (pos)
18753 (save-excursion
18754 (goto-char pos)
18755 (skip-chars-forward " \r\t\n")
18756 (point-at-bol)))))
18757 beg end)
18758 ;; Determine boundaries of changes.
18759 (if (org-region-active-p)
18760 (setq beg (funcall skip-blanks (region-beginning))
18761 end (copy-marker (region-end)))
18762 (setq beg (funcall skip-blanks (point-at-bol))
18763 end (copy-marker (point-at-eol))))
18764 ;; Depending on the starting line, choose an action on the text
18765 ;; between BEG and END.
18766 (org-with-limited-levels
18767 (save-excursion
18768 (goto-char beg)
18769 (cond
18770 ;; Case 1. Start at an item: de-itemize. Note that it only
18771 ;; happens when a region is active: `org-ctrl-c-minus'
18772 ;; would call `org-cycle-list-bullet' otherwise.
18773 ((org-at-item-p)
18774 (while (< (point) end)
18775 (when (org-at-item-p)
18776 (skip-chars-forward " \t")
18777 (delete-region (point) (match-end 0)))
18778 (forward-line)))
18779 ;; Case 2. Start at an heading: convert to items.
18780 ((org-at-heading-p)
18781 (let* ((bul (org-list-bullet-string "-"))
18782 (bul-len (length bul))
18783 ;; Indentation of the first heading. It should be
18784 ;; relative to the indentation of its parent, if any.
18785 (start-ind (save-excursion
18786 (cond
18787 ((not org-adapt-indentation) 0)
18788 ((not (outline-previous-heading)) 0)
18789 (t (length (match-string 0))))))
18790 ;; Level of first heading. Further headings will be
18791 ;; compared to it to determine hierarchy in the list.
18792 (ref-level (org-reduced-level (org-outline-level))))
18793 (while (< (point) end)
18794 (let* ((level (org-reduced-level (org-outline-level)))
18795 (delta (max 0 (- level ref-level))))
18796 ;; If current headline is less indented than the first
18797 ;; one, set it as reference, in order to preserve
18798 ;; subtrees.
18799 (when (< level ref-level) (setq ref-level level))
18800 (replace-match bul t t)
18801 (org-indent-line-to (+ start-ind (* delta bul-len)))
18802 ;; Ensure all text down to END (or SECTION-END) belongs
18803 ;; to the newly created item.
18804 (let ((section-end (save-excursion
18805 (or (outline-next-heading) (point)))))
18806 (forward-line)
18807 (funcall shift-text
18808 (+ start-ind (* (1+ delta) bul-len))
18809 (min end section-end)))))))
18810 ;; Case 3. Normal line with ARG: turn each non-item line into
18811 ;; an item.
18812 (arg
18813 (while (< (point) end)
18814 (unless (or (org-at-heading-p) (org-at-item-p))
18815 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18816 (replace-match
18817 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18818 (forward-line)))
18819 ;; Case 4. Normal line without ARG: make the first line of
18820 ;; region an item, and shift indentation of others
18821 ;; lines to set them as item's body.
18822 (t (let* ((bul (org-list-bullet-string "-"))
18823 (bul-len (length bul))
18824 (ref-ind (org-get-indentation)))
18825 (skip-chars-forward " \t")
18826 (insert bul)
18827 (forward-line)
18828 (while (< (point) end)
18829 ;; Ensure that lines less indented than first one
18830 ;; still get included in item body.
18831 (funcall shift-text
18832 (+ ref-ind bul-len)
18833 (min end (save-excursion (or (outline-next-heading)
18834 (point)))))
18835 (forward-line)))))))))
18837 (defun org-toggle-heading (&optional nstars)
18838 "Convert headings to normal text, or items or text to headings.
18839 If there is no active region, only the current line is considered.
18841 If the first non blank line is an headline, remove the stars from
18842 all headlines in the region.
18844 If it is a plain list item, turn all plain list items into headings.
18846 If it is a normal line, turn each and every normal line (i.e. not
18847 an heading or an item) in the region into a heading.
18849 When converting a line into a heading, the number of stars is chosen
18850 such that the lines become children of the current entry. However,
18851 when a prefix argument is given, its value determines the number of
18852 stars to add."
18853 (interactive "P")
18854 (let ((skip-blanks
18855 (function
18856 ;; Return beginning of first non-blank line, starting from
18857 ;; line at POS.
18858 (lambda (pos)
18859 (save-excursion
18860 (goto-char pos)
18861 (skip-chars-forward " \r\t\n")
18862 (point-at-bol)))))
18863 beg end)
18864 ;; Determine boundaries of changes. If region ends at a bol, do
18865 ;; not consider the last line to be in the region.
18866 (if (org-region-active-p)
18867 (setq beg (funcall skip-blanks (region-beginning))
18868 end (copy-marker (save-excursion
18869 (goto-char (region-end))
18870 (if (bolp) (point) (point-at-eol)))))
18871 (setq beg (funcall skip-blanks (point-at-bol))
18872 end (copy-marker (point-at-eol))))
18873 ;; Ensure inline tasks don't count as headings.
18874 (org-with-limited-levels
18875 (save-excursion
18876 (goto-char beg)
18877 (cond
18878 ;; Case 1. Started at an heading: de-star headings.
18879 ((org-at-heading-p)
18880 (while (< (point) end)
18881 (when (org-at-heading-p t)
18882 (looking-at org-outline-regexp) (replace-match ""))
18883 (forward-line)))
18884 ;; Case 2. Started at an item: change items into headlines.
18885 ;; One star will be added by `org-list-to-subtree'.
18886 ((org-at-item-p)
18887 (let* ((stars (make-string
18888 (if nstars
18889 ;; subtract the star that will be added again by
18890 ;; `org-list-to-subtree'
18891 (1- (prefix-numeric-value current-prefix-arg))
18892 (or (org-current-level) 0))
18893 ?*))
18894 (add-stars
18895 (cond (nstars "") ; stars from prefix only
18896 ((equal stars "") "") ; before first heading
18897 (org-odd-levels-only "*") ; inside heading, odd
18898 (t "")))) ; inside heading, oddeven
18899 (while (< (point) end)
18900 (when (org-at-item-p)
18901 ;; Pay attention to cases when region ends before list.
18902 (let* ((struct (org-list-struct))
18903 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18904 (save-restriction
18905 (narrow-to-region (point) list-end)
18906 (insert
18907 (org-list-to-subtree
18908 (org-list-parse-list t)
18909 '(:istart (concat stars add-stars (funcall get-stars depth))
18910 :icount (concat stars add-stars (funcall get-stars depth))))))))
18911 (forward-line))))
18912 ;; Case 3. Started at normal text: make every line an heading,
18913 ;; skipping headlines and items.
18914 (t (let* ((stars (make-string
18915 (if nstars
18916 (prefix-numeric-value current-prefix-arg)
18917 (or (org-current-level) 0))
18918 ?*))
18919 (add-stars
18920 (cond (nstars "") ; stars from prefix only
18921 ((equal stars "") "*") ; before first heading
18922 (org-odd-levels-only "**") ; inside heading, odd
18923 (t "*"))) ; inside heading, oddeven
18924 (rpl (concat stars add-stars " ")))
18925 (while (< (point) end)
18926 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
18927 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18928 (replace-match (concat rpl (match-string 2))))
18929 (forward-line)))))))))
18931 (defun org-meta-return (&optional arg)
18932 "Insert a new heading or wrap a region in a table.
18933 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18934 See the individual commands for more information."
18935 (interactive "P")
18936 (cond
18937 ((run-hook-with-args-until-success 'org-metareturn-hook))
18938 ((or (org-at-drawer-p) (org-at-property-p))
18939 (newline-and-indent))
18940 ((org-at-table-p)
18941 (call-interactively 'org-table-wrap-region))
18942 (t (call-interactively 'org-insert-heading))))
18944 ;;; Menu entries
18946 ;; Define the Org-mode menus
18947 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18948 '("Tbl"
18949 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18950 ["Next Field" org-cycle (org-at-table-p)]
18951 ["Previous Field" org-shifttab (org-at-table-p)]
18952 ["Next Row" org-return (org-at-table-p)]
18953 "--"
18954 ["Blank Field" org-table-blank-field (org-at-table-p)]
18955 ["Edit Field" org-table-edit-field (org-at-table-p)]
18956 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18957 "--"
18958 ("Column"
18959 ["Move Column Left" org-metaleft (org-at-table-p)]
18960 ["Move Column Right" org-metaright (org-at-table-p)]
18961 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18962 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18963 ("Row"
18964 ["Move Row Up" org-metaup (org-at-table-p)]
18965 ["Move Row Down" org-metadown (org-at-table-p)]
18966 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18967 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18968 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18969 "--"
18970 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18971 ("Rectangle"
18972 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18973 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18974 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18975 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18976 "--"
18977 ("Calculate"
18978 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18979 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18980 ["Edit Formulas" org-edit-special (org-at-table-p)]
18981 "--"
18982 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18983 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18984 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18985 "--"
18986 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18987 "--"
18988 ["Sum Column/Rectangle" org-table-sum
18989 (or (org-at-table-p) (org-region-active-p))]
18990 ["Which Column?" org-table-current-column (org-at-table-p)])
18991 ["Debug Formulas"
18992 org-table-toggle-formula-debugger
18993 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18994 ["Show Col/Row Numbers"
18995 org-table-toggle-coordinate-overlays
18996 :style toggle
18997 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18998 "--"
18999 ["Create" org-table-create (and (not (org-at-table-p))
19000 org-enable-table-editor)]
19001 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19002 ["Import from File" org-table-import (not (org-at-table-p))]
19003 ["Export to File" org-table-export (org-at-table-p)]
19004 "--"
19005 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19007 (easy-menu-define org-org-menu org-mode-map "Org menu"
19008 '("Org"
19009 ("Show/Hide"
19010 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19011 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19012 ["Sparse Tree..." org-sparse-tree t]
19013 ["Reveal Context" org-reveal t]
19014 ["Show All" show-all t]
19015 "--"
19016 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19017 "--"
19018 ["New Heading" org-insert-heading t]
19019 ("Navigate Headings"
19020 ["Up" outline-up-heading t]
19021 ["Next" outline-next-visible-heading t]
19022 ["Previous" outline-previous-visible-heading t]
19023 ["Next Same Level" outline-forward-same-level t]
19024 ["Previous Same Level" outline-backward-same-level t]
19025 "--"
19026 ["Jump" org-goto t])
19027 ("Edit Structure"
19028 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19029 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19030 "--"
19031 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19032 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19033 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19034 "--"
19035 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19036 "--"
19037 ["Copy visible text" org-copy-visible t]
19038 "--"
19039 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19040 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19041 ["Demote Heading" org-metaright (not (org-at-table-p))]
19042 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19043 "--"
19044 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19045 "--"
19046 ["Convert to odd levels" org-convert-to-odd-levels t]
19047 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19048 ("Editing"
19049 ["Emphasis..." org-emphasize t]
19050 ["Edit Source Example" org-edit-special t]
19051 "--"
19052 ["Footnote new/jump" org-footnote-action t]
19053 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19054 ("Archive"
19055 ["Archive (default method)" org-archive-subtree-default t]
19056 "--"
19057 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19058 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19059 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19061 "--"
19062 ("Hyperlinks"
19063 ["Store Link (Global)" org-store-link t]
19064 ["Find existing link to here" org-occur-link-in-agenda-files t]
19065 ["Insert Link" org-insert-link t]
19066 ["Follow Link" org-open-at-point t]
19067 "--"
19068 ["Next link" org-next-link t]
19069 ["Previous link" org-previous-link t]
19070 "--"
19071 ["Descriptive Links"
19072 org-toggle-link-display
19073 :style radio
19074 :selected org-descriptive-links
19076 ["Literal Links"
19077 org-toggle-link-display
19078 :style radio
19079 :selected (not org-descriptive-links)])
19080 "--"
19081 ("TODO Lists"
19082 ["TODO/DONE/-" org-todo t]
19083 ("Select keyword"
19084 ["Next keyword" org-shiftright (org-at-heading-p)]
19085 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19086 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19087 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19088 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19089 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19090 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19091 "--"
19092 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19093 :selected org-enforce-todo-dependencies :style toggle :active t]
19094 "Settings for tree at point"
19095 ["Do Children sequentially" org-toggle-ordered-property :style radio
19096 :selected (org-entry-get nil "ORDERED")
19097 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19098 ["Do Children parallel" org-toggle-ordered-property :style radio
19099 :selected (not (org-entry-get nil "ORDERED"))
19100 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19101 "--"
19102 ["Set Priority" org-priority t]
19103 ["Priority Up" org-shiftup t]
19104 ["Priority Down" org-shiftdown t]
19105 "--"
19106 ["Get news from all feeds" org-feed-update-all t]
19107 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19108 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19109 ("TAGS and Properties"
19110 ["Set Tags" org-set-tags-command t]
19111 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19112 "--"
19113 ["Set property" org-set-property t]
19114 ["Column view of properties" org-columns t]
19115 ["Insert Column View DBlock" org-insert-columns-dblock t])
19116 ("Dates and Scheduling"
19117 ["Timestamp" org-time-stamp t]
19118 ["Timestamp (inactive)" org-time-stamp-inactive t]
19119 ("Change Date"
19120 ["1 Day Later" org-shiftright t]
19121 ["1 Day Earlier" org-shiftleft t]
19122 ["1 ... Later" org-shiftup t]
19123 ["1 ... Earlier" org-shiftdown t])
19124 ["Compute Time Range" org-evaluate-time-range t]
19125 ["Schedule Item" org-schedule t]
19126 ["Deadline" org-deadline t]
19127 "--"
19128 ["Custom time format" org-toggle-time-stamp-overlays
19129 :style radio :selected org-display-custom-times]
19130 "--"
19131 ["Goto Calendar" org-goto-calendar t]
19132 ["Date from Calendar" org-date-from-calendar t]
19133 "--"
19134 ["Start/Restart Timer" org-timer-start t]
19135 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19136 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19137 ["Insert Timer String" org-timer t]
19138 ["Insert Timer Item" org-timer-item t])
19139 ("Logging work"
19140 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19141 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19142 ["Clock out" org-clock-out t]
19143 ["Clock cancel" org-clock-cancel t]
19144 "--"
19145 ["Mark as default task" org-clock-mark-default-task t]
19146 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19147 ["Goto running clock" org-clock-goto t]
19148 "--"
19149 ["Display times" org-clock-display t]
19150 ["Create clock table" org-clock-report t]
19151 "--"
19152 ["Record DONE time"
19153 (progn (setq org-log-done (not org-log-done))
19154 (message "Switching to %s will %s record a timestamp"
19155 (car org-done-keywords)
19156 (if org-log-done "automatically" "not")))
19157 :style toggle :selected org-log-done])
19158 "--"
19159 ["Agenda Command..." org-agenda t]
19160 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19161 ("File List for Agenda")
19162 ("Special views current file"
19163 ["TODO Tree" org-show-todo-tree t]
19164 ["Check Deadlines" org-check-deadlines t]
19165 ["Timeline" org-timeline t]
19166 ["Tags/Property tree" org-match-sparse-tree t])
19167 "--"
19168 ["Export/Publish..." org-export t]
19169 ("LaTeX"
19170 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19171 :selected org-cdlatex-mode]
19172 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19173 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19174 ["Modify math symbol" org-cdlatex-math-modify
19175 (org-inside-LaTeX-fragment-p)]
19176 ["Insert citation" org-reftex-citation t]
19177 "--"
19178 ["Template for BEAMER" org-insert-beamer-options-template t])
19179 "--"
19180 ("MobileOrg"
19181 ["Push Files and Views" org-mobile-push t]
19182 ["Get Captured and Flagged" org-mobile-pull t]
19183 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19184 "--"
19185 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19186 "--"
19187 ("Documentation"
19188 ["Show Version" org-version t]
19189 ["Info Documentation" org-info t])
19190 ("Customize"
19191 ["Browse Org Group" org-customize t]
19192 "--"
19193 ["Expand This Menu" org-create-customize-menu
19194 (fboundp 'customize-menu-create)])
19195 ["Send bug report" org-submit-bug-report t]
19196 "--"
19197 ("Refresh/Reload"
19198 ["Refresh setup current buffer" org-mode-restart t]
19199 ["Reload Org (after update)" org-reload t]
19200 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19203 (defun org-info (&optional node)
19204 "Read documentation for Org-mode in the info system.
19205 With optional NODE, go directly to that node."
19206 (interactive)
19207 (info (format "(org)%s" (or node ""))))
19209 ;;;###autoload
19210 (defun org-submit-bug-report ()
19211 "Submit a bug report on Org-mode via mail.
19213 Don't hesitate to report any problems or inaccurate documentation.
19215 If you don't have setup sending mail from (X)Emacs, please copy the
19216 output buffer into your mail program, as it gives us important
19217 information about your Org-mode version and configuration."
19218 (interactive)
19219 (require 'reporter)
19220 (org-load-modules-maybe)
19221 (org-require-autoloaded-modules)
19222 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19223 (reporter-submit-bug-report
19224 "emacs-orgmode@gnu.org"
19225 (org-version)
19226 (let (list)
19227 (save-window-excursion
19228 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19229 (delete-other-windows)
19230 (erase-buffer)
19231 (insert "You are about to submit a bug report to the Org-mode mailing list.
19233 We would like to add your full Org-mode and Outline configuration to the
19234 bug report. This greatly simplifies the work of the maintainer and
19235 other experts on the mailing list.
19237 HOWEVER, some variables you have customized may contain private
19238 information. The names of customers, colleagues, or friends, might
19239 appear in the form of file names, tags, todo states, or search strings.
19240 If you answer yes to the prompt, you might want to check and remove
19241 such private information before sending the email.")
19242 (add-text-properties (point-min) (point-max) '(face org-warning))
19243 (when (yes-or-no-p "Include your Org-mode configuration ")
19244 (mapatoms
19245 (lambda (v)
19246 (and (boundp v)
19247 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19248 (or (and (symbol-value v)
19249 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19250 (and
19251 (get v 'custom-type) (get v 'standard-value)
19252 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19253 (push v list)))))
19254 (kill-buffer (get-buffer "*Warn about privacy*"))
19255 list))
19256 nil nil
19257 "Remember to cover the basics, that is, what you expected to happen and
19258 what in fact did happen. You don't know how to make a good report? See
19260 http://orgmode.org/manual/Feedback.html#Feedback
19262 Your bug report will be posted to the Org-mode mailing list.
19263 ------------------------------------------------------------------------")
19264 (save-excursion
19265 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19266 (replace-match "\\1Bug: \\3 [\\2]")))))
19269 (defun org-install-agenda-files-menu ()
19270 (let ((bl (buffer-list)))
19271 (save-excursion
19272 (while bl
19273 (set-buffer (pop bl))
19274 (if (eq major-mode 'org-mode) (setq bl nil)))
19275 (when (eq major-mode 'org-mode)
19276 (easy-menu-change
19277 '("Org") "File List for Agenda"
19278 (append
19279 (list
19280 ["Edit File List" (org-edit-agenda-file-list) t]
19281 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19282 ["Remove Current File from List" org-remove-file t]
19283 ["Cycle through agenda files" org-cycle-agenda-files t]
19284 ["Occur in all agenda files" org-occur-in-agenda-files t]
19285 "--")
19286 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19288 ;;;; Documentation
19290 ;;;###autoload
19291 (defun org-require-autoloaded-modules ()
19292 (interactive)
19293 (mapc 'require
19294 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19295 org-docbook org-exp org-html org-icalendar
19296 org-id org-latex
19297 org-publish org-remember org-table
19298 org-timer org-xoxo)))
19300 ;;;###autoload
19301 (defun org-reload (&optional uncompiled)
19302 "Reload all org lisp files.
19303 With prefix arg UNCOMPILED, load the uncompiled versions."
19304 (interactive "P")
19305 (require 'find-func)
19306 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19307 (dir-org (file-name-directory (org-find-library-name "org")))
19308 (dir-org-contrib (ignore-errors
19309 (file-name-directory
19310 (org-find-library-name "org-contribdir"))))
19311 (babel-files
19312 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19313 (append (list nil "comint" "eval" "exp" "keys"
19314 "lob" "ref" "table" "tangle")
19315 (delq nil
19316 (mapcar
19317 (lambda (lang)
19318 (when (cdr lang) (symbol-name (car lang))))
19319 org-babel-load-languages)))))
19320 (files
19321 (append (directory-files dir-org t file-re)
19322 babel-files
19323 (and dir-org-contrib
19324 (directory-files dir-org-contrib t file-re))))
19325 (remove-re (concat (if (featurep 'xemacs)
19326 "org-colview" "org-colview-xemacs")
19327 "\\'")))
19328 (setq files (mapcar 'file-name-sans-extension files))
19329 (setq files (mapcar
19330 (lambda (x) (if (string-match remove-re x) nil x))
19331 files))
19332 (setq files (delq nil files))
19333 (mapc
19334 (lambda (f)
19335 (when (featurep (intern (file-name-nondirectory f)))
19336 (if (and (not uncompiled)
19337 (file-exists-p (concat f ".elc")))
19338 (load (concat f ".elc") nil nil t)
19339 (load (concat f ".el") nil nil t))))
19340 files))
19341 (org-version))
19343 ;;;###autoload
19344 (defun org-customize ()
19345 "Call the customize function with org as argument."
19346 (interactive)
19347 (org-load-modules-maybe)
19348 (org-require-autoloaded-modules)
19349 (customize-browse 'org))
19351 (defun org-create-customize-menu ()
19352 "Create a full customization menu for Org-mode, insert it into the menu."
19353 (interactive)
19354 (org-load-modules-maybe)
19355 (org-require-autoloaded-modules)
19356 (if (fboundp 'customize-menu-create)
19357 (progn
19358 (easy-menu-change
19359 '("Org") "Customize"
19360 `(["Browse Org group" org-customize t]
19361 "--"
19362 ,(customize-menu-create 'org)
19363 ["Set" Custom-set t]
19364 ["Save" Custom-save t]
19365 ["Reset to Current" Custom-reset-current t]
19366 ["Reset to Saved" Custom-reset-saved t]
19367 ["Reset to Standard Settings" Custom-reset-standard t]))
19368 (message "\"Org\"-menu now contains full customization menu"))
19369 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19371 ;;;; Miscellaneous stuff
19373 ;;; Generally useful functions
19375 (defun org-get-at-bol (property)
19376 "Get text property PROPERTY at beginning of line."
19377 (get-text-property (point-at-bol) property))
19379 (defun org-find-text-property-in-string (prop s)
19380 "Return the first non-nil value of property PROP in string S."
19381 (or (get-text-property 0 prop s)
19382 (get-text-property (or (next-single-property-change 0 prop s) 0)
19383 prop s)))
19385 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19386 "Display the given MESSAGE as a warning."
19387 (if (fboundp 'display-warning)
19388 (display-warning 'org message
19389 (if (featurep 'xemacs) 'warning :warning))
19390 (let ((buf (get-buffer-create "*Org warnings*")))
19391 (with-current-buffer buf
19392 (goto-char (point-max))
19393 (insert "Warning (Org): " message)
19394 (unless (bolp)
19395 (newline)))
19396 (display-buffer buf)
19397 (sit-for 0))))
19399 (defun org-eval (form)
19400 "Eval FORM and return result."
19401 (condition-case error
19402 (eval form)
19403 (error (format "%%![Error: %s]" error))))
19405 (defun org-in-clocktable-p ()
19406 "Check if the cursor is in a clocktable."
19407 (let ((pos (point)) start)
19408 (save-excursion
19409 (end-of-line 1)
19410 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19411 (setq start (match-beginning 0))
19412 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19413 (>= (match-end 0) pos)
19414 start))))
19416 (defun org-in-commented-line ()
19417 "Is point in a line starting with `#'?"
19418 (equal (char-after (point-at-bol)) ?#))
19420 (defun org-in-indented-comment-line ()
19421 "Is point in a line starting with `#' after some white space?"
19422 (save-excursion
19423 (save-match-data
19424 (goto-char (point-at-bol))
19425 (looking-at "[ \t]*#"))))
19427 (defun org-in-verbatim-emphasis ()
19428 (save-match-data
19429 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19431 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19432 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19433 (if (and marker (marker-buffer marker)
19434 (buffer-live-p (marker-buffer marker)))
19435 (progn
19436 (org-pop-to-buffer-same-window (marker-buffer marker))
19437 (if (or (> marker (point-max)) (< marker (point-min)))
19438 (widen))
19439 (goto-char marker)
19440 (org-show-context 'org-goto))
19441 (if bookmark
19442 (bookmark-jump bookmark)
19443 (error "Cannot find location"))))
19445 (defun org-quote-csv-field (s)
19446 "Quote field for inclusion in CSV material."
19447 (if (string-match "[\",]" s)
19448 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19451 (defun org-force-self-insert (N)
19452 "Needed to enforce self-insert under remapping."
19453 (interactive "p")
19454 (self-insert-command N))
19456 (defun org-string-width (s)
19457 "Compute width of string, ignoring invisible characters.
19458 This ignores character with invisibility property `org-link', and also
19459 characters with property `org-cwidth', because these will become invisible
19460 upon the next fontification round."
19461 (let (b l)
19462 (when (or (eq t buffer-invisibility-spec)
19463 (assq 'org-link buffer-invisibility-spec))
19464 (while (setq b (text-property-any 0 (length s)
19465 'invisible 'org-link s))
19466 (setq s (concat (substring s 0 b)
19467 (substring s (or (next-single-property-change
19468 b 'invisible s) (length s)))))))
19469 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19470 (setq s (concat (substring s 0 b)
19471 (substring s (or (next-single-property-change
19472 b 'org-cwidth s) (length s))))))
19473 (setq l (string-width s) b -1)
19474 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19475 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19478 (defun org-shorten-string (s maxlength)
19479 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19480 If the string is shorter or has length MAXLENGTH, just return the
19481 original string. If it is longer, the functions finds a space in the
19482 string, breaks this string off at that locations and adds three dots
19483 as ellipsis. Including the ellipsis, the string will not be longer
19484 than MAXLENGTH. If finding a good breaking point in the string does
19485 not work, the string is just chopped off in the middle of a word
19486 if necessary."
19487 (if (<= (length s) maxlength)
19489 (let* ((n (max (- maxlength 4) 1))
19490 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19491 (if (string-match re s)
19492 (concat (match-string 1 s) "...")
19493 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19495 (defun org-get-indentation (&optional line)
19496 "Get the indentation of the current line, interpreting tabs.
19497 When LINE is given, assume it represents a line and compute its indentation."
19498 (if line
19499 (if (string-match "^ *" (org-remove-tabs line))
19500 (match-end 0))
19501 (save-excursion
19502 (beginning-of-line 1)
19503 (skip-chars-forward " \t")
19504 (current-column))))
19506 (defun org-get-string-indentation (s)
19507 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19508 (let ((n -1) (i 0) (w tab-width) c)
19509 (catch 'exit
19510 (while (< (setq n (1+ n)) (length s))
19511 (setq c (aref s n))
19512 (cond ((= c ?\ ) (setq i (1+ i)))
19513 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19514 (t (throw 'exit t)))))
19517 (defun org-remove-tabs (s &optional width)
19518 "Replace tabulators in S with spaces.
19519 Assumes that s is a single line, starting in column 0."
19520 (setq width (or width tab-width))
19521 (while (string-match "\t" s)
19522 (setq s (replace-match
19523 (make-string
19524 (- (* width (/ (+ (match-beginning 0) width) width))
19525 (match-beginning 0)) ?\ )
19526 t t s)))
19529 (defun org-fix-indentation (line ind)
19530 "Fix indentation in LINE.
19531 IND is a cons cell with target and minimum indentation.
19532 If the current indentation in LINE is smaller than the minimum,
19533 leave it alone. If it is larger than ind, set it to the target."
19534 (let* ((l (org-remove-tabs line))
19535 (i (org-get-indentation l))
19536 (i1 (car ind)) (i2 (cdr ind)))
19537 (if (>= i i2) (setq l (substring line i2)))
19538 (if (> i1 0)
19539 (concat (make-string i1 ?\ ) l)
19540 l)))
19542 (defun org-remove-indentation (code &optional n)
19543 "Remove the maximum common indentation from the lines in CODE.
19544 N may optionally be the number of spaces to remove."
19545 (with-temp-buffer
19546 (insert code)
19547 (org-do-remove-indentation n)
19548 (buffer-string)))
19550 (defun org-do-remove-indentation (&optional n)
19551 "Remove the maximum common indentation from the buffer."
19552 (untabify (point-min) (point-max))
19553 (let ((min 10000) re)
19554 (if n
19555 (setq min n)
19556 (goto-char (point-min))
19557 (while (re-search-forward "^ *[^ \n]" nil t)
19558 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19559 (unless (or (= min 0) (= min 10000))
19560 (setq re (format "^ \\{%d\\}" min))
19561 (goto-char (point-min))
19562 (while (re-search-forward re nil t)
19563 (replace-match "")
19564 (end-of-line 1))
19565 min)))
19567 (defun org-fill-template (template alist)
19568 "Find each %key of ALIST in TEMPLATE and replace it."
19569 (let ((case-fold-search nil)
19570 entry key value)
19571 (setq alist (sort (copy-sequence alist)
19572 (lambda (a b) (< (length (car a)) (length (car b))))))
19573 (while (setq entry (pop alist))
19574 (setq template
19575 (replace-regexp-in-string
19576 (concat "%" (regexp-quote (car entry)))
19577 (cdr entry) template t t)))
19578 template))
19580 (defun org-base-buffer (buffer)
19581 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19582 (if (not buffer)
19583 buffer
19584 (or (buffer-base-buffer buffer)
19585 buffer)))
19587 (defun org-trim (s)
19588 "Remove whitespace at beginning and end of string."
19589 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19590 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19593 (defun org-wrap (string &optional width lines)
19594 "Wrap string to either a number of lines, or a width in characters.
19595 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19596 that costs. If there is a word longer than WIDTH, the text is actually
19597 wrapped to the length of that word.
19598 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19599 many lines, whatever width that takes.
19600 The return value is a list of lines, without newlines at the end."
19601 (let* ((words (org-split-string string "[ \t\n]+"))
19602 (maxword (apply 'max (mapcar 'org-string-width words)))
19603 w ll)
19604 (cond (width
19605 (org-do-wrap words (max maxword width)))
19606 (lines
19607 (setq w maxword)
19608 (setq ll (org-do-wrap words maxword))
19609 (if (<= (length ll) lines)
19611 (setq ll words)
19612 (while (> (length ll) lines)
19613 (setq w (1+ w))
19614 (setq ll (org-do-wrap words w)))
19615 ll))
19616 (t (error "Cannot wrap this")))))
19618 (defun org-do-wrap (words width)
19619 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19620 (let (lines line)
19621 (while words
19622 (setq line (pop words))
19623 (while (and words (< (+ (length line) (length (car words))) width))
19624 (setq line (concat line " " (pop words))))
19625 (setq lines (push line lines)))
19626 (nreverse lines)))
19628 (defun org-split-string (string &optional separators)
19629 "Splits STRING into substrings at SEPARATORS.
19630 No empty strings are returned if there are matches at the beginning
19631 and end of string."
19632 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19633 (start 0)
19634 notfirst
19635 (list nil))
19636 (while (and (string-match rexp string
19637 (if (and notfirst
19638 (= start (match-beginning 0))
19639 (< start (length string)))
19640 (1+ start) start))
19641 (< (match-beginning 0) (length string)))
19642 (setq notfirst t)
19643 (or (eq (match-beginning 0) 0)
19644 (and (eq (match-beginning 0) (match-end 0))
19645 (eq (match-beginning 0) start))
19646 (setq list
19647 (cons (substring string start (match-beginning 0))
19648 list)))
19649 (setq start (match-end 0)))
19650 (or (eq start (length string))
19651 (setq list
19652 (cons (substring string start)
19653 list)))
19654 (nreverse list)))
19656 (defun org-quote-vert (s)
19657 "Replace \"|\" with \"\\vert\"."
19658 (while (string-match "|" s)
19659 (setq s (replace-match "\\vert" t t s)))
19662 (defun org-uuidgen-p (s)
19663 "Is S an ID created by UUIDGEN?"
19664 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19666 (defun org-in-src-block-p nil
19667 "Whether point is in a code source block."
19668 (let (ov)
19669 (when (setq ov (overlays-at (point)))
19670 (memq 'org-block-background
19671 (overlay-properties
19672 (car ov))))))
19674 (defun org-context ()
19675 "Return a list of contexts of the current cursor position.
19676 If several contexts apply, all are returned.
19677 Each context entry is a list with a symbol naming the context, and
19678 two positions indicating start and end of the context. Possible
19679 contexts are:
19681 :headline anywhere in a headline
19682 :headline-stars on the leading stars in a headline
19683 :todo-keyword on a TODO keyword (including DONE) in a headline
19684 :tags on the TAGS in a headline
19685 :priority on the priority cookie in a headline
19686 :item on the first line of a plain list item
19687 :item-bullet on the bullet/number of a plain list item
19688 :checkbox on the checkbox in a plain list item
19689 :table in an org-mode table
19690 :table-special on a special filed in a table
19691 :table-table in a table.el table
19692 :clocktable in a clocktable
19693 :src-block in a source block
19694 :link on a hyperlink
19695 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19696 :target on a <<target>>
19697 :radio-target on a <<<radio-target>>>
19698 :latex-fragment on a LaTeX fragment
19699 :latex-preview on a LaTeX fragment with overlaid preview image
19701 This function expects the position to be visible because it uses font-lock
19702 faces as a help to recognize the following contexts: :table-special, :link,
19703 and :keyword."
19704 (let* ((f (get-text-property (point) 'face))
19705 (faces (if (listp f) f (list f)))
19706 (case-fold-search t)
19707 (p (point)) clist o)
19708 ;; First the large context
19709 (cond
19710 ((org-at-heading-p t)
19711 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19712 (when (progn
19713 (beginning-of-line 1)
19714 (looking-at org-todo-line-tags-regexp))
19715 (push (org-point-in-group p 1 :headline-stars) clist)
19716 (push (org-point-in-group p 2 :todo-keyword) clist)
19717 (push (org-point-in-group p 4 :tags) clist))
19718 (goto-char p)
19719 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19720 (if (looking-at "\\[#[A-Z0-9]\\]")
19721 (push (org-point-in-group p 0 :priority) clist)))
19723 ((org-at-item-p)
19724 (push (org-point-in-group p 2 :item-bullet) clist)
19725 (push (list :item (point-at-bol)
19726 (save-excursion (org-end-of-item) (point)))
19727 clist)
19728 (and (org-at-item-checkbox-p)
19729 (push (org-point-in-group p 0 :checkbox) clist)))
19731 ((org-at-table-p)
19732 (push (list :table (org-table-begin) (org-table-end)) clist)
19733 (if (memq 'org-formula faces)
19734 (push (list :table-special
19735 (previous-single-property-change p 'face)
19736 (next-single-property-change p 'face)) clist)))
19737 ((org-at-table-p 'any)
19738 (push (list :table-table) clist)))
19739 (goto-char p)
19741 ;; New the "medium" contexts: clocktables, source blocks
19742 (cond ((org-in-clocktable-p)
19743 (push (list :clocktable
19744 (and (or (looking-at "#\\+BEGIN: clocktable")
19745 (search-backward "#+BEGIN: clocktable" nil t))
19746 (match-beginning 0))
19747 (and (re-search-forward "#\\+END:?" nil t)
19748 (match-end 0))) clist))
19749 ((org-in-src-block-p)
19750 (push (list :src-block
19751 (and (or (looking-at "#\\+BEGIN_SRC")
19752 (search-backward "#+BEGIN_SRC" nil t))
19753 (match-beginning 0))
19754 (and (search-forward "#+END_SRC" nil t)
19755 (match-beginning 0))) clist)))
19756 (goto-char p)
19758 ;; Now the small context
19759 (cond
19760 ((org-at-timestamp-p)
19761 (push (org-point-in-group p 0 :timestamp) clist))
19762 ((memq 'org-link faces)
19763 (push (list :link
19764 (previous-single-property-change p 'face)
19765 (next-single-property-change p 'face)) clist))
19766 ((memq 'org-special-keyword faces)
19767 (push (list :keyword
19768 (previous-single-property-change p 'face)
19769 (next-single-property-change p 'face)) clist))
19770 ((org-at-target-p)
19771 (push (org-point-in-group p 0 :target) clist)
19772 (goto-char (1- (match-beginning 0)))
19773 (if (looking-at org-radio-target-regexp)
19774 (push (org-point-in-group p 0 :radio-target) clist))
19775 (goto-char p))
19776 ((setq o (car (delq nil
19777 (mapcar
19778 (lambda (x)
19779 (if (memq x org-latex-fragment-image-overlays) x))
19780 (overlays-at (point))))))
19781 (push (list :latex-fragment
19782 (overlay-start o) (overlay-end o)) clist)
19783 (push (list :latex-preview
19784 (overlay-start o) (overlay-end o)) clist))
19785 ((org-inside-LaTeX-fragment-p)
19786 ;; FIXME: positions wrong.
19787 (push (list :latex-fragment (point) (point)) clist)))
19789 (setq clist (nreverse (delq nil clist)))
19790 clist))
19792 ;; FIXME: Compare with at-regexp-p Do we need both?
19793 (defun org-in-regexp (re &optional nlines visually)
19794 "Check if point is inside a match of regexp.
19795 Normally only the current line is checked, but you can include NLINES extra
19796 lines both before and after point into the search.
19797 If VISUALLY is set, require that the cursor is not after the match but
19798 really on, so that the block visually is on the match."
19799 (catch 'exit
19800 (let ((pos (point))
19801 (eol (point-at-eol (+ 1 (or nlines 0))))
19802 (inc (if visually 1 0)))
19803 (save-excursion
19804 (beginning-of-line (- 1 (or nlines 0)))
19805 (while (re-search-forward re eol t)
19806 (if (and (<= (match-beginning 0) pos)
19807 (>= (+ inc (match-end 0)) pos))
19808 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19810 (defun org-at-regexp-p (regexp)
19811 "Is point inside a match of REGEXP in the current line?"
19812 (catch 'exit
19813 (save-excursion
19814 (let ((pos (point)) (end (point-at-eol)))
19815 (beginning-of-line 1)
19816 (while (re-search-forward regexp end t)
19817 (if (and (<= (match-beginning 0) pos)
19818 (>= (match-end 0) pos))
19819 (throw 'exit t)))
19820 nil))))
19822 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19823 "Non-nil when point is between matches of START-RE and END-RE.
19825 Also return a non-nil value when point is on one of the matches.
19827 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19828 buffer positions. Default values are the positions of headlines
19829 surrounding the point.
19831 The functions returns a cons cell whose car (resp. cdr) is the
19832 position before START-RE (resp. after END-RE)."
19833 (save-match-data
19834 (let ((pos (point))
19835 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19836 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19837 beg end)
19838 (save-excursion
19839 ;; Point is on a block when on START-RE or if START-RE can be
19840 ;; found before it...
19841 (and (or (org-at-regexp-p start-re)
19842 (re-search-backward start-re limit-up t))
19843 (setq beg (match-beginning 0))
19844 ;; ... and END-RE after it...
19845 (goto-char (match-end 0))
19846 (re-search-forward end-re limit-down t)
19847 (> (setq end (match-end 0)) pos)
19848 ;; ... without another START-RE in-between.
19849 (goto-char (match-beginning 0))
19850 (not (re-search-backward start-re (1+ beg) t))
19851 ;; Return value.
19852 (cons beg end))))))
19854 (defun org-in-block-p (names)
19855 "Non-nil when point belongs to a block whose name belongs to NAMES.
19857 NAMES is a list of strings containing names of blocks.
19859 Return first block name matched, or nil. Beware that in case of
19860 nested blocks, the returned name may not belong to the closest
19861 block from point."
19862 (save-match-data
19863 (catch 'exit
19864 (let ((case-fold-search t)
19865 (lim-up (save-excursion (outline-previous-heading)))
19866 (lim-down (save-excursion (outline-next-heading))))
19867 (mapc (lambda (name)
19868 (let ((n (regexp-quote name)))
19869 (when (org-between-regexps-p
19870 (concat "^[ \t]*#\\+begin_" n)
19871 (concat "^[ \t]*#\\+end_" n)
19872 lim-up lim-down)
19873 (throw 'exit n))))
19874 names))
19875 nil)))
19877 (defun org-occur-in-agenda-files (regexp &optional nlines)
19878 "Call `multi-occur' with buffers for all agenda files."
19879 (interactive "sOrg-files matching: \np")
19880 (let* ((files (org-agenda-files))
19881 (tnames (mapcar 'file-truename files))
19882 (extra org-agenda-text-search-extra-files)
19884 (when (eq (car extra) 'agenda-archives)
19885 (setq extra (cdr extra))
19886 (setq files (org-add-archive-files files)))
19887 (while (setq f (pop extra))
19888 (unless (member (file-truename f) tnames)
19889 (add-to-list 'files f 'append)
19890 (add-to-list 'tnames (file-truename f) 'append)))
19891 (multi-occur
19892 (mapcar (lambda (x)
19893 (with-current-buffer
19894 (or (get-file-buffer x) (find-file-noselect x))
19895 (widen)
19896 (current-buffer)))
19897 files)
19898 regexp)))
19900 (if (boundp 'occur-mode-find-occurrence-hook)
19901 ;; Emacs 23
19902 (add-hook 'occur-mode-find-occurrence-hook
19903 (lambda ()
19904 (when (eq major-mode 'org-mode)
19905 (org-reveal))))
19906 ;; Emacs 22
19907 (defadvice occur-mode-goto-occurrence
19908 (after org-occur-reveal activate)
19909 (and (eq major-mode 'org-mode) (org-reveal)))
19910 (defadvice occur-mode-goto-occurrence-other-window
19911 (after org-occur-reveal activate)
19912 (and (eq major-mode 'org-mode) (org-reveal)))
19913 (defadvice occur-mode-display-occurrence
19914 (after org-occur-reveal activate)
19915 (when (eq major-mode 'org-mode)
19916 (let ((pos (occur-mode-find-occurrence)))
19917 (with-current-buffer (marker-buffer pos)
19918 (save-excursion
19919 (goto-char pos)
19920 (org-reveal)))))))
19922 (defun org-occur-link-in-agenda-files ()
19923 "Create a link and search for it in the agendas.
19924 The link is not stored in `org-stored-links', it is just created
19925 for the search purpose."
19926 (interactive)
19927 (let ((link (condition-case nil
19928 (org-store-link nil)
19929 (error "Unable to create a link to here"))))
19930 (org-occur-in-agenda-files (regexp-quote link))))
19932 (defun org-uniquify (list)
19933 "Remove duplicate elements from LIST."
19934 (let (res)
19935 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19936 res))
19938 (defun org-delete-all (elts list)
19939 "Remove all elements in ELTS from LIST."
19940 (while elts
19941 (setq list (delete (pop elts) list)))
19942 list)
19944 (defun org-count (cl-item cl-seq)
19945 "Count the number of occurrences of ITEM in SEQ.
19946 Taken from `count' in cl-seq.el with all keyword arguments removed."
19947 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19948 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19949 (while (< cl-start cl-end)
19950 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19951 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19952 (setq cl-start (1+ cl-start)))
19953 cl-count))
19955 (defun org-remove-if (predicate seq)
19956 "Remove everything from SEQ that fulfills PREDICATE."
19957 (let (res e)
19958 (while seq
19959 (setq e (pop seq))
19960 (if (not (funcall predicate e)) (push e res)))
19961 (nreverse res)))
19963 (defun org-remove-if-not (predicate seq)
19964 "Remove everything from SEQ that does not fulfill PREDICATE."
19965 (let (res e)
19966 (while seq
19967 (setq e (pop seq))
19968 (if (funcall predicate e) (push e res)))
19969 (nreverse res)))
19971 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19972 "Reduce two-argument FUNCTION across SEQ.
19973 Taken from `reduce' in cl-seq.el with all keyword arguments but
19974 \":initial-value\" removed."
19975 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19976 (cadr (memq :initial-value cl-keys)))
19977 (cl-seq (pop cl-seq))
19978 (t (funcall cl-func)))))
19979 (while cl-seq
19980 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19981 cl-accum))
19983 (defun org-back-over-empty-lines ()
19984 "Move backwards over whitespace, to the beginning of the first empty line.
19985 Returns the number of empty lines passed."
19986 (let ((pos (point)))
19987 (if (cdr (assoc 'heading org-blank-before-new-entry))
19988 (skip-chars-backward " \t\n\r")
19989 (unless (eobp)
19990 (forward-line -1)))
19991 (beginning-of-line 2)
19992 (goto-char (min (point) pos))
19993 (count-lines (point) pos)))
19995 (defun org-skip-whitespace ()
19996 (skip-chars-forward " \t\n\r"))
19998 (defun org-point-in-group (point group &optional context)
19999 "Check if POINT is in match-group GROUP.
20000 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20001 match. If the match group does not exist or point is not inside it,
20002 return nil."
20003 (and (match-beginning group)
20004 (>= point (match-beginning group))
20005 (<= point (match-end group))
20006 (if context
20007 (list context (match-beginning group) (match-end group))
20008 t)))
20010 (defun org-switch-to-buffer-other-window (&rest args)
20011 "Switch to buffer in a second window on the current frame.
20012 In particular, do not allow pop-up frames.
20013 Returns the newly created buffer."
20014 (let (pop-up-frames special-display-buffer-names special-display-regexps
20015 special-display-function)
20016 (apply 'switch-to-buffer-other-window args)))
20018 (defun org-combine-plists (&rest plists)
20019 "Create a single property list from all plists in PLISTS.
20020 The process starts by copying the first list, and then setting properties
20021 from the other lists. Settings in the last list are the most significant
20022 ones and overrule settings in the other lists."
20023 (let ((rtn (copy-sequence (pop plists)))
20024 p v ls)
20025 (while plists
20026 (setq ls (pop plists))
20027 (while ls
20028 (setq p (pop ls) v (pop ls))
20029 (setq rtn (plist-put rtn p v))))
20030 rtn))
20032 (defun org-move-line-down (arg)
20033 "Move the current line down. With prefix argument, move it past ARG lines."
20034 (interactive "p")
20035 (let ((col (current-column))
20036 beg end pos)
20037 (beginning-of-line 1) (setq beg (point))
20038 (beginning-of-line 2) (setq end (point))
20039 (beginning-of-line (+ 1 arg))
20040 (setq pos (move-marker (make-marker) (point)))
20041 (insert (delete-and-extract-region beg end))
20042 (goto-char pos)
20043 (org-move-to-column col)))
20045 (defun org-move-line-up (arg)
20046 "Move the current line up. With prefix argument, move it past ARG lines."
20047 (interactive "p")
20048 (let ((col (current-column))
20049 beg end pos)
20050 (beginning-of-line 1) (setq beg (point))
20051 (beginning-of-line 2) (setq end (point))
20052 (beginning-of-line (- arg))
20053 (setq pos (move-marker (make-marker) (point)))
20054 (insert (delete-and-extract-region beg end))
20055 (goto-char pos)
20056 (org-move-to-column col)))
20058 (defun org-replace-escapes (string table)
20059 "Replace %-escapes in STRING with values in TABLE.
20060 TABLE is an association list with keys like \"%a\" and string values.
20061 The sequences in STRING may contain normal field width and padding information,
20062 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20063 so values can contain further %-escapes if they are define later in TABLE."
20064 (let ((tbl (copy-alist table))
20065 (case-fold-search nil)
20066 (pchg 0)
20067 e re rpl)
20068 (while (setq e (pop tbl))
20069 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20070 (when (and (cdr e) (string-match re (cdr e)))
20071 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20072 (safe "SREF"))
20073 (add-text-properties 0 3 (list 'sref sref) safe)
20074 (setcdr e (replace-match safe t t (cdr e)))))
20075 (while (string-match re string)
20076 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20077 (cdr e)))
20078 (setq string (replace-match rpl t t string))))
20079 (while (setq pchg (next-property-change pchg string))
20080 (let ((sref (get-text-property pchg 'sref string)))
20081 (when (and sref (string-match "SREF" string pchg))
20082 (setq string (replace-match sref t t string)))))
20083 string))
20085 (defun org-sublist (list start end)
20086 "Return a section of LIST, from START to END.
20087 Counting starts at 1."
20088 (let (rtn (c start))
20089 (setq list (nthcdr (1- start) list))
20090 (while (and list (<= c end))
20091 (push (pop list) rtn)
20092 (setq c (1+ c)))
20093 (nreverse rtn)))
20095 (defun org-find-base-buffer-visiting (file)
20096 "Like `find-buffer-visiting' but always return the base buffer and
20097 not an indirect buffer."
20098 (let ((buf (or (get-file-buffer file)
20099 (find-buffer-visiting file))))
20100 (if buf
20101 (or (buffer-base-buffer buf) buf)
20102 nil)))
20104 (defun org-image-file-name-regexp (&optional extensions)
20105 "Return regexp matching the file names of images.
20106 If EXTENSIONS is given, only match these."
20107 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20108 (image-file-name-regexp)
20109 (let ((image-file-name-extensions
20110 (or extensions
20111 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20112 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20113 (concat "\\."
20114 (regexp-opt (nconc (mapcar 'upcase
20115 image-file-name-extensions)
20116 image-file-name-extensions)
20118 "\\'"))))
20120 (defun org-file-image-p (file &optional extensions)
20121 "Return non-nil if FILE is an image."
20122 (save-match-data
20123 (string-match (org-image-file-name-regexp extensions) file)))
20125 (defun org-get-cursor-date ()
20126 "Return the date at cursor in as a time.
20127 This works in the calendar and in the agenda, anywhere else it just
20128 returns the current time."
20129 (let (date day defd)
20130 (cond
20131 ((eq major-mode 'calendar-mode)
20132 (setq date (calendar-cursor-to-date)
20133 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20134 ((eq major-mode 'org-agenda-mode)
20135 (setq day (get-text-property (point) 'day))
20136 (if day
20137 (setq date (calendar-gregorian-from-absolute day)
20138 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20139 (nth 2 date))))))
20140 (or defd (current-time))))
20142 (defvar org-agenda-action-marker (make-marker)
20143 "Marker pointing to the entry for the next agenda action.")
20145 (defun org-mark-entry-for-agenda-action ()
20146 "Mark the current entry as target of an agenda action.
20147 Agenda actions are actions executed from the agenda with the key `k',
20148 which make use of the date at the cursor."
20149 (interactive)
20150 (move-marker org-agenda-action-marker
20151 (save-excursion (org-back-to-heading t) (point))
20152 (current-buffer))
20153 (message
20154 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20156 (defun org-mark-subtree ()
20157 "Mark the current subtree.
20158 This puts point at the start of the current subtree, and mark at the end.
20160 If point is in an inline task, mark that task instead."
20161 (interactive)
20162 (let ((inline-task-p
20163 (and (featurep 'org-inlinetask)
20164 (org-inlinetask-in-task-p)))
20165 (beg))
20166 ;; Get beginning of subtree
20167 (cond
20168 (inline-task-p (org-inlinetask-goto-beginning))
20169 ((org-at-heading-p) (beginning-of-line))
20170 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20171 (setq beg (point))
20172 ;; Get end of it
20173 (if inline-task-p
20174 (org-inlinetask-goto-end)
20175 (org-end-of-subtree))
20176 ;; Mark zone
20177 (push-mark (point) nil t)
20178 (goto-char beg)))
20180 ;;; Paragraph filling stuff.
20181 ;; We want this to be just right, so use the full arsenal.
20183 (defun org-indent-line-function ()
20184 "Indent line depending on context."
20185 (interactive)
20186 (let* ((pos (point))
20187 (itemp (org-at-item-p))
20188 (case-fold-search t)
20189 (org-drawer-regexp (or org-drawer-regexp "\000"))
20190 (inline-task-p (and (featurep 'org-inlinetask)
20191 (org-inlinetask-in-task-p)))
20192 (inline-re (and inline-task-p
20193 (org-inlinetask-outline-regexp)))
20194 column)
20195 (beginning-of-line 1)
20196 (cond
20197 ;; Comments
20198 ((looking-at "# ") (setq column 0))
20199 ;; Headings
20200 ((looking-at org-outline-regexp) (setq column 0))
20201 ;; Included files
20202 ((looking-at "#\\+include:") (setq column 0))
20203 ;; Footnote definition
20204 ((looking-at org-footnote-definition-re) (setq column 0))
20205 ;; Literal examples
20206 ((looking-at "[ \t]*:\\( \\|$\\)")
20207 (setq column (org-get-indentation))) ; do nothing
20208 ;; Lists
20209 ((ignore-errors (goto-char (org-in-item-p)))
20210 (setq column (if itemp
20211 (org-get-indentation)
20212 (org-list-item-body-column (point))))
20213 (goto-char pos))
20214 ;; Drawers
20215 ((and (looking-at "[ \t]*:END:")
20216 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20217 (save-excursion
20218 (goto-char (1- (match-beginning 1)))
20219 (setq column (current-column))))
20220 ;; Special blocks
20221 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20222 (save-excursion
20223 (re-search-backward
20224 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20225 (setq column (org-get-indentation (match-string 0))))
20226 ((and (not (looking-at "[ \t]*#\\+begin_"))
20227 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20228 (save-excursion
20229 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20230 (setq column
20231 (cond ((equal (downcase (match-string 1)) "src")
20232 ;; src blocks: let `org-edit-src-exit' handle them
20233 (org-get-indentation))
20234 ((equal (downcase (match-string 1)) "example")
20235 (max (org-get-indentation)
20236 (org-get-indentation (match-string 0))))
20238 (org-get-indentation (match-string 0))))))
20239 ;; This line has nothing special, look at the previous relevant
20240 ;; line to compute indentation
20242 (beginning-of-line 0)
20243 (while (and (not (bobp))
20244 (not (looking-at org-drawer-regexp))
20245 ;; When point started in an inline task, do not move
20246 ;; above task starting line.
20247 (not (and inline-task-p (looking-at inline-re)))
20248 ;; Skip drawers, blocks, empty lines, verbatim,
20249 ;; comments, tables, footnotes definitions, lists,
20250 ;; inline tasks.
20251 (or (and (looking-at "[ \t]*:END:")
20252 (re-search-backward org-drawer-regexp nil t))
20253 (and (looking-at "[ \t]*#\\+end_")
20254 (re-search-backward "[ \t]*#\\+begin_"nil t))
20255 (looking-at "[ \t]*[\n:#|]")
20256 (looking-at org-footnote-definition-re)
20257 (and (ignore-errors (goto-char (org-in-item-p)))
20258 (goto-char
20259 (org-list-get-top-point (org-list-struct))))
20260 (and (not inline-task-p)
20261 (featurep 'org-inlinetask)
20262 (org-inlinetask-in-task-p)
20263 (or (org-inlinetask-goto-beginning) t))))
20264 (beginning-of-line 0))
20265 (cond
20266 ;; There was an heading above.
20267 ((looking-at "\\*+[ \t]+")
20268 (if (not org-adapt-indentation)
20269 (setq column 0)
20270 (goto-char (match-end 0))
20271 (setq column (current-column))))
20272 ;; A drawer had started and is unfinished
20273 ((looking-at org-drawer-regexp)
20274 (goto-char (1- (match-beginning 1)))
20275 (setq column (current-column)))
20276 ;; Else, nothing noticeable found: get indentation and go on.
20277 (t (setq column (org-get-indentation))))))
20278 ;; Now apply indentation and move cursor accordingly
20279 (goto-char pos)
20280 (if (<= (current-column) (current-indentation))
20281 (org-indent-line-to column)
20282 (save-excursion (org-indent-line-to column)))
20283 ;; Special polishing for properties, see `org-property-format'
20284 (setq column (current-column))
20285 (beginning-of-line 1)
20286 (if (looking-at
20287 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20288 (replace-match (concat (match-string 1)
20289 (format org-property-format
20290 (match-string 2) (match-string 3)))
20291 t t))
20292 (org-move-to-column column)))
20294 (defun org-indent-drawer ()
20295 "Indent the drawer at point."
20296 (interactive)
20297 (let ((p (point))
20298 (e (and (save-excursion (re-search-forward ":END:" nil t))
20299 (match-end 0)))
20300 (folded
20301 (save-excursion
20302 (end-of-line)
20303 (when (overlays-at (point))
20304 (member 'invisible (overlay-properties
20305 (car (overlays-at (point)))))))))
20306 (when folded (org-cycle))
20307 (indent-for-tab-command)
20308 (while (and (move-beginning-of-line 2) (< (point) e))
20309 (indent-for-tab-command))
20310 (goto-char p)
20311 (when folded (org-cycle)))
20312 (message "Drawer at point indented"))
20314 (defun org-indent-block ()
20315 "Indent the block at point."
20316 (interactive)
20317 (let ((p (point))
20318 (case-fold-search t)
20319 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20320 (match-end 0)))
20321 (folded
20322 (save-excursion
20323 (end-of-line)
20324 (when (overlays-at (point))
20325 (member 'invisible (overlay-properties
20326 (car (overlays-at (point)))))))))
20327 (when folded (org-cycle))
20328 (indent-for-tab-command)
20329 (while (and (move-beginning-of-line 2) (< (point) e))
20330 (indent-for-tab-command))
20331 (goto-char p)
20332 (when folded (org-cycle)))
20333 (message "Block at point indented"))
20335 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20336 "Variable to store copy of `adaptive-fill-regexp'.
20337 Since `adaptive-fill-regexp' is set to never match, we need to
20338 store a backup of its value before entering `org-mode' so that
20339 the functionality can be provided as a fall-back.")
20341 (defun org-set-autofill-regexps ()
20342 (interactive)
20343 ;; In the paragraph separator we include headlines, because filling
20344 ;; text in a line directly attached to a headline would otherwise
20345 ;; fill the headline as well.
20346 (org-set-local 'comment-start-skip "^#+[ \t]*")
20347 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20348 ;; The paragraph starter includes hand-formatted lists.
20349 (org-set-local
20350 'paragraph-start
20351 (concat
20352 "\f" "\\|"
20353 "[ ]*$" "\\|"
20354 org-outline-regexp "\\|"
20355 "[ \t]*#" "\\|"
20356 (org-item-re) "\\|"
20357 "[ \t]*[:|]" "\\|"
20358 "\\$\\$" "\\|"
20359 "\\\\\\(begin\\|end\\|[][]\\)"))
20360 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20361 ;; But only if the user has not turned off tables or fixed-width regions
20362 (org-set-local
20363 'auto-fill-inhibit-regexp
20364 (concat org-outline-regexp
20365 "\\|#\\+"
20366 "\\|[ \t]*" org-keyword-time-regexp
20367 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20368 (concat
20369 "\\|[ \t]*["
20370 (if org-enable-table-editor "|" "")
20371 (if org-enable-fixed-width-editor ":" "")
20372 "]"))))
20373 ;; We use our own fill-paragraph function, to make sure that tables
20374 ;; and fixed-width regions are not wrapped. That function will pass
20375 ;; through to `fill-paragraph' when appropriate.
20376 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20377 ;; Prevent auto-fill from inserting unwanted new items.
20378 (if (boundp 'fill-nobreak-predicate)
20379 (org-set-local
20380 'fill-nobreak-predicate
20381 (org-uniquify
20382 (append fill-nobreak-predicate
20383 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20384 ;; Adaptive filling: To get full control, first make sure that
20385 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20386 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20387 (org-set-local 'org-adaptive-fill-regexp-backup
20388 adaptive-fill-regexp))
20389 (org-set-local 'adaptive-fill-regexp "\000")
20390 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20391 (org-set-local 'adaptive-fill-function
20392 'org-adaptive-fill-function)
20393 (org-set-local
20394 'align-mode-rules-list
20395 '((org-in-buffer-settings
20396 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20397 (modes . '(org-mode))))))
20399 (defun org-fill-item-nobreak-p ()
20400 "Non-nil when a line break at point would insert a new item."
20401 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20403 (defun org-fill-line-break-nobreak-p ()
20404 "Non-nil when a line break at point would create an Org line break."
20405 (save-excursion
20406 (skip-chars-backward "[ \t]")
20407 (skip-chars-backward "\\\\")
20408 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20410 (defun org-fill-paragraph (&optional justify)
20411 "Re-align a table, pass through to fill-paragraph if no table."
20412 (let ((table-p (org-at-table-p))
20413 (table.el-p (org-at-table.el-p))
20414 (itemp (org-in-item-p)))
20415 (cond ((and (equal (char-after (point-at-bol)) ?*)
20416 (save-excursion (goto-char (point-at-bol))
20417 (looking-at org-outline-regexp)))
20418 t) ; skip headlines
20419 (table.el-p t) ; skip table.el tables
20420 (table-p (org-table-align) t) ; align Org tables
20421 (itemp ; align text in items
20422 (let* ((struct (save-excursion (goto-char itemp)
20423 (org-list-struct)))
20424 (parents (org-list-parents-alist struct))
20425 (children (org-list-get-children itemp struct parents))
20426 beg end prev next prefix)
20427 ;; Determine in which part of item point is: before
20428 ;; first child, after last child, between two
20429 ;; sub-lists, or simply in item if there's no child.
20430 (cond
20431 ((not children)
20432 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20433 beg itemp
20434 end (org-list-get-item-end itemp struct)))
20435 ((< (point) (setq next (car children)))
20436 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20437 beg itemp
20438 end next))
20439 ((> (point) (setq prev (car (last children))))
20440 (setq beg (org-list-get-item-end prev struct)
20441 end (org-list-get-item-end itemp struct)
20442 prefix (save-excursion
20443 (goto-char beg)
20444 (skip-chars-forward " \t")
20445 (make-string (current-column) ?\ ))))
20446 (t (catch 'exit
20447 (while (setq next (pop children))
20448 (if (> (point) next)
20449 (setq prev next)
20450 (setq beg (org-list-get-item-end prev struct)
20451 end next
20452 prefix (save-excursion
20453 (goto-char beg)
20454 (skip-chars-forward " \t")
20455 (make-string (current-column) ?\ )))
20456 (throw 'exit nil))))))
20457 ;; Use `fill-paragraph' with buffer narrowed to item
20458 ;; without any child, and with our computed PREFIX.
20459 (flet ((fill-context-prefix (from to &optional flr) prefix))
20460 (save-restriction
20461 (narrow-to-region beg end)
20462 (save-excursion (fill-paragraph justify)))) t))
20463 ;; Special case where point is not in a list but is on
20464 ;; a paragraph adjacent to a list: make sure this paragraph
20465 ;; doesn't get merged with the end of the list by narrowing
20466 ;; buffer first.
20467 ((save-excursion (forward-paragraph -1)
20468 (setq itemp (org-in-item-p)))
20469 (let ((struct (save-excursion (goto-char itemp)
20470 (org-list-struct))))
20471 (save-restriction
20472 (narrow-to-region (org-list-get-bottom-point struct)
20473 (save-excursion (forward-paragraph 1)
20474 (point)))
20475 (fill-paragraph justify) t)))
20476 ;; Else simply call `fill-paragraph'.
20477 (t nil))))
20479 ;; For reference, this is the default value of adaptive-fill-regexp
20480 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20482 (defun org-adaptive-fill-function ()
20483 "Return a fill prefix for org-mode files."
20484 (let (itemp)
20485 (save-excursion
20486 (cond
20487 ;; Comment line
20488 ((looking-at "#[ \t]+")
20489 (match-string-no-properties 0))
20490 ;; Plain list item
20491 ((org-at-item-p)
20492 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20493 ;; Point is in a list after `backward-paragraph': original
20494 ;; point wasn't in the list, or filling would have been taken
20495 ;; care of by `org-auto-fill-function', but the list and the
20496 ;; real paragraph are not separated by a blank line. Thus, move
20497 ;; point after the list to go back to real paragraph and
20498 ;; determine fill-prefix.
20499 ((setq itemp (org-in-item-p))
20500 (goto-char itemp)
20501 (let* ((struct (org-list-struct))
20502 (bottom (org-list-get-bottom-point struct)))
20503 (goto-char bottom)
20504 (make-string (org-get-indentation) ?\ )))
20505 ;; Other text
20506 ((looking-at org-adaptive-fill-regexp-backup)
20507 (match-string-no-properties 0))))))
20509 (defun org-auto-fill-function ()
20510 "Auto-fill function."
20511 (let (itemp prefix)
20512 ;; When in a list, compute an appropriate fill-prefix and make
20513 ;; sure it will be used by `do-auto-fill'.
20514 (if (setq itemp (org-in-item-p))
20515 (progn
20516 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20517 (flet ((fill-context-prefix (from to &optional flr) prefix))
20518 (do-auto-fill)))
20519 ;; Else just use `do-auto-fill'.
20520 (do-auto-fill))))
20522 ;;; Other stuff.
20524 (defun org-toggle-fixed-width-section (arg)
20525 "Toggle the fixed-width export.
20526 If there is no active region, the QUOTE keyword at the current headline is
20527 inserted or removed. When present, it causes the text between this headline
20528 and the next to be exported as fixed-width text, and unmodified.
20529 If there is an active region, this command adds or removes a colon as the
20530 first character of this line. If the first character of a line is a colon,
20531 this line is also exported in fixed-width font."
20532 (interactive "P")
20533 (let* ((cc 0)
20534 (regionp (org-region-active-p))
20535 (beg (if regionp (region-beginning) (point)))
20536 (end (if regionp (region-end)))
20537 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20538 (case-fold-search nil)
20539 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20540 off)
20541 (if regionp
20542 (save-excursion
20543 (goto-char beg)
20544 (setq cc (current-column))
20545 (beginning-of-line 1)
20546 (setq off (looking-at re))
20547 (while (> nlines 0)
20548 (setq nlines (1- nlines))
20549 (beginning-of-line 1)
20550 (cond
20551 (arg
20552 (org-move-to-column cc t)
20553 (insert ": \n")
20554 (forward-line -1))
20555 ((and off (looking-at re))
20556 (replace-match "" t t nil 1))
20557 ((not off) (org-move-to-column cc t) (insert ": ")))
20558 (forward-line 1)))
20559 (save-excursion
20560 (org-back-to-heading)
20561 (cond
20562 ((looking-at (format org-heading-keyword-regexp-format
20563 org-quote-string))
20564 (goto-char (match-end 1))
20565 (looking-at (concat " +" org-quote-string))
20566 (replace-match "" t t)
20567 (when (eolp) (insert " ")))
20568 ((looking-at org-outline-regexp)
20569 (goto-char (match-end 0))
20570 (insert org-quote-string " ")))))))
20572 (defun org-reftex-citation ()
20573 "Use reftex-citation to insert a citation into the buffer.
20574 This looks for a line like
20576 #+BIBLIOGRAPHY: foo plain option:-d
20578 and derives from it that foo.bib is the bibliography file relevant
20579 for this document. It then installs the necessary environment for RefTeX
20580 to work in this buffer and calls `reftex-citation' to insert a citation
20581 into the buffer.
20583 Export of such citations to both LaTeX and HTML is handled by the contributed
20584 package org-exp-bibtex by Taru Karttunen."
20585 (interactive)
20586 (let ((reftex-docstruct-symbol 'rds)
20587 (reftex-cite-format "\\cite{%l}")
20588 rds bib)
20589 (save-excursion
20590 (save-restriction
20591 (widen)
20592 (let ((case-fold-search t)
20593 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20594 (if (not (save-excursion
20595 (or (re-search-forward re nil t)
20596 (re-search-backward re nil t))))
20597 (error "No bibliography defined in file")
20598 (setq bib (concat (match-string 1) ".bib")
20599 rds (list (list 'bib bib)))))))
20600 (call-interactively 'reftex-citation)))
20602 ;;;; Functions extending outline functionality
20604 (defun org-beginning-of-line (&optional arg)
20605 "Go to the beginning of the current line. If that is invisible, continue
20606 to a visible line beginning. This makes the function of C-a more intuitive.
20607 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20608 first attempt, and only move to after the tags when the cursor is already
20609 beyond the end of the headline."
20610 (interactive "P")
20611 (let ((pos (point))
20612 (special (if (consp org-special-ctrl-a/e)
20613 (car org-special-ctrl-a/e)
20614 org-special-ctrl-a/e))
20615 refpos)
20616 (if (org-bound-and-true-p line-move-visual)
20617 (beginning-of-visual-line 1)
20618 (beginning-of-line 1))
20619 (if (and arg (fboundp 'move-beginning-of-line))
20620 (call-interactively 'move-beginning-of-line)
20621 (if (bobp)
20623 (backward-char 1)
20624 (if (org-truely-invisible-p)
20625 (while (and (not (bobp)) (org-truely-invisible-p))
20626 (backward-char 1)
20627 (beginning-of-line 1))
20628 (forward-char 1))))
20629 (when special
20630 (cond
20631 ((and (looking-at org-complex-heading-regexp)
20632 (= (char-after (match-end 1)) ?\ ))
20633 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20634 (point-at-eol)))
20635 (goto-char
20636 (if (eq special t)
20637 (cond ((> pos refpos) refpos)
20638 ((= pos (point)) refpos)
20639 (t (point)))
20640 (cond ((> pos (point)) (point))
20641 ((not (eq last-command this-command)) (point))
20642 (t refpos)))))
20643 ((org-at-item-p)
20644 ;; Being at an item and not looking at an the item means point
20645 ;; was previously moved to beginning of a visual line, whiche
20646 ;; doesn't contain the item. Therefore, do nothing special,
20647 ;; just stay here.
20648 (when (looking-at org-list-full-item-re)
20649 ;; Set special position at first white space character after
20650 ;; bullet, and check-box, if any.
20651 (let ((after-bullet
20652 (let ((box (match-end 3)))
20653 (if (not box) (match-end 1)
20654 (let ((after (char-after box)))
20655 (if (and after (= after ? )) (1+ box) box))))))
20656 ;; Special case: Move point to special position when
20657 ;; currently after it or at beginning of line.
20658 (if (eq special t)
20659 (when (or (> pos after-bullet) (= (point) pos))
20660 (goto-char after-bullet))
20661 ;; Reversed case: Move point to special position when
20662 ;; point was already at beginning of line and command is
20663 ;; repeated.
20664 (when (and (= (point) pos) (eq last-command this-command))
20665 (goto-char after-bullet))))))))
20666 (org-no-warnings
20667 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20669 (defun org-end-of-line (&optional arg)
20670 "Go to the end of the line.
20671 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20672 first attempt, and only move to after the tags when the cursor is already
20673 beyond the end of the headline."
20674 (interactive "P")
20675 (let ((special (if (consp org-special-ctrl-a/e)
20676 (cdr org-special-ctrl-a/e)
20677 org-special-ctrl-a/e)))
20678 (cond
20679 ((or (not special) arg
20680 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20681 (call-interactively
20682 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20683 ((fboundp 'move-end-of-line) 'move-end-of-line)
20684 (t 'end-of-line))))
20685 ((org-at-heading-p)
20686 (let ((pos (point)))
20687 (beginning-of-line 1)
20688 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20689 (if (eq special t)
20690 (if (or (< pos (match-beginning 1))
20691 (= pos (match-end 0)))
20692 (goto-char (match-beginning 1))
20693 (goto-char (match-end 0)))
20694 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20695 (goto-char (match-end 0))
20696 (goto-char (match-beginning 1))))
20697 (call-interactively (if (fboundp 'move-end-of-line)
20698 'move-end-of-line
20699 'end-of-line)))))
20700 ((org-at-drawer-p)
20701 (move-end-of-line 1)
20702 (when (overlays-at (1- (point))) (backward-char 1)))
20703 ;; At an item: Move before any hidden text.
20704 (t (call-interactively
20705 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20706 ((fboundp 'move-end-of-line) 'move-end-of-line)
20707 (t 'end-of-line)))))
20708 (org-no-warnings
20709 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20711 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20712 (define-key org-mode-map "\C-e" 'org-end-of-line)
20714 (defun org-backward-sentence (&optional arg)
20715 "Go to beginning of sentence, or beginning of table field.
20716 This will call `backward-sentence' or `org-table-beginning-of-field',
20717 depending on context."
20718 (interactive "P")
20719 (cond
20720 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20721 (t (call-interactively 'backward-sentence))))
20723 (defun org-forward-sentence (&optional arg)
20724 "Go to end of sentence, or end of table field.
20725 This will call `forward-sentence' or `org-table-end-of-field',
20726 depending on context."
20727 (interactive "P")
20728 (cond
20729 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20730 (t (call-interactively 'forward-sentence))))
20732 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20733 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20735 (defun org-kill-line (&optional arg)
20736 "Kill line, to tags or end of line."
20737 (interactive "P")
20738 (cond
20739 ((or (not org-special-ctrl-k)
20740 (bolp)
20741 (not (org-at-heading-p)))
20742 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20743 org-ctrl-k-protect-subtree)
20744 (if (or (eq org-ctrl-k-protect-subtree 'error)
20745 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20746 (error "C-k aborted - would kill hidden subtree")))
20747 (call-interactively
20748 (if visual-line-mode 'kill-visual-line 'kill-line)))
20749 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20750 (kill-region (point) (match-beginning 1))
20751 (org-set-tags nil t))
20752 (t (kill-region (point) (point-at-eol)))))
20754 (define-key org-mode-map "\C-k" 'org-kill-line)
20756 (defun org-yank (&optional arg)
20757 "Yank. If the kill is a subtree, treat it specially.
20758 This command will look at the current kill and check if is a single
20759 subtree, or a series of subtrees[1]. If it passes the test, and if the
20760 cursor is at the beginning of a line or after the stars of a currently
20761 empty headline, then the yank is handled specially. How exactly depends
20762 on the value of the following variables, both set by default.
20764 org-yank-folded-subtrees
20765 When set, the subtree(s) will be folded after insertion, but only
20766 if doing so would now swallow text after the yanked text.
20768 org-yank-adjusted-subtrees
20769 When set, the subtree will be promoted or demoted in order to
20770 fit into the local outline tree structure, which means that the level
20771 will be adjusted so that it becomes the smaller one of the two
20772 *visible* surrounding headings.
20774 Any prefix to this command will cause `yank' to be called directly with
20775 no special treatment. In particular, a simple \\[universal-argument] prefix \
20776 will just
20777 plainly yank the text as it is.
20779 \[1] The test checks if the first non-white line is a heading
20780 and if there are no other headings with fewer stars."
20781 (interactive "P")
20782 (org-yank-generic 'yank arg))
20784 (defun org-yank-generic (command arg)
20785 "Perform some yank-like command.
20787 This function implements the behavior described in the `org-yank'
20788 documentation. However, it has been generalized to work for any
20789 interactive command with similar behavior."
20791 ;; pretend to be command COMMAND
20792 (setq this-command command)
20794 (if arg
20795 (call-interactively command)
20797 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20798 (and (org-kill-is-subtree-p)
20799 (or (bolp)
20800 (and (looking-at "[ \t]*$")
20801 (string-match
20802 "\\`\\*+\\'"
20803 (buffer-substring (point-at-bol) (point)))))))
20804 swallowp)
20805 (cond
20806 ((and subtreep org-yank-folded-subtrees)
20807 (let ((beg (point))
20808 end)
20809 (if (and subtreep org-yank-adjusted-subtrees)
20810 (org-paste-subtree nil nil 'for-yank)
20811 (call-interactively command))
20813 (setq end (point))
20814 (goto-char beg)
20815 (when (and (bolp) subtreep
20816 (not (setq swallowp
20817 (org-yank-folding-would-swallow-text beg end))))
20818 (org-with-limited-levels
20819 (or (looking-at org-outline-regexp)
20820 (re-search-forward org-outline-regexp-bol end t))
20821 (while (and (< (point) end) (looking-at org-outline-regexp))
20822 (hide-subtree)
20823 (org-cycle-show-empty-lines 'folded)
20824 (condition-case nil
20825 (outline-forward-same-level 1)
20826 (error (goto-char end))))))
20827 (when swallowp
20828 (message
20829 "Inserted text not folded because that would swallow text"))
20831 (goto-char end)
20832 (skip-chars-forward " \t\n\r")
20833 (beginning-of-line 1)
20834 (push-mark beg 'nomsg)))
20835 ((and subtreep org-yank-adjusted-subtrees)
20836 (let ((beg (point-at-bol)))
20837 (org-paste-subtree nil nil 'for-yank)
20838 (push-mark beg 'nomsg)))
20840 (call-interactively command))))))
20842 (defun org-yank-folding-would-swallow-text (beg end)
20843 "Would hide-subtree at BEG swallow any text after END?"
20844 (let (level)
20845 (org-with-limited-levels
20846 (save-excursion
20847 (goto-char beg)
20848 (when (or (looking-at org-outline-regexp)
20849 (re-search-forward org-outline-regexp-bol end t))
20850 (setq level (org-outline-level)))
20851 (goto-char end)
20852 (skip-chars-forward " \t\r\n\v\f")
20853 (if (or (eobp)
20854 (and (bolp) (looking-at org-outline-regexp)
20855 (<= (org-outline-level) level)))
20856 nil ; Nothing would be swallowed
20857 t))))) ; something would swallow
20859 (define-key org-mode-map "\C-y" 'org-yank)
20861 (defun org-truely-invisible-p ()
20862 "Check if point is at a character currently not visible.
20863 This version does not only check the character property, but also
20864 `visible-mode'."
20865 ;; Early versions of noutline don't have `outline-invisible-p'.
20866 (if (org-bound-and-true-p visible-mode)
20868 (outline-invisible-p)))
20870 (defun org-invisible-p2 ()
20871 "Check if point is at a character currently not visible."
20872 (save-excursion
20873 (if (and (eolp) (not (bobp))) (backward-char 1))
20874 ;; Early versions of noutline don't have `outline-invisible-p'.
20875 (outline-invisible-p)))
20877 (defun org-back-to-heading (&optional invisible-ok)
20878 "Call `outline-back-to-heading', but provide a better error message."
20879 (condition-case nil
20880 (outline-back-to-heading invisible-ok)
20881 (error (error "Before first headline at position %d in buffer %s"
20882 (point) (current-buffer)))))
20884 (defun org-beginning-of-defun ()
20885 "Go to the beginning of the subtree, i.e. back to the heading."
20886 (org-back-to-heading))
20887 (defun org-end-of-defun ()
20888 "Go to the end of the subtree."
20889 (org-end-of-subtree nil t))
20891 (defun org-before-first-heading-p ()
20892 "Before first heading?"
20893 (save-excursion
20894 (end-of-line)
20895 (null (re-search-backward org-outline-regexp-bol nil t))))
20897 (defun org-at-heading-p (&optional ignored)
20898 (outline-on-heading-p t))
20899 ;; Compatibility alias with Org versions < 7.8.03
20900 (defalias 'org-on-heading-p 'org-at-heading-p)
20902 (defun org-at-drawer-p nil
20903 "Is cursor at a drawer keyword?"
20904 (save-excursion
20905 (move-beginning-of-line 1)
20906 (looking-at org-drawer-regexp)))
20908 (defun org-at-block-p nil
20909 "Is cursor at a block keyword?"
20910 (save-excursion
20911 (move-beginning-of-line 1)
20912 (looking-at org-block-regexp)))
20914 (defun org-point-at-end-of-empty-headline ()
20915 "If point is at the end of an empty headline, return t, else nil.
20916 If the heading only contains a TODO keyword, it is still still considered
20917 empty."
20918 (and (looking-at "[ \t]*$")
20919 (save-excursion
20920 (beginning-of-line 1)
20921 (let ((case-fold-search nil))
20922 (looking-at org-todo-line-regexp)))
20923 (string= (match-string 3) "")))
20925 (defun org-at-heading-or-item-p ()
20926 (or (org-at-heading-p) (org-at-item-p)))
20928 (defun org-at-target-p ()
20929 (or (org-in-regexp org-radio-target-regexp)
20930 (org-in-regexp org-target-regexp)))
20931 ;; Compatibility alias with Org versions < 7.8.03
20932 (defalias 'org-on-target-p 'org-at-target-p)
20934 (defun org-up-heading-all (arg)
20935 "Move to the heading line of which the present line is a subheading.
20936 This function considers both visible and invisible heading lines.
20937 With argument, move up ARG levels."
20938 (if (fboundp 'outline-up-heading-all)
20939 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20940 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20942 (defun org-up-heading-safe ()
20943 "Move to the heading line of which the present line is a subheading.
20944 This version will not throw an error. It will return the level of the
20945 headline found, or nil if no higher level is found.
20947 Also, this function will be a lot faster than `outline-up-heading',
20948 because it relies on stars being the outline starters. This can really
20949 make a significant difference in outlines with very many siblings."
20950 (let (start-level re)
20951 (org-back-to-heading t)
20952 (setq start-level (funcall outline-level))
20953 (if (equal start-level 1)
20955 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20956 (if (re-search-backward re nil t)
20957 (funcall outline-level)))))
20959 (defun org-first-sibling-p ()
20960 "Is this heading the first child of its parents?"
20961 (interactive)
20962 (let ((re org-outline-regexp-bol)
20963 level l)
20964 (unless (org-at-heading-p t)
20965 (error "Not at a heading"))
20966 (setq level (funcall outline-level))
20967 (save-excursion
20968 (if (not (re-search-backward re nil t))
20970 (setq l (funcall outline-level))
20971 (< l level)))))
20973 (defun org-goto-sibling (&optional previous)
20974 "Goto the next sibling, even if it is invisible.
20975 When PREVIOUS is set, go to the previous sibling instead. Returns t
20976 when a sibling was found. When none is found, return nil and don't
20977 move point."
20978 (let ((fun (if previous 're-search-backward 're-search-forward))
20979 (pos (point))
20980 (re org-outline-regexp-bol)
20981 level l)
20982 (when (condition-case nil (org-back-to-heading t) (error nil))
20983 (setq level (funcall outline-level))
20984 (catch 'exit
20985 (or previous (forward-char 1))
20986 (while (funcall fun re nil t)
20987 (setq l (funcall outline-level))
20988 (when (< l level) (goto-char pos) (throw 'exit nil))
20989 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20990 (goto-char pos)
20991 nil))))
20993 (defun org-show-siblings ()
20994 "Show all siblings of the current headline."
20995 (save-excursion
20996 (while (org-goto-sibling) (org-flag-heading nil)))
20997 (save-excursion
20998 (while (org-goto-sibling 'previous)
20999 (org-flag-heading nil))))
21001 (defun org-goto-first-child ()
21002 "Goto the first child, even if it is invisible.
21003 Return t when a child was found. Otherwise don't move point and
21004 return nil."
21005 (let (level (pos (point)) (re org-outline-regexp-bol))
21006 (when (condition-case nil (org-back-to-heading t) (error nil))
21007 (setq level (outline-level))
21008 (forward-char 1)
21009 (if (and (re-search-forward re nil t) (> (outline-level) level))
21010 (progn (goto-char (match-beginning 0)) t)
21011 (goto-char pos) nil))))
21013 (defun org-show-hidden-entry ()
21014 "Show an entry where even the heading is hidden."
21015 (save-excursion
21016 (org-show-entry)))
21018 (defun org-flag-heading (flag &optional entry)
21019 "Flag the current heading. FLAG non-nil means make invisible.
21020 When ENTRY is non-nil, show the entire entry."
21021 (save-excursion
21022 (org-back-to-heading t)
21023 ;; Check if we should show the entire entry
21024 (if entry
21025 (progn
21026 (org-show-entry)
21027 (save-excursion
21028 (and (outline-next-heading)
21029 (org-flag-heading nil))))
21030 (outline-flag-region (max (point-min) (1- (point)))
21031 (save-excursion (outline-end-of-heading) (point))
21032 flag))))
21034 (defun org-get-next-sibling ()
21035 "Move to next heading of the same level, and return point.
21036 If there is no such heading, return nil.
21037 This is like outline-next-sibling, but invisible headings are ok."
21038 (let ((level (funcall outline-level)))
21039 (outline-next-heading)
21040 (while (and (not (eobp)) (> (funcall outline-level) level))
21041 (outline-next-heading))
21042 (if (or (eobp) (< (funcall outline-level) level))
21044 (point))))
21046 (defun org-get-last-sibling ()
21047 "Move to previous heading of the same level, and return point.
21048 If there is no such heading, return nil."
21049 (let ((opoint (point))
21050 (level (funcall outline-level)))
21051 (outline-previous-heading)
21052 (when (and (/= (point) opoint) (outline-on-heading-p t))
21053 (while (and (> (funcall outline-level) level)
21054 (not (bobp)))
21055 (outline-previous-heading))
21056 (if (< (funcall outline-level) level)
21058 (point)))))
21060 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21061 ;; This contains an exact copy of the original function, but it uses
21062 ;; `org-back-to-heading', to make it work also in invisible
21063 ;; trees. And is uses an invisible-OK argument.
21064 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21065 ;; Furthermore, when used inside Org, finding the end of a large subtree
21066 ;; with many children and grandchildren etc, this can be much faster
21067 ;; than the outline version.
21068 (org-back-to-heading invisible-OK)
21069 (let ((first t)
21070 (level (funcall outline-level)))
21071 (if (and (eq major-mode 'org-mode) (< level 1000))
21072 ;; A true heading (not a plain list item), in Org-mode
21073 ;; This means we can easily find the end by looking
21074 ;; only for the right number of stars. Using a regexp to do
21075 ;; this is so much faster than using a Lisp loop.
21076 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21077 (forward-char 1)
21078 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21079 ;; something else, do it the slow way
21080 (while (and (not (eobp))
21081 (or first (> (funcall outline-level) level)))
21082 (setq first nil)
21083 (outline-next-heading)))
21084 (unless to-heading
21085 (if (memq (preceding-char) '(?\n ?\^M))
21086 (progn
21087 ;; Go to end of line before heading
21088 (forward-char -1)
21089 (if (memq (preceding-char) '(?\n ?\^M))
21090 ;; leave blank line before heading
21091 (forward-char -1))))))
21092 (point))
21094 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21095 "Use Org version in org-mode, for dramatic speed-up."
21096 (if (eq major-mode 'org-mode)
21097 (progn
21098 (org-end-of-subtree nil t)
21099 (unless (eobp) (backward-char 1)))
21100 ad-do-it))
21102 (defun org-end-of-meta-data-and-drawers ()
21103 "Jump to the first text after meta data and drawers in the current entry.
21104 This will move over empty lines, lines with planning time stamps,
21105 clocking lines, and drawers."
21106 (org-back-to-heading t)
21107 (let ((end (save-excursion (outline-next-heading) (point)))
21108 (re (concat "\\(" org-drawer-regexp "\\)"
21109 "\\|" "[ \t]*" org-keyword-time-regexp)))
21110 (forward-line 1)
21111 (while (re-search-forward re end t)
21112 (if (not (match-end 1))
21113 ;; empty or planning line
21114 (forward-line 1)
21115 ;; a drawer, find the end
21116 (re-search-forward "^[ \t]*:END:" end 'move)
21117 (forward-line 1)))
21118 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21119 (point)))
21121 (defun org-forward-same-level (arg &optional invisible-ok)
21122 "Move forward to the arg'th subheading at same level as this one.
21123 Stop at the first and last subheadings of a superior heading.
21124 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21125 it wil also look at invisible ones."
21126 (interactive "p")
21127 (org-back-to-heading invisible-ok)
21128 (org-at-heading-p)
21129 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21130 (re (format "^\\*\\{1,%d\\} " level))
21132 (forward-char 1)
21133 (while (> arg 0)
21134 (while (and (re-search-forward re nil 'move)
21135 (setq l (- (match-end 0) (match-beginning 0) 1))
21136 (= l level)
21137 (not invisible-ok)
21138 (progn (backward-char 1) (outline-invisible-p)))
21139 (if (< l level) (setq arg 1)))
21140 (setq arg (1- arg)))
21141 (beginning-of-line 1)))
21143 (defun org-backward-same-level (arg &optional invisible-ok)
21144 "Move backward to the arg'th subheading at same level as this one.
21145 Stop at the first and last subheadings of a superior heading."
21146 (interactive "p")
21147 (org-back-to-heading)
21148 (org-at-heading-p)
21149 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21150 (re (format "^\\*\\{1,%d\\} " level))
21152 (while (> arg 0)
21153 (while (and (re-search-backward re nil 'move)
21154 (setq l (- (match-end 0) (match-beginning 0) 1))
21155 (= l level)
21156 (not invisible-ok)
21157 (outline-invisible-p))
21158 (if (< l level) (setq arg 1)))
21159 (setq arg (1- arg)))))
21161 (defun org-show-subtree ()
21162 "Show everything after this heading at deeper levels."
21163 (outline-flag-region
21164 (point)
21165 (save-excursion
21166 (org-end-of-subtree t t))
21167 nil))
21169 (defun org-show-entry ()
21170 "Show the body directly following this heading.
21171 Show the heading too, if it is currently invisible."
21172 (interactive)
21173 (save-excursion
21174 (condition-case nil
21175 (progn
21176 (org-back-to-heading t)
21177 (outline-flag-region
21178 (max (point-min) (1- (point)))
21179 (save-excursion
21180 (if (re-search-forward
21181 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21182 (match-beginning 1)
21183 (point-max)))
21184 nil)
21185 (org-cycle-hide-drawers 'children))
21186 (error nil))))
21188 (defun org-make-options-regexp (kwds &optional extra)
21189 "Make a regular expression for keyword lines."
21190 (concat
21192 "#?[ \t]*\\+\\("
21193 (mapconcat 'regexp-quote kwds "\\|")
21194 (if extra (concat "\\|" extra))
21195 "\\):[ \t]*"
21196 "\\(.*\\)"))
21198 ;; Make isearch reveal the necessary context
21199 (defun org-isearch-end ()
21200 "Reveal context after isearch exits."
21201 (when isearch-success ; only if search was successful
21202 (if (featurep 'xemacs)
21203 ;; Under XEmacs, the hook is run in the correct place,
21204 ;; we directly show the context.
21205 (org-show-context 'isearch)
21206 ;; In Emacs the hook runs *before* restoring the overlays.
21207 ;; So we have to use a one-time post-command-hook to do this.
21208 ;; (Emacs 22 has a special variable, see function `org-mode')
21209 (unless (and (boundp 'isearch-mode-end-hook-quit)
21210 isearch-mode-end-hook-quit)
21211 ;; Only when the isearch was not quitted.
21212 (org-add-hook 'post-command-hook 'org-isearch-post-command
21213 'append 'local)))))
21215 (defun org-isearch-post-command ()
21216 "Remove self from hook, and show context."
21217 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21218 (org-show-context 'isearch))
21221 ;;;; Integration with and fixes for other packages
21223 ;;; Imenu support
21225 (defvar org-imenu-markers nil
21226 "All markers currently used by Imenu.")
21227 (make-variable-buffer-local 'org-imenu-markers)
21229 (defun org-imenu-new-marker (&optional pos)
21230 "Return a new marker for use by Imenu, and remember the marker."
21231 (let ((m (make-marker)))
21232 (move-marker m (or pos (point)))
21233 (push m org-imenu-markers)
21236 (defun org-imenu-get-tree ()
21237 "Produce the index for Imenu."
21238 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21239 (setq org-imenu-markers nil)
21240 (let* ((n org-imenu-depth)
21241 (re (concat "^" (org-get-limited-outline-regexp)))
21242 (subs (make-vector (1+ n) nil))
21243 (last-level 0)
21244 m level head)
21245 (save-excursion
21246 (save-restriction
21247 (widen)
21248 (goto-char (point-max))
21249 (while (re-search-backward re nil t)
21250 (setq level (org-reduced-level (funcall outline-level)))
21251 (when (<= level n)
21252 (looking-at org-complex-heading-regexp)
21253 (setq head (org-link-display-format
21254 (org-match-string-no-properties 4))
21255 m (org-imenu-new-marker))
21256 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21257 (if (>= level last-level)
21258 (push (cons head m) (aref subs level))
21259 (push (cons head (aref subs (1+ level))) (aref subs level))
21260 (loop for i from (1+ level) to n do (aset subs i nil)))
21261 (setq last-level level)))))
21262 (aref subs 1)))
21264 (eval-after-load "imenu"
21265 '(progn
21266 (add-hook 'imenu-after-jump-hook
21267 (lambda ()
21268 (if (eq major-mode 'org-mode)
21269 (org-show-context 'org-goto))))))
21271 (defun org-link-display-format (link)
21272 "Replace a link with either the description, or the link target
21273 if no description is present"
21274 (save-match-data
21275 (if (string-match org-bracket-link-analytic-regexp link)
21276 (replace-match (if (match-end 5)
21277 (match-string 5 link)
21278 (concat (match-string 1 link)
21279 (match-string 3 link)))
21280 nil t link)
21281 link)))
21283 (defun org-toggle-link-display ()
21284 "Toggle the literal or descriptive display of links."
21285 (interactive)
21286 (if org-descriptive-links
21287 (progn (org-remove-from-invisibility-spec '(org-link))
21288 (org-restart-font-lock)
21289 (setq org-descriptive-links nil))
21290 (progn (add-to-invisibility-spec '(org-link))
21291 (org-restart-font-lock)
21292 (setq org-descriptive-links t))))
21294 ;; Speedbar support
21296 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21297 "Overlay marking the agenda restriction line in speedbar.")
21298 (overlay-put org-speedbar-restriction-lock-overlay
21299 'face 'org-agenda-restriction-lock)
21300 (overlay-put org-speedbar-restriction-lock-overlay
21301 'help-echo "Agendas are currently limited to this item.")
21302 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21304 (defun org-speedbar-set-agenda-restriction ()
21305 "Restrict future agenda commands to the location at point in speedbar.
21306 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21307 (interactive)
21308 (require 'org-agenda)
21309 (let (p m tp np dir txt)
21310 (cond
21311 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21312 'org-imenu t))
21313 (setq m (get-text-property p 'org-imenu-marker))
21314 (with-current-buffer (marker-buffer m)
21315 (goto-char m)
21316 (org-agenda-set-restriction-lock 'subtree)))
21317 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21318 'speedbar-function 'speedbar-find-file))
21319 (setq tp (previous-single-property-change
21320 (1+ p) 'speedbar-function)
21321 np (next-single-property-change
21322 tp 'speedbar-function)
21323 dir (speedbar-line-directory)
21324 txt (buffer-substring-no-properties (or tp (point-min))
21325 (or np (point-max))))
21326 (with-current-buffer (find-file-noselect
21327 (let ((default-directory dir))
21328 (expand-file-name txt)))
21329 (unless (eq major-mode 'org-mode)
21330 (error "Cannot restrict to non-Org-mode file"))
21331 (org-agenda-set-restriction-lock 'file)))
21332 (t (error "Don't know how to restrict Org-mode's agenda")))
21333 (move-overlay org-speedbar-restriction-lock-overlay
21334 (point-at-bol) (point-at-eol))
21335 (setq current-prefix-arg nil)
21336 (org-agenda-maybe-redo)))
21338 (eval-after-load "speedbar"
21339 '(progn
21340 (speedbar-add-supported-extension ".org")
21341 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21342 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21343 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21344 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21345 (add-hook 'speedbar-visiting-tag-hook
21346 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21348 ;;; Fixes and Hacks for problems with other packages
21350 ;; Make flyspell not check words in links, to not mess up our keymap
21351 (defun org-mode-flyspell-verify ()
21352 "Don't let flyspell put overlays at active buttons, or on
21353 {todo,all-time,additional-option-like}-keywords."
21354 (let ((pos (max (1- (point)) (point-min)))
21355 (word (thing-at-point 'word)))
21356 (and (not (get-text-property pos 'keymap))
21357 (not (get-text-property pos 'org-no-flyspell))
21358 (not (member word org-todo-keywords-1))
21359 (not (member word org-all-time-keywords))
21360 (not (member word org-additional-option-like-keywords)))))
21362 (defun org-remove-flyspell-overlays-in (beg end)
21363 "Remove flyspell overlays in region."
21364 (and (org-bound-and-true-p flyspell-mode)
21365 (fboundp 'flyspell-delete-region-overlays)
21366 (flyspell-delete-region-overlays beg end))
21367 (add-text-properties beg end '(org-no-flyspell t)))
21369 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21370 (eval-after-load "bookmark"
21371 '(if (boundp 'bookmark-after-jump-hook)
21372 ;; We can use the hook
21373 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21374 ;; Hook not available, use advice
21375 (defadvice bookmark-jump (after org-make-visible activate)
21376 "Make the position visible."
21377 (org-bookmark-jump-unhide))))
21379 ;; Make sure saveplace shows the location if it was hidden
21380 (eval-after-load "saveplace"
21381 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21382 "Make the position visible."
21383 (org-bookmark-jump-unhide)))
21385 ;; Make sure ecb shows the location if it was hidden
21386 (eval-after-load "ecb"
21387 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21388 "Make hierarchy visible when jumping into location from ECB tree buffer."
21389 (if (eq major-mode 'org-mode)
21390 (org-show-context))))
21392 (defun org-bookmark-jump-unhide ()
21393 "Unhide the current position, to show the bookmark location."
21394 (and (eq major-mode 'org-mode)
21395 (or (outline-invisible-p)
21396 (save-excursion (goto-char (max (point-min) (1- (point))))
21397 (outline-invisible-p)))
21398 (org-show-context 'bookmark-jump)))
21400 ;; Make session.el ignore our circular variable
21401 (eval-after-load "session"
21402 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21404 ;;;; Experimental code
21406 (defun org-closed-in-range ()
21407 "Sparse tree of items closed in a certain time range.
21408 Still experimental, may disappear in the future."
21409 (interactive)
21410 ;; Get the time interval from the user.
21411 (let* ((time1 (org-float-time
21412 (org-read-date nil 'to-time nil "Starting date: ")))
21413 (time2 (org-float-time
21414 (org-read-date nil 'to-time nil "End date:")))
21415 ;; callback function
21416 (callback (lambda ()
21417 (let ((time
21418 (org-float-time
21419 (apply 'encode-time
21420 (org-parse-time-string
21421 (match-string 1))))))
21422 ;; check if time in interval
21423 (and (>= time time1) (<= time time2))))))
21424 ;; make tree, check each match with the callback
21425 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21427 ;;;; Finish up
21429 (provide 'org)
21431 (run-hooks 'org-load-hook)
21433 ;;; org.el ends here