improve comment in local.mk template
[org-mode.git] / lisp / org.el
bloba2e5387f07a43ba6ba7e8ece5afe6783ca888c8d
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
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias)
83 (unless (boundp 'calendar-view-holidays-initially-flag)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially))
86 (unless (boundp 'calendar-view-diary-initially-flag)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially))
89 (unless (boundp 'diary-fancy-buffer)
90 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
92 (require 'outline)
93 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
94 ;; Other stuff we need.
95 (require 'time-date)
96 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
97 (require 'easymenu)
98 (require 'overlay)
100 (require 'org-macs)
101 (require 'org-entities)
102 (require 'org-compat)
103 (require 'org-faces)
104 (require 'org-list)
105 (require 'org-pcomplete)
106 (require 'org-src)
107 (require 'org-footnote)
109 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
110 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
111 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
112 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
113 (declare-function org-at-clock-log-p "org-clock" ())
114 (declare-function org-clock-timestamps-up "org-clock" ())
115 (declare-function org-clock-timestamps-down "org-clock" ())
117 ;; babel
118 (require 'ob)
119 (require 'ob-table)
120 (require 'ob-lob)
121 (require 'ob-ref)
122 (require 'ob-tangle)
123 (require 'ob-comint)
124 (require 'ob-keys)
126 ;; load languages based on value of `org-babel-load-languages'
127 (defvar org-babel-load-languages)
128 ;;;###autoload
129 (defun org-babel-do-load-languages (sym value)
130 "Load the languages defined in `org-babel-load-languages'."
131 (set-default sym value)
132 (mapc (lambda (pair)
133 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
134 (if active
135 (progn
136 (require (intern (concat "ob-" lang))))
137 (progn
138 (funcall 'fmakunbound
139 (intern (concat "org-babel-execute:" lang)))
140 (funcall 'fmakunbound
141 (intern (concat "org-babel-expand-body:" lang)))))))
142 org-babel-load-languages))
144 (defcustom org-babel-load-languages '((emacs-lisp . t))
145 "Languages which can be evaluated in Org-mode buffers.
146 This list can be used to load support for any of the languages
147 below, note that each language will depend on a different set of
148 system executables and/or Emacs modes. When a language is
149 \"loaded\", then code blocks in that language can be evaluated
150 with `org-babel-execute-src-block' bound by default to C-c
151 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
152 be set to remove code block evaluation from the C-c C-c
153 keybinding. By default only Emacs Lisp (which has no
154 requirements) is loaded."
155 :group 'org-babel
156 :set 'org-babel-do-load-languages
157 :version "24.1"
158 :type '(alist :tag "Babel Languages"
159 :key-type
160 (choice
161 (const :tag "Awk" awk)
162 (const :tag "C" C)
163 (const :tag "R" R)
164 (const :tag "Asymptote" asymptote)
165 (const :tag "Calc" calc)
166 (const :tag "Clojure" clojure)
167 (const :tag "CSS" css)
168 (const :tag "Ditaa" ditaa)
169 (const :tag "Dot" dot)
170 (const :tag "Emacs Lisp" emacs-lisp)
171 (const :tag "Fortran" fortran)
172 (const :tag "Gnuplot" gnuplot)
173 (const :tag "Haskell" haskell)
174 (const :tag "IO" io)
175 (const :tag "Java" java)
176 (const :tag "Javascript" js)
177 (const :tag "LaTeX" latex)
178 (const :tag "Ledger" ledger)
179 (const :tag "Lilypond" lilypond)
180 (const :tag "Maxima" maxima)
181 (const :tag "Matlab" matlab)
182 (const :tag "Mscgen" mscgen)
183 (const :tag "Ocaml" ocaml)
184 (const :tag "Octave" octave)
185 (const :tag "Org" org)
186 (const :tag "Perl" perl)
187 (const :tag "Pico Lisp" picolisp)
188 (const :tag "PlantUML" plantuml)
189 (const :tag "Python" python)
190 (const :tag "Ruby" ruby)
191 (const :tag "Sass" sass)
192 (const :tag "Scala" scala)
193 (const :tag "Scheme" scheme)
194 (const :tag "Screen" screen)
195 (const :tag "Shell Script" sh)
196 (const :tag "Shen" shen)
197 (const :tag "Sql" sql)
198 (const :tag "Sqlite" sqlite))
199 :value-type (boolean :tag "Activate" :value t)))
201 ;;;; Customization variables
202 (defcustom org-clone-delete-id nil
203 "Remove ID property of clones of a subtree.
204 When non-nil, clones of a subtree don't inherit the ID property.
205 Otherwise they inherit the ID property with a new unique
206 identifier."
207 :type 'boolean
208 :version "24.1"
209 :group 'org-id)
211 ;;; Version
212 (eval-when-compile
213 (defun org-release () "N/A")
214 (defun org-git-version () "N/A !!check installation!!")
215 (and (load (concat (org-find-library-dir "org") "../UTILITIES/org-fixup.el")
216 'noerror 'nomessage 'nosuffix)
217 (org-no-warnings (org-fixup))))
218 ;;;###autoload
219 (defun org-version (&optional here full message)
220 "Show the org-mode version in the echo area.
221 With prefix arg HERE, insert it at point."
222 (interactive "P")
223 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
224 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
225 (org-version (org-release))
226 (git-version (org-git-version))
227 (version (format "Org-mode version %s (%s @ %s)"
228 org-version
229 git-version
230 (if org-install-dir
231 (if (string= org-dir org-install-dir)
232 org-install-dir
233 (concat "mixed installation! " org-install-dir " and " org-dir))
234 "org-install.el can not be found!")))
235 (_version (if full version org-version)))
236 (if (org-called-interactively-p 'interactive)
237 (if here
238 (insert version)
239 (message version))
240 (if message (message _version))
241 _version)))
243 ;;; Compatibility constants
245 ;;; The custom variables
247 (defgroup org nil
248 "Outline-based notes management and organizer."
249 :tag "Org"
250 :group 'outlines
251 :group 'calendar)
253 (defcustom org-mode-hook nil
254 "Mode hook for Org-mode, run after the mode was turned on."
255 :group 'org
256 :type 'hook)
258 (defcustom org-load-hook nil
259 "Hook that is run after org.el has been loaded."
260 :group 'org
261 :type 'hook)
263 (defcustom org-log-buffer-setup-hook nil
264 "Hook that is run after an Org log buffer is created."
265 :group 'org
266 :version "24.1"
267 :type 'hook)
269 (defvar org-modules) ; defined below
270 (defvar org-modules-loaded nil
271 "Have the modules been loaded already?")
273 (defun org-load-modules-maybe (&optional force)
274 "Load all extensions listed in `org-modules'."
275 (when (or force (not org-modules-loaded))
276 (mapc (lambda (ext)
277 (condition-case nil (require ext)
278 (error (message "Problems while trying to load feature `%s'" ext))))
279 org-modules)
280 (setq org-modules-loaded t)))
282 (defun org-set-modules (var value)
283 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
284 (set var value)
285 (when (featurep 'org)
286 (org-load-modules-maybe 'force)))
288 (when (org-bound-and-true-p org-modules)
289 (let ((a (member 'org-infojs org-modules)))
290 (and a (setcar a 'org-jsinfo))))
292 (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)
293 "Modules that should always be loaded together with org.el.
294 If a description starts with <C>, the file is not part of Emacs
295 and loading it will require that you have downloaded and properly installed
296 the org-mode distribution.
298 You can also use this system to load external packages (i.e. neither Org
299 core modules, nor modules from the CONTRIB directory). Just add symbols
300 to the end of the list. If the package is called org-xyz.el, then you need
301 to add the symbol `xyz', and the package must have a call to
303 (provide 'org-xyz)"
304 :group 'org
305 :set 'org-set-modules
306 :type
307 '(set :greedy t
308 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
309 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
310 (const :tag " crypt: Encryption of subtrees" org-crypt)
311 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
312 (const :tag " docview: Links to doc-view buffers" org-docview)
313 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
314 (const :tag " id: Global IDs for identifying entries" org-id)
315 (const :tag " info: Links to Info nodes" org-info)
316 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
317 (const :tag " habit: Track your consistency with habits" org-habit)
318 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
319 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
320 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
321 (const :tag " mew Links to Mew folders/messages" org-mew)
322 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
323 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
324 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
325 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
326 (const :tag " vm: Links to VM folders/messages" org-vm)
327 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
328 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
329 (const :tag " mouse: Additional mouse support" org-mouse)
330 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
332 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
333 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
334 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
335 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
336 (const :tag "C collector: Collect properties into tables" org-collector)
337 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
338 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
339 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
340 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
341 (const :tag "C eval: Include command output as text" org-eval)
342 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
343 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
344 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
345 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
346 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
348 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
350 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
351 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
352 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
353 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
354 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
355 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
356 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
357 (const :tag "C mtags: Support for muse-like tags" org-mtags)
358 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
359 (const :tag "C registry: A registry for Org-mode links" org-registry)
360 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
361 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
362 (const :tag "C secretary: Team management with org-mode" org-secretary)
363 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
364 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
365 (const :tag "C track: Keep up with Org-mode development" org-track)
366 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
367 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
368 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
370 (defcustom org-support-shift-select nil
371 "Non-nil means make shift-cursor commands select text when possible.
373 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
374 start selecting a region, or enlarge regions started in this way.
375 In Org-mode, in special contexts, these same keys are used for
376 other purposes, important enough to compete with shift selection.
377 Org tries to balance these needs by supporting `shift-select-mode'
378 outside these special contexts, under control of this variable.
380 The default of this variable is nil, to avoid confusing behavior. Shifted
381 cursor keys will then execute Org commands in the following contexts:
382 - on a headline, changing TODO state (left/right) and priority (up/down)
383 - on a time stamp, changing the time
384 - in a plain list item, changing the bullet type
385 - in a property definition line, switching between allowed values
386 - in the BEGIN line of a clock table (changing the time block).
387 Outside these contexts, the commands will throw an error.
389 When this variable is t and the cursor is not in a special
390 context, Org-mode will support shift-selection for making and
391 enlarging regions. To make this more effective, the bullet
392 cycling will no longer happen anywhere in an item line, but only
393 if the cursor is exactly on the bullet.
395 If you set this variable to the symbol `always', then the keys
396 will not be special in headlines, property lines, and item lines,
397 to make shift selection work there as well. If this is what you
398 want, you can use the following alternative commands: `C-c C-t'
399 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
400 can be used to switch TODO sets, `C-c -' to cycle item bullet
401 types, and properties can be edited by hand or in column view.
403 However, when the cursor is on a timestamp, shift-cursor commands
404 will still edit the time stamp - this is just too good to give up.
406 XEmacs user should have this variable set to nil, because
407 `shift-select-mode' is in Emacs 23 or later only."
408 :group 'org
409 :type '(choice
410 (const :tag "Never" nil)
411 (const :tag "When outside special context" t)
412 (const :tag "Everywhere except timestamps" always)))
414 (defcustom org-loop-over-headlines-in-active-region nil
415 "Shall some commands act upon headlines in the active region?
417 When set to `t', some commands will be performed in all headlines
418 within the active region.
420 When set to `start-level', some commands will be performed in all
421 headlines within the active region, provided that these headlines
422 are of the same level than the first one.
424 When set to a string, those commands will be performed on the
425 matching headlines within the active region. Such string must be
426 a tags/property/todo match as it is used in the agenda tags view.
428 The list of commands is: `org-schedule', `org-deadline',
429 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
430 `org-archive-to-archive-sibling'. The archiving commands skip
431 already archived entries."
432 :type '(choice (const :tag "Don't loop" nil)
433 (const :tag "All headlines in active region" t)
434 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
435 (string :tag "Tags/Property/Todo matcher"))
436 :version "24.1"
437 :group 'org-todo
438 :group 'org-archive)
440 (defgroup org-startup nil
441 "Options concerning startup of Org-mode."
442 :tag "Org Startup"
443 :group 'org)
445 (defcustom org-startup-folded t
446 "Non-nil means entering Org-mode will switch to OVERVIEW.
447 This can also be configured on a per-file basis by adding one of
448 the following lines anywhere in the buffer:
450 #+STARTUP: fold (or `overview', this is equivalent)
451 #+STARTUP: nofold (or `showall', this is equivalent)
452 #+STARTUP: content
453 #+STARTUP: showeverything"
454 :group 'org-startup
455 :type '(choice
456 (const :tag "nofold: show all" nil)
457 (const :tag "fold: overview" t)
458 (const :tag "content: all headlines" content)
459 (const :tag "show everything, even drawers" showeverything)))
461 (defcustom org-startup-truncated t
462 "Non-nil means entering Org-mode will set `truncate-lines'.
463 This is useful since some lines containing links can be very long and
464 uninteresting. Also tables look terrible when wrapped."
465 :group 'org-startup
466 :type 'boolean)
468 (defcustom org-startup-indented nil
469 "Non-nil means turn on `org-indent-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: indent
474 #+STARTUP: noindent"
475 :group 'org-structure
476 :type '(choice
477 (const :tag "Not" nil)
478 (const :tag "Globally (slow on startup in large files)" t)))
480 (defcustom org-use-sub-superscripts t
481 "Non-nil means interpret \"_\" and \"^\" for export.
482 When this option is turned on, you can use TeX-like syntax for sub- and
483 superscripts. Several characters after \"_\" or \"^\" will be
484 considered as a single item - so grouping with {} is normally not
485 needed. For example, the following things will be parsed as single
486 sub- or superscripts.
488 10^24 or 10^tau several digits will be considered 1 item.
489 10^-12 or 10^-tau a leading sign with digits or a word
490 x^2-y^3 will be read as x^2 - y^3, because items are
491 terminated by almost any nonword/nondigit char.
492 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
494 Still, ambiguity is possible - so when in doubt use {} to enclose the
495 sub/superscript. If you set this variable to the symbol `{}',
496 the braces are *required* in order to trigger interpretations as
497 sub/superscript. This can be helpful in documents that need \"_\"
498 frequently in plain text.
500 Not all export backends support this, but HTML does.
502 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
503 :group 'org-startup
504 :group 'org-export-translation
505 :version "24.1"
506 :type '(choice
507 (const :tag "Always interpret" t)
508 (const :tag "Only with braces" {})
509 (const :tag "Never interpret" nil)))
511 (if (fboundp 'defvaralias)
512 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
515 (defcustom org-startup-with-beamer-mode nil
516 "Non-nil means turn on `org-beamer-mode' on startup.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
520 #+STARTUP: beamer"
521 :group 'org-startup
522 :version "24.1"
523 :type 'boolean)
525 (defcustom org-startup-align-all-tables nil
526 "Non-nil means align all tables when visiting a file.
527 This is useful when the column width in tables is forced with <N> cookies
528 in table fields. Such tables will look correct only after the first re-align.
529 This can also be configured on a per-file basis by adding one of
530 the following lines anywhere in the buffer:
531 #+STARTUP: align
532 #+STARTUP: noalign"
533 :group 'org-startup
534 :type 'boolean)
536 (defcustom org-startup-with-inline-images nil
537 "Non-nil means show inline images when loading a new Org file.
538 This can also be configured on a per-file basis by adding one of
539 the following lines anywhere in the buffer:
540 #+STARTUP: inlineimages
541 #+STARTUP: noinlineimages"
542 :group 'org-startup
543 :version "24.1"
544 :type 'boolean)
546 (defcustom org-insert-mode-line-in-empty-file nil
547 "Non-nil means insert the first line setting Org-mode in empty files.
548 When the function `org-mode' is called interactively in an empty file, this
549 normally means that the file name does not automatically trigger Org-mode.
550 To ensure that the file will always be in Org-mode in the future, a
551 line enforcing Org-mode will be inserted into the buffer, if this option
552 has been set."
553 :group 'org-startup
554 :type 'boolean)
556 (defcustom org-replace-disputed-keys nil
557 "Non-nil means use alternative key bindings for some keys.
558 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
559 These keys are also used by other packages like shift-selection-mode'
560 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
561 If you want to use Org-mode together with one of these other modes,
562 or more generally if you would like to move some Org-mode commands to
563 other keys, set this variable and configure the keys with the variable
564 `org-disputed-keys'.
566 This option is only relevant at load-time of Org-mode, and must be set
567 *before* org.el is loaded. Changing it requires a restart of Emacs to
568 become effective."
569 :group 'org-startup
570 :type 'boolean)
572 (defcustom org-use-extra-keys nil
573 "Non-nil means use extra key sequence definitions for certain commands.
574 This happens automatically if you run XEmacs or if `window-system'
575 is nil. This variable lets you do the same manually. You must
576 set it before loading org.
578 Example: on Carbon Emacs 22 running graphically, with an external
579 keyboard on a Powerbook, the default way of setting M-left might
580 not work for either Alt or ESC. Setting this variable will make
581 it work for ESC."
582 :group 'org-startup
583 :type 'boolean)
585 (if (fboundp 'defvaralias)
586 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
588 (defcustom org-disputed-keys
589 '(([(shift up)] . [(meta p)])
590 ([(shift down)] . [(meta n)])
591 ([(shift left)] . [(meta -)])
592 ([(shift right)] . [(meta +)])
593 ([(control shift right)] . [(meta shift +)])
594 ([(control shift left)] . [(meta shift -)]))
595 "Keys for which Org-mode and other modes compete.
596 This is an alist, cars are the default keys, second element specifies
597 the alternative to use when `org-replace-disputed-keys' is t.
599 Keys can be specified in any syntax supported by `define-key'.
600 The value of this option takes effect only at Org-mode's startup,
601 therefore you'll have to restart Emacs to apply it after changing."
602 :group 'org-startup
603 :type 'alist)
605 (defun org-key (key)
606 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
607 Or return the original if not disputed.
608 Also apply the translations defined in `org-xemacs-key-equivalents'."
609 (when org-replace-disputed-keys
610 (let* ((nkey (key-description key))
611 (x (org-find-if (lambda (x)
612 (equal (key-description (car x)) nkey))
613 org-disputed-keys)))
614 (setq key (if x (cdr x) key))))
615 (when (featurep 'xemacs)
616 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
617 key)
619 (defun org-find-if (predicate seq)
620 (catch 'exit
621 (while seq
622 (if (funcall predicate (car seq))
623 (throw 'exit (car seq))
624 (pop seq)))))
626 (defun org-defkey (keymap key def)
627 "Define a key, possibly translated, as returned by `org-key'."
628 (define-key keymap (org-key key) def))
630 (defcustom org-ellipsis nil
631 "The ellipsis to use in the Org-mode outline.
632 When nil, just use the standard three dots. When a string, use that instead,
633 When a face, use the standard 3 dots, but with the specified face.
634 The change affects only Org-mode (which will then use its own display table).
635 Changing this requires executing `M-x org-mode' in a buffer to become
636 effective."
637 :group 'org-startup
638 :type '(choice (const :tag "Default" nil)
639 (face :tag "Face" :value org-warning)
640 (string :tag "String" :value "...#")))
642 (defvar org-display-table nil
643 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
645 (defgroup org-keywords nil
646 "Keywords in Org-mode."
647 :tag "Org Keywords"
648 :group 'org)
650 (defcustom org-deadline-string "DEADLINE:"
651 "String to mark deadline entries.
652 A deadline is this string, followed by a time stamp. Should be a word,
653 terminated by a colon. You can insert a schedule keyword and
654 a timestamp with \\[org-deadline].
655 Changes become only effective after restarting Emacs."
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-scheduled-string "SCHEDULED:"
660 "String to mark scheduled TODO entries.
661 A schedule is this string, followed by a time stamp. Should be a word,
662 terminated by a colon. You can insert a schedule keyword and
663 a timestamp with \\[org-schedule].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-closed-string "CLOSED:"
669 "String used as the prefix for timestamps logging closing a TODO entry."
670 :group 'org-keywords
671 :type 'string)
673 (defcustom org-clock-string "CLOCK:"
674 "String used as prefix for timestamps clocking work hours on an item."
675 :group 'org-keywords
676 :type 'string)
678 (defcustom org-comment-string "COMMENT"
679 "Entries starting with this keyword will never be exported.
680 An entry can be toggled between COMMENT and normal with
681 \\[org-toggle-comment].
682 Changes become only effective after restarting Emacs."
683 :group 'org-keywords
684 :type 'string)
686 (defcustom org-quote-string "QUOTE"
687 "Entries starting with this keyword will be exported in fixed-width font.
688 Quoting applies only to the text in the entry following the headline, and does
689 not extend beyond the next headline, even if that is lower level.
690 An entry can be toggled between QUOTE and normal with
691 \\[org-toggle-fixed-width-section]."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-repeat-re
696 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
697 "Regular expression for specifying repeated events.
698 After a match, group 1 contains the repeat expression.")
700 (defgroup org-structure nil
701 "Options concerning the general structure of Org-mode files."
702 :tag "Org Structure"
703 :group 'org)
705 (defgroup org-reveal-location nil
706 "Options about how to make context of a location visible."
707 :tag "Org Reveal Location"
708 :group 'org-structure)
710 (defconst org-context-choice
711 '(choice
712 (const :tag "Always" t)
713 (const :tag "Never" nil)
714 (repeat :greedy t :tag "Individual contexts"
715 (cons
716 (choice :tag "Context"
717 (const agenda)
718 (const org-goto)
719 (const occur-tree)
720 (const tags-tree)
721 (const link-search)
722 (const mark-goto)
723 (const bookmark-jump)
724 (const isearch)
725 (const default))
726 (boolean))))
727 "Contexts for the reveal options.")
729 (defcustom org-show-hierarchy-above '((default . t))
730 "Non-nil means show full hierarchy when revealing a location.
731 Org-mode often shows locations in an org-mode file which might have
732 been invisible before. When this is set, the hierarchy of headings
733 above the exposed location is shown.
734 Turning this off for example for sparse trees makes them very compact.
735 Instead of t, this can also be an alist specifying this option for different
736 contexts. Valid contexts are
737 agenda when exposing an entry from the agenda
738 org-goto when using the command `org-goto' on key C-c C-j
739 occur-tree when using the command `org-occur' on key C-c /
740 tags-tree when constructing a sparse tree based on tags matches
741 link-search when exposing search matches associated with a link
742 mark-goto when exposing the jump goal of a mark
743 bookmark-jump when exposing a bookmark location
744 isearch when exiting from an incremental search
745 default default for all contexts not set explicitly"
746 :group 'org-reveal-location
747 :type org-context-choice)
749 (defcustom org-show-following-heading '((default . nil))
750 "Non-nil means show following heading when revealing a location.
751 Org-mode often shows locations in an org-mode file which might have
752 been invisible before. When this is set, the heading following the
753 match is shown.
754 Turning this off for example for sparse trees makes them very compact,
755 but makes it harder to edit the location of the match. In such a case,
756 use the command \\[org-reveal] to show more context.
757 Instead of t, this can also be an alist specifying this option for different
758 contexts. See `org-show-hierarchy-above' for valid contexts."
759 :group 'org-reveal-location
760 :type org-context-choice)
762 (defcustom org-show-siblings '((default . nil) (isearch t))
763 "Non-nil means show all sibling heading when revealing a location.
764 Org-mode often shows locations in an org-mode file which might have
765 been invisible before. When this is set, the sibling of the current entry
766 heading are all made visible. If `org-show-hierarchy-above' is t,
767 the same happens on each level of the hierarchy above the current entry.
769 By default this is on for the isearch context, off for all other contexts.
770 Turning this off for example for sparse trees makes them very compact,
771 but makes it harder to edit the location of the match. In such a case,
772 use the command \\[org-reveal] to show more context.
773 Instead of t, this can also be an alist specifying this option for different
774 contexts. See `org-show-hierarchy-above' for valid contexts."
775 :group 'org-reveal-location
776 :type org-context-choice)
778 (defcustom org-show-entry-below '((default . nil))
779 "Non-nil means show the entry below a headline when revealing a location.
780 Org-mode often shows locations in an org-mode file which might have
781 been invisible before. When this is set, the text below the headline that is
782 exposed is also shown.
784 By default this is off for all contexts.
785 Instead of t, this can also be an alist specifying this option for different
786 contexts. See `org-show-hierarchy-above' for valid contexts."
787 :group 'org-reveal-location
788 :type org-context-choice)
790 (defcustom org-indirect-buffer-display 'other-window
791 "How should indirect tree buffers be displayed?
792 This applies to indirect buffers created with the commands
793 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
794 Valid values are:
795 current-window Display in the current window
796 other-window Just display in another window.
797 dedicated-frame Create one new frame, and re-use it each time.
798 new-frame Make a new frame each time. Note that in this case
799 previously-made indirect buffers are kept, and you need to
800 kill these buffers yourself."
801 :group 'org-structure
802 :group 'org-agenda-windows
803 :type '(choice
804 (const :tag "In current window" current-window)
805 (const :tag "In current frame, other window" other-window)
806 (const :tag "Each time a new frame" new-frame)
807 (const :tag "One dedicated frame" dedicated-frame)))
809 (defcustom org-use-speed-commands nil
810 "Non-nil means activate single letter commands at beginning of a headline.
811 This may also be a function to test for appropriate locations where speed
812 commands should be active."
813 :group 'org-structure
814 :type '(choice
815 (const :tag "Never" nil)
816 (const :tag "At beginning of headline stars" t)
817 (function)))
819 (defcustom org-speed-commands-user nil
820 "Alist of additional speed commands.
821 This list will be checked before `org-speed-commands-default'
822 when the variable `org-use-speed-commands' is non-nil
823 and when the cursor is at the beginning of a headline.
824 The car if each entry is a string with a single letter, which must
825 be assigned to `self-insert-command' in the global map.
826 The cdr is either a command to be called interactively, a function
827 to be called, or a form to be evaluated.
828 An entry that is just a list with a single string will be interpreted
829 as a descriptive headline that will be added when listing the speed
830 commands in the Help buffer using the `?' speed command."
831 :group 'org-structure
832 :type '(repeat :value ("k" . ignore)
833 (choice :value ("k" . ignore)
834 (list :tag "Descriptive Headline" (string :tag "Headline"))
835 (cons :tag "Letter and Command"
836 (string :tag "Command letter")
837 (choice
838 (function)
839 (sexp))))))
841 (defgroup org-cycle nil
842 "Options concerning visibility cycling in Org-mode."
843 :tag "Org Cycle"
844 :group 'org-structure)
846 (defcustom org-cycle-skip-children-state-if-no-children t
847 "Non-nil means skip CHILDREN state in entries that don't have any."
848 :group 'org-cycle
849 :type 'boolean)
851 (defcustom org-cycle-max-level nil
852 "Maximum level which should still be subject to visibility cycling.
853 Levels higher than this will, for cycling, be treated as text, not a headline.
854 When `org-odd-levels-only' is set, a value of N in this variable actually
855 means 2N-1 stars as the limiting headline.
856 When nil, cycle all levels.
857 Note that the limiting level of cycling is also influenced by
858 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
859 `org-inlinetask-min-level' is, cycling will be limited to levels one less
860 than its value."
861 :group 'org-cycle
862 :type '(choice
863 (const :tag "No limit" nil)
864 (integer :tag "Maximum level")))
866 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
867 "Names of drawers. Drawers are not opened by cycling on the headline above.
868 Drawers only open with a TAB on the drawer line itself. A drawer looks like
869 this:
870 :DRAWERNAME:
871 .....
872 :END:
873 The drawer \"PROPERTIES\" is special for capturing properties through
874 the property API.
876 Drawers can be defined on the per-file basis with a line like:
878 #+DRAWERS: HIDDEN STATE PROPERTIES"
879 :group 'org-structure
880 :group 'org-cycle
881 :type '(repeat (string :tag "Drawer Name")))
883 (defcustom org-hide-block-startup nil
884 "Non-nil means entering Org-mode will fold all blocks.
885 This can also be set in on a per-file basis with
887 #+STARTUP: hideblocks
888 #+STARTUP: showblocks"
889 :group 'org-startup
890 :group 'org-cycle
891 :type 'boolean)
893 (defcustom org-cycle-global-at-bob nil
894 "Cycle globally if cursor is at beginning of buffer and not at a headline.
895 This makes it possible to do global cycling without having to use S-TAB or
896 \\[universal-argument] TAB. For this special case to work, the first line \
897 of the buffer
898 must not be a headline - it may be empty or some other text. When used in
899 this way, `org-cycle-hook' is disables temporarily, to make sure the
900 cursor stays at the beginning of the buffer.
901 When this option is nil, don't do anything special at the beginning
902 of the buffer."
903 :group 'org-cycle
904 :type 'boolean)
906 (defcustom org-cycle-level-after-item/entry-creation t
907 "Non-nil means cycle entry level or item indentation in new empty entries.
909 When the cursor is at the end of an empty headline, i.e with only stars
910 and maybe a TODO keyword, TAB will then switch the entry to become a child,
911 and then all possible ancestor states, before returning to the original state.
912 This makes data entry extremely fast: M-RET to create a new headline,
913 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
915 When the cursor is at the end of an empty plain list item, one TAB will
916 make it a subitem, two or more tabs will back up to make this an item
917 higher up in the item hierarchy."
918 :group 'org-cycle
919 :type 'boolean)
921 (defcustom org-cycle-emulate-tab t
922 "Where should `org-cycle' emulate TAB.
923 nil Never
924 white Only in completely white lines
925 whitestart Only at the beginning of lines, before the first non-white char
926 t Everywhere except in headlines
927 exc-hl-bol Everywhere except at the start of a headline
928 If TAB is used in a place where it does not emulate TAB, the current subtree
929 visibility is cycled."
930 :group 'org-cycle
931 :type '(choice (const :tag "Never" nil)
932 (const :tag "Only in completely white lines" white)
933 (const :tag "Before first char in a line" whitestart)
934 (const :tag "Everywhere except in headlines" t)
935 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
938 (defcustom org-cycle-separator-lines 2
939 "Number of empty lines needed to keep an empty line between collapsed trees.
940 If you leave an empty line between the end of a subtree and the following
941 headline, this empty line is hidden when the subtree is folded.
942 Org-mode will leave (exactly) one empty line visible if the number of
943 empty lines is equal or larger to the number given in this variable.
944 So the default 2 means at least 2 empty lines after the end of a subtree
945 are needed to produce free space between a collapsed subtree and the
946 following headline.
948 If the number is negative, and the number of empty lines is at least -N,
949 all empty lines are shown.
951 Special case: when 0, never leave empty lines in collapsed view."
952 :group 'org-cycle
953 :type 'integer)
954 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
956 (defcustom org-pre-cycle-hook nil
957 "Hook that is run before visibility cycling is happening.
958 The function(s) in this hook must accept a single argument which indicates
959 the new state that will be set right after running this hook. The
960 argument is a symbol. Before a global state change, it can have the values
961 `overview', `content', or `all'. Before a local state change, it can have
962 the values `folded', `children', or `subtree'."
963 :group 'org-cycle
964 :type 'hook)
966 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
967 org-cycle-hide-drawers
968 org-cycle-show-empty-lines
969 org-optimize-window-after-visibility-change)
970 "Hook that is run after `org-cycle' has changed the buffer visibility.
971 The function(s) in this hook must accept a single argument which indicates
972 the new state that was set by the most recent `org-cycle' command. The
973 argument is a symbol. After a global state change, it can have the values
974 `overview', `content', or `all'. After a local state change, it can have
975 the values `folded', `children', or `subtree'."
976 :group 'org-cycle
977 :type 'hook)
979 (defgroup org-edit-structure nil
980 "Options concerning structure editing in Org-mode."
981 :tag "Org Edit Structure"
982 :group 'org-structure)
984 (defcustom org-odd-levels-only nil
985 "Non-nil means skip even levels and only use odd levels for the outline.
986 This has the effect that two stars are being added/taken away in
987 promotion/demotion commands. It also influences how levels are
988 handled by the exporters.
989 Changing it requires restart of `font-lock-mode' to become effective
990 for fontification also in regions already fontified.
991 You may also set this on a per-file basis by adding one of the following
992 lines to the buffer:
994 #+STARTUP: odd
995 #+STARTUP: oddeven"
996 :group 'org-edit-structure
997 :group 'org-appearance
998 :type 'boolean)
1000 (defcustom org-adapt-indentation t
1001 "Non-nil means adapt indentation to outline node level.
1003 When this variable is set, Org assumes that you write outlines by
1004 indenting text in each node to align with the headline (after the stars).
1005 The following issues are influenced by this variable:
1007 - When this is set and the *entire* text in an entry is indented, the
1008 indentation is increased by one space in a demotion command, and
1009 decreased by one in a promotion command. If any line in the entry
1010 body starts with text at column 0, indentation is not changed at all.
1012 - Property drawers and planning information is inserted indented when
1013 this variable s set. When nil, they will not be indented.
1015 - TAB indents a line relative to context. The lines below a headline
1016 will be indented when this variable is set.
1018 Note that this is all about true indentation, by adding and removing
1019 space characters. See also `org-indent.el' which does level-dependent
1020 indentation in a virtual way, i.e. at display time in Emacs."
1021 :group 'org-edit-structure
1022 :type 'boolean)
1024 (defcustom org-special-ctrl-a/e nil
1025 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1027 When t, `C-a' will bring back the cursor to the beginning of the
1028 headline text, i.e. after the stars and after a possible TODO
1029 keyword. In an item, this will be the position after bullet and
1030 check-box, if any. When the cursor is already at that position,
1031 another `C-a' will bring it to the beginning of the line.
1033 `C-e' will jump to the end of the headline, ignoring the presence
1034 of tags in the headline. A second `C-e' will then jump to the
1035 true end of the line, after any tags. This also means that, when
1036 this variable is non-nil, `C-e' also will never jump beyond the
1037 end of the heading of a folded section, i.e. not after the
1038 ellipses.
1040 When set to the symbol `reversed', the first `C-a' or `C-e' works
1041 normally, going to the true line boundary first. Only a directly
1042 following, identical keypress will bring the cursor to the
1043 special positions.
1045 This may also be a cons cell where the behavior for `C-a' and
1046 `C-e' is set separately."
1047 :group 'org-edit-structure
1048 :type '(choice
1049 (const :tag "off" nil)
1050 (const :tag "on: after stars/bullet and before tags first" t)
1051 (const :tag "reversed: true line boundary first" reversed)
1052 (cons :tag "Set C-a and C-e separately"
1053 (choice :tag "Special C-a"
1054 (const :tag "off" nil)
1055 (const :tag "on: after stars/bullet first" t)
1056 (const :tag "reversed: before stars/bullet first" reversed))
1057 (choice :tag "Special C-e"
1058 (const :tag "off" nil)
1059 (const :tag "on: before tags first" t)
1060 (const :tag "reversed: after tags first" reversed)))))
1061 (if (fboundp 'defvaralias)
1062 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1064 (defcustom org-special-ctrl-k nil
1065 "Non-nil means `C-k' will behave specially in headlines.
1066 When nil, `C-k' will call the default `kill-line' command.
1067 When t, the following will happen while the cursor is in the headline:
1069 - When the cursor is at the beginning of a headline, kill the entire
1070 line and possible the folded subtree below the line.
1071 - When in the middle of the headline text, kill the headline up to the tags.
1072 - When after the headline text, kill the tags."
1073 :group 'org-edit-structure
1074 :type 'boolean)
1076 (defcustom org-ctrl-k-protect-subtree nil
1077 "Non-nil means, do not delete a hidden subtree with C-k.
1078 When set to the symbol `error', simply throw an error when C-k is
1079 used to kill (part-of) a headline that has hidden text behind it.
1080 Any other non-nil value will result in a query to the user, if it is
1081 OK to kill that hidden subtree. When nil, kill without remorse."
1082 :group 'org-edit-structure
1083 :version "24.1"
1084 :type '(choice
1085 (const :tag "Do not protect hidden subtrees" nil)
1086 (const :tag "Protect hidden subtrees with a security query" t)
1087 (const :tag "Never kill a hidden subtree with C-k" error)))
1089 (defcustom org-catch-invisible-edits nil
1090 "Check if in invisible region before inserting or deleting a character.
1091 Valid values are:
1093 nil Do not check, so just do invisible edits.
1094 error Throw an error and do nothing.
1095 show Make point visible, and do the requested edit.
1096 show-and-error Make point visible, then throw an error and abort the edit.
1097 smart Make point visible, and do insertion/deletion if it is
1098 adjacent to visible text and the change feels predictable.
1099 Never delete a previously invisible character or add in the
1100 middle or right after an invisible region. Basically, this
1101 allows insertion and backward-delete right before ellipses.
1102 FIXME: maybe in this case we should not even show?"
1103 :group 'org-edit-structure
1104 :version "24.1"
1105 :type '(choice
1106 (const :tag "Do not check" nil)
1107 (const :tag "Throw error when trying to edit" error)
1108 (const :tag "Unhide, but do not do the edit" show-and-error)
1109 (const :tag "Show invisible part and do the edit" show)
1110 (const :tag "Be smart and do the right thing" smart)))
1112 (defcustom org-yank-folded-subtrees t
1113 "Non-nil means when yanking subtrees, fold them.
1114 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1115 it starts with a heading and all other headings in it are either children
1116 or siblings, then fold all the subtrees. However, do this only if no
1117 text after the yank would be swallowed into a folded tree by this action."
1118 :group 'org-edit-structure
1119 :type 'boolean)
1121 (defcustom org-yank-adjusted-subtrees nil
1122 "Non-nil means when yanking subtrees, adjust the level.
1123 With this setting, `org-paste-subtree' is used to insert the subtree, see
1124 this function for details."
1125 :group 'org-edit-structure
1126 :type 'boolean)
1128 (defcustom org-M-RET-may-split-line '((default . t))
1129 "Non-nil means M-RET will split the line at the cursor position.
1130 When nil, it will go to the end of the line before making a
1131 new line.
1132 You may also set this option in a different way for different
1133 contexts. Valid contexts are:
1135 headline when creating a new headline
1136 item when creating a new item
1137 table in a table field
1138 default the value to be used for all contexts not explicitly
1139 customized"
1140 :group 'org-structure
1141 :group 'org-table
1142 :type '(choice
1143 (const :tag "Always" t)
1144 (const :tag "Never" nil)
1145 (repeat :greedy t :tag "Individual contexts"
1146 (cons
1147 (choice :tag "Context"
1148 (const headline)
1149 (const item)
1150 (const table)
1151 (const default))
1152 (boolean)))))
1155 (defcustom org-insert-heading-respect-content nil
1156 "Non-nil means insert new headings after the current subtree.
1157 When nil, the new heading is created directly after the current line.
1158 The commands \\[org-insert-heading-respect-content] and
1159 \\[org-insert-todo-heading-respect-content] turn this variable on
1160 for the duration of the command."
1161 :group 'org-structure
1162 :type 'boolean)
1164 (defcustom org-blank-before-new-entry '((heading . auto)
1165 (plain-list-item . auto))
1166 "Should `org-insert-heading' leave a blank line before new heading/item?
1167 The value is an alist, with `heading' and `plain-list-item' as CAR,
1168 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1169 which case Org will look at the surrounding headings/items and try to
1170 make an intelligent decision whether to insert a blank line or not.
1172 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1173 set, the setting here is ignored and no empty line is inserted, to avoid
1174 breaking the list structure."
1175 :group 'org-edit-structure
1176 :type '(list
1177 (cons (const heading)
1178 (choice (const :tag "Never" nil)
1179 (const :tag "Always" t)
1180 (const :tag "Auto" auto)))
1181 (cons (const plain-list-item)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))))
1186 (defcustom org-insert-heading-hook nil
1187 "Hook being run after inserting a new heading."
1188 :group 'org-edit-structure
1189 :type 'hook)
1191 (defcustom org-enable-fixed-width-editor t
1192 "Non-nil means lines starting with \":\" are treated as fixed-width.
1193 This currently only means they are never auto-wrapped.
1194 When nil, such lines will be treated like ordinary lines.
1195 See also the QUOTE keyword."
1196 :group 'org-edit-structure
1197 :type 'boolean)
1199 (defcustom org-goto-auto-isearch t
1200 "Non-nil means typing characters in `org-goto' starts incremental search."
1201 :group 'org-edit-structure
1202 :type 'boolean)
1204 (defgroup org-sparse-trees nil
1205 "Options concerning sparse trees in Org-mode."
1206 :tag "Org Sparse Trees"
1207 :group 'org-structure)
1209 (defcustom org-highlight-sparse-tree-matches t
1210 "Non-nil means highlight all matches that define a sparse tree.
1211 The highlights will automatically disappear the next time the buffer is
1212 changed by an edit command."
1213 :group 'org-sparse-trees
1214 :type 'boolean)
1216 (defcustom org-remove-highlights-with-change t
1217 "Non-nil means any change to the buffer will remove temporary highlights.
1218 Such highlights are created by `org-occur' and `org-clock-display'.
1219 When nil, `C-c C-c needs to be used to get rid of the highlights.
1220 The highlights created by `org-preview-latex-fragment' always need
1221 `C-c C-c' to be removed."
1222 :group 'org-sparse-trees
1223 :group 'org-time
1224 :type 'boolean)
1227 (defcustom org-occur-hook '(org-first-headline-recenter)
1228 "Hook that is run after `org-occur' has constructed a sparse tree.
1229 This can be used to recenter the window to show as much of the structure
1230 as possible."
1231 :group 'org-sparse-trees
1232 :type 'hook)
1234 (defgroup org-imenu-and-speedbar nil
1235 "Options concerning imenu and speedbar in Org-mode."
1236 :tag "Org Imenu and Speedbar"
1237 :group 'org-structure)
1239 (defcustom org-imenu-depth 2
1240 "The maximum level for Imenu access to Org-mode headlines.
1241 This also applied for speedbar access."
1242 :group 'org-imenu-and-speedbar
1243 :type 'integer)
1245 (defgroup org-table nil
1246 "Options concerning tables in Org-mode."
1247 :tag "Org Table"
1248 :group 'org)
1250 (defcustom org-enable-table-editor 'optimized
1251 "Non-nil means lines starting with \"|\" are handled by the table editor.
1252 When nil, such lines will be treated like ordinary lines.
1254 When equal to the symbol `optimized', the table editor will be optimized to
1255 do the following:
1256 - Automatic overwrite mode in front of whitespace in table fields.
1257 This makes the structure of the table stay in tact as long as the edited
1258 field does not exceed the column width.
1259 - Minimize the number of realigns. Normally, the table is aligned each time
1260 TAB or RET are pressed to move to another field. With optimization this
1261 happens only if changes to a field might have changed the column width.
1262 Optimization requires replacing the functions `self-insert-command',
1263 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1264 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1265 very good at guessing when a re-align will be necessary, but you can always
1266 force one with \\[org-ctrl-c-ctrl-c].
1268 If you would like to use the optimized version in Org-mode, but the
1269 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1271 This variable can be used to turn on and off the table editor during a session,
1272 but in order to toggle optimization, a restart is required.
1274 See also the variable `org-table-auto-blank-field'."
1275 :group 'org-table
1276 :type '(choice
1277 (const :tag "off" nil)
1278 (const :tag "on" t)
1279 (const :tag "on, optimized" optimized)))
1281 (defcustom org-self-insert-cluster-for-undo t
1282 "Non-nil means cluster self-insert commands for undo when possible.
1283 If this is set, then, like in the Emacs command loop, 20 consecutive
1284 characters will be undone together.
1285 This is configurable, because there is some impact on typing performance."
1286 :group 'org-table
1287 :type 'boolean)
1289 (defcustom org-table-tab-recognizes-table.el t
1290 "Non-nil means TAB will automatically notice a table.el table.
1291 When it sees such a table, it moves point into it and - if necessary -
1292 calls `table-recognize-table'."
1293 :group 'org-table-editing
1294 :type 'boolean)
1296 (defgroup org-link nil
1297 "Options concerning links in Org-mode."
1298 :tag "Org Link"
1299 :group 'org)
1301 (defvar org-link-abbrev-alist-local nil
1302 "Buffer-local version of `org-link-abbrev-alist', which see.
1303 The value of this is taken from the #+LINK lines.")
1304 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1306 (defcustom org-link-abbrev-alist nil
1307 "Alist of link abbreviations.
1308 The car of each element is a string, to be replaced at the start of a link.
1309 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1310 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1312 [[linkkey:tag][description]]
1314 The 'linkkey' must be a word word, starting with a letter, followed
1315 by letters, numbers, '-' or '_'.
1317 If REPLACE is a string, the tag will simply be appended to create the link.
1318 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1319 the placeholder \"%h\" will cause a url-encoded version of the tag to
1320 be inserted at that point (see the function `url-hexify-string').
1322 REPLACE may also be a function that will be called with the tag as the
1323 only argument to create the link, which should be returned as a string.
1325 See the manual for examples."
1326 :group 'org-link
1327 :type '(repeat
1328 (cons
1329 (string :tag "Protocol")
1330 (choice
1331 (string :tag "Format")
1332 (function)))))
1334 (defcustom org-descriptive-links t
1335 "Non-nil means Org will display descriptive links.
1336 E.g. [[http://orgmode.org][Org website]] will be displayed as
1337 \"Org Website\", hiding the link itself and just displaying its
1338 description. When set to `nil', Org will display the full links
1339 literally.
1341 You can interactively set the value of this variable by calling
1342 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1343 :group 'org-link
1344 :type 'boolean)
1346 (defcustom org-link-file-path-type 'adaptive
1347 "How the path name in file links should be stored.
1348 Valid values are:
1350 relative Relative to the current directory, i.e. the directory of the file
1351 into which the link is being inserted.
1352 absolute Absolute path, if possible with ~ for home directory.
1353 noabbrev Absolute path, no abbreviation of home directory.
1354 adaptive Use relative path for files in the current directory and sub-
1355 directories of it. For other files, use an absolute path."
1356 :group 'org-link
1357 :type '(choice
1358 (const relative)
1359 (const absolute)
1360 (const noabbrev)
1361 (const adaptive)))
1363 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1364 "Types of links that should be activated in Org-mode files.
1365 This is a list of symbols, each leading to the activation of a certain link
1366 type. In principle, it does not hurt to turn on most link types - there may
1367 be a small gain when turning off unused link types. The types are:
1369 bracket The recommended [[link][description]] or [[link]] links with hiding.
1370 angle Links in angular brackets that may contain whitespace like
1371 <bbdb:Carsten Dominik>.
1372 plain Plain links in normal text, no whitespace, like http://google.com.
1373 radio Text that is matched by a radio target, see manual for details.
1374 tag Tag settings in a headline (link to tag search).
1375 date Time stamps (link to calendar).
1376 footnote Footnote labels.
1378 Changing this variable requires a restart of Emacs to become effective."
1379 :group 'org-link
1380 :type '(set :greedy t
1381 (const :tag "Double bracket links" bracket)
1382 (const :tag "Angular bracket links" angle)
1383 (const :tag "Plain text links" plain)
1384 (const :tag "Radio target matches" radio)
1385 (const :tag "Tags" tag)
1386 (const :tag "Timestamps" date)
1387 (const :tag "Footnotes" footnote)))
1389 (defcustom org-make-link-description-function nil
1390 "Function to use to generate link descriptions from links.
1391 If nil the link location will be used. This function must take
1392 two parameters; the first is the link and the second the
1393 description `org-insert-link' has generated, and should return the
1394 description to use."
1395 :group 'org-link
1396 :type 'function)
1398 (defgroup org-link-store nil
1399 "Options concerning storing links in Org-mode."
1400 :tag "Org Store Link"
1401 :group 'org-link)
1403 (defcustom org-email-link-description-format "Email %c: %.30s"
1404 "Format of the description part of a link to an email or usenet message.
1405 The following %-escapes will be replaced by corresponding information:
1407 %F full \"From\" field
1408 %f name, taken from \"From\" field, address if no name
1409 %T full \"To\" field
1410 %t first name in \"To\" field, address if no name
1411 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1412 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1413 %s subject
1414 %d date
1415 %m message-id.
1417 You may use normal field width specification between the % and the letter.
1418 This is for example useful to limit the length of the subject.
1420 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1421 :group 'org-link-store
1422 :type 'string)
1424 (defcustom org-from-is-user-regexp
1425 (let (r1 r2)
1426 (when (and user-mail-address (not (string= user-mail-address "")))
1427 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1428 (when (and user-full-name (not (string= user-full-name "")))
1429 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1430 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1431 "Regexp matched against the \"From:\" header of an email or usenet message.
1432 It should match if the message is from the user him/herself."
1433 :group 'org-link-store
1434 :type 'regexp)
1436 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1437 "Non-nil means storing a link to an Org file will use entry IDs.
1439 Note that before this variable is even considered, org-id must be loaded,
1440 so please customize `org-modules' and turn it on.
1442 The variable can have the following values:
1444 t Create an ID if needed to make a link to the current entry.
1446 create-if-interactive
1447 If `org-store-link' is called directly (interactively, as a user
1448 command), do create an ID to support the link. But when doing the
1449 job for remember, only use the ID if it already exists. The
1450 purpose of this setting is to avoid proliferation of unwanted
1451 IDs, just because you happen to be in an Org file when you
1452 call `org-remember' that automatically and preemptively
1453 creates a link. If you do want to get an ID link in a remember
1454 template to an entry not having an ID, create it first by
1455 explicitly creating a link to it, using `C-c C-l' first.
1457 create-if-interactive-and-no-custom-id
1458 Like create-if-interactive, but do not create an ID if there is
1459 a CUSTOM_ID property defined in the entry. This is the default.
1461 use-existing
1462 Use existing ID, do not create one.
1464 nil Never use an ID to make a link, instead link using a text search for
1465 the headline text."
1466 :group 'org-link-store
1467 :type '(choice
1468 (const :tag "Create ID to make link" t)
1469 (const :tag "Create if storing link interactively"
1470 create-if-interactive)
1471 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1472 create-if-interactive-and-no-custom-id)
1473 (const :tag "Only use existing" use-existing)
1474 (const :tag "Do not use ID to create link" nil)))
1476 (defcustom org-context-in-file-links t
1477 "Non-nil means file links from `org-store-link' contain context.
1478 A search string will be added to the file name with :: as separator and
1479 used to find the context when the link is activated by the command
1480 `org-open-at-point'. When this option is t, the entire active region
1481 will be placed in the search string of the file link. If set to a
1482 positive integer, only the first n lines of context will be stored.
1484 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1485 negates this setting for the duration of the command."
1486 :group 'org-link-store
1487 :type '(choice boolean integer))
1489 (defcustom org-keep-stored-link-after-insertion nil
1490 "Non-nil means keep link in list for entire session.
1492 The command `org-store-link' adds a link pointing to the current
1493 location to an internal list. These links accumulate during a session.
1494 The command `org-insert-link' can be used to insert links into any
1495 Org-mode file (offering completion for all stored links). When this
1496 option is nil, every link which has been inserted once using \\[org-insert-link]
1497 will be removed from the list, to make completing the unused links
1498 more efficient."
1499 :group 'org-link-store
1500 :type 'boolean)
1502 (defgroup org-link-follow nil
1503 "Options concerning following links in Org-mode."
1504 :tag "Org Follow Link"
1505 :group 'org-link)
1507 (defcustom org-link-translation-function nil
1508 "Function to translate links with different syntax to Org syntax.
1509 This can be used to translate links created for example by the Planner
1510 or emacs-wiki packages to Org syntax.
1511 The function must accept two parameters, a TYPE containing the link
1512 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1513 which is everything after the link protocol. It should return a cons
1514 with possibly modified values of type and path.
1515 Org contains a function for this, so if you set this variable to
1516 `org-translate-link-from-planner', you should be able follow many
1517 links created by planner."
1518 :group 'org-link-follow
1519 :type 'function)
1521 (defcustom org-follow-link-hook nil
1522 "Hook that is run after a link has been followed."
1523 :group 'org-link-follow
1524 :type 'hook)
1526 (defcustom org-tab-follows-link nil
1527 "Non-nil means on links TAB will follow the link.
1528 Needs to be set before org.el is loaded.
1529 This really should not be used, it does not make sense, and the
1530 implementation is bad."
1531 :group 'org-link-follow
1532 :type 'boolean)
1534 (defcustom org-return-follows-link nil
1535 "Non-nil means on links RET will follow the link."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mouse-1-follows-link
1540 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1541 "Non-nil means mouse-1 on a link will follow the link.
1542 A longer mouse click will still set point. Does not work on XEmacs.
1543 Needs to be set before org.el is loaded."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-mark-ring-length 4
1548 "Number of different positions to be recorded in the ring.
1549 Changing this requires a restart of Emacs to work correctly."
1550 :group 'org-link-follow
1551 :type 'integer)
1553 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1554 "Non-nil means internal links in Org files must exactly match a headline.
1555 When nil, the link search tries to match a phrase with all words
1556 in the search text."
1557 :group 'org-link-follow
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Use fuzzy text search" nil)
1561 (const :tag "Match only exact headline" t)
1562 (const :tag "Match exact headline or query to create it"
1563 query-to-create)))
1565 (defcustom org-link-frame-setup
1566 '((vm . vm-visit-folder-other-frame)
1567 (vm-imap . vm-visit-imap-folder-other-frame)
1568 (gnus . org-gnus-no-new-news)
1569 (file . find-file-other-window)
1570 (wl . wl-other-frame))
1571 "Setup the frame configuration for following links.
1572 When following a link with Emacs, it may often be useful to display
1573 this link in another window or frame. This variable can be used to
1574 set this up for the different types of links.
1575 For VM, use any of
1576 `vm-visit-folder'
1577 `vm-visit-folder-other-window'
1578 `vm-visit-folder-other-frame'
1579 For Gnus, use any of
1580 `gnus'
1581 `gnus-other-frame'
1582 `org-gnus-no-new-news'
1583 For FILE, use any of
1584 `find-file'
1585 `find-file-other-window'
1586 `find-file-other-frame'
1587 For Wanderlust use any of
1588 `wl'
1589 `wl-other-frame'
1590 For the calendar, use the variable `calendar-setup'.
1591 For BBDB, it is currently only possible to display the matches in
1592 another window."
1593 :group 'org-link-follow
1594 :type '(list
1595 (cons (const vm)
1596 (choice
1597 (const vm-visit-folder)
1598 (const vm-visit-folder-other-window)
1599 (const vm-visit-folder-other-frame)))
1600 (cons (const gnus)
1601 (choice
1602 (const gnus)
1603 (const gnus-other-frame)
1604 (const org-gnus-no-new-news)))
1605 (cons (const file)
1606 (choice
1607 (const find-file)
1608 (const find-file-other-window)
1609 (const find-file-other-frame)))
1610 (cons (const wl)
1611 (choice
1612 (const wl)
1613 (const wl-other-frame)))))
1615 (defcustom org-display-internal-link-with-indirect-buffer nil
1616 "Non-nil means use indirect buffer to display infile links.
1617 Activating internal links (from one location in a file to another location
1618 in the same file) normally just jumps to the location. When the link is
1619 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1620 is displayed in
1621 another window. When this option is set, the other window actually displays
1622 an indirect buffer clone of the current buffer, to avoid any visibility
1623 changes to the current buffer."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-open-non-existing-files nil
1628 "Non-nil means `org-open-file' will open non-existing files.
1629 When nil, an error will be generated.
1630 This variable applies only to external applications because they
1631 might choke on non-existing files. If the link is to a file that
1632 will be opened in Emacs, the variable is ignored."
1633 :group 'org-link-follow
1634 :type 'boolean)
1636 (defcustom org-open-directory-means-index-dot-org nil
1637 "Non-nil means a link to a directory really means to index.org.
1638 When nil, following a directory link will run dired or open a finder/explorer
1639 window on that directory."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1644 "Function and arguments to call for following mailto links.
1645 This is a list with the first element being a Lisp function, and the
1646 remaining elements being arguments to the function. In string arguments,
1647 %a will be replaced by the address, and %s will be replaced by the subject
1648 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1652 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1653 (const :tag "message-mail" (message-mail "%a" "%s"))
1654 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1656 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing shell links.
1658 Shell links can be dangerous: just think about a link
1660 [[shell:rm -rf ~/*][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-shell-link-not-regexp ""
1677 "A regexp to skip confirmation for shell links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1683 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1684 Elisp links can be dangerous: just think about a link
1686 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1688 This link would show up in your Org-mode document as \"Google Search\",
1689 but really it would remove your entire home directory.
1690 Therefore we advise against setting this variable to nil.
1691 Just change it to `y-or-n-p' if you want to confirm with a
1692 single keystroke rather than having to type \"yes\"."
1693 :group 'org-link-follow
1694 :type '(choice
1695 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1696 (const :tag "with y-or-n (faster)" y-or-n-p)
1697 (const :tag "no confirmation (dangerous)" nil)))
1698 (put 'org-confirm-shell-link-function
1699 'safe-local-variable
1700 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1702 (defcustom org-confirm-elisp-link-not-regexp ""
1703 "A regexp to skip confirmation for Elisp links."
1704 :group 'org-link-follow
1705 :version "24.1"
1706 :type 'regexp)
1708 (defconst org-file-apps-defaults-gnu
1709 '((remote . emacs)
1710 (system . mailcap)
1711 (t . mailcap))
1712 "Default file applications on a UNIX or GNU/Linux system.
1713 See `org-file-apps'.")
1715 (defconst org-file-apps-defaults-macosx
1716 '((remote . emacs)
1717 (t . "open %s")
1718 (system . "open %s")
1719 ("ps.gz" . "gv %s")
1720 ("eps.gz" . "gv %s")
1721 ("dvi" . "xdvi %s")
1722 ("fig" . "xfig %s"))
1723 "Default file applications on a MacOS X system.
1724 The system \"open\" is known as a default, but we use X11 applications
1725 for some files for which the OS does not have a good default.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-windowsnt
1729 (list
1730 '(remote . emacs)
1731 (cons t
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file))
1736 (cons 'system
1737 (list (if (featurep 'xemacs)
1738 'mswindows-shell-execute
1739 'w32-shell-execute)
1740 "open" 'file)))
1741 "Default file applications on a Windows NT system.
1742 The system \"open\" is used for most files.
1743 See `org-file-apps'.")
1745 (defcustom org-file-apps
1747 (auto-mode . emacs)
1748 ("\\.mm\\'" . default)
1749 ("\\.x?html?\\'" . default)
1750 ("\\.pdf\\'" . default)
1752 "External applications for opening `file:path' items in a document.
1753 Org-mode uses system defaults for different file types, but
1754 you can use this variable to set the application for a given file
1755 extension. The entries in this list are cons cells where the car identifies
1756 files and the cdr the corresponding command. Possible values for the
1757 file identifier are
1758 \"string\" A string as a file identifier can be interpreted in different
1759 ways, depending on its contents:
1761 - Alphanumeric characters only:
1762 Match links with this file extension.
1763 Example: (\"pdf\" . \"evince %s\")
1764 to open PDFs with evince.
1766 - Regular expression: Match links where the
1767 filename matches the regexp. If you want to
1768 use groups here, use shy groups.
1770 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1771 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1772 to open *.html and *.xhtml with firefox.
1774 - Regular expression which contains (non-shy) groups:
1775 Match links where the whole link, including \"::\", and
1776 anything after that, matches the regexp.
1777 In a custom command string, %1, %2, etc. are replaced with
1778 the parts of the link that were matched by the groups.
1779 For backwards compatibility, if a command string is given
1780 that does not use any of the group matches, this case is
1781 handled identically to the second one (i.e. match against
1782 file name only).
1783 In a custom lisp form, you can access the group matches with
1784 (match-string n link).
1786 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1787 to open [[file:document.pdf::5]] with evince at page 5.
1789 `directory' Matches a directory
1790 `remote' Matches a remote file, accessible through tramp or efs.
1791 Remote files most likely should be visited through Emacs
1792 because external applications cannot handle such paths.
1793 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1794 so all files Emacs knows how to handle. Using this with
1795 command `emacs' will open most files in Emacs. Beware that this
1796 will also open html files inside Emacs, unless you add
1797 (\"html\" . default) to the list as well.
1798 t Default for files not matched by any of the other options.
1799 `system' The system command to open files, like `open' on Windows
1800 and Mac OS X, and mailcap under GNU/Linux. This is the command
1801 that will be selected if you call `C-c C-o' with a double
1802 \\[universal-argument] \\[universal-argument] prefix.
1804 Possible values for the command are:
1805 `emacs' The file will be visited by the current Emacs process.
1806 `default' Use the default application for this file type, which is the
1807 association for t in the list, most likely in the system-specific
1808 part.
1809 This can be used to overrule an unwanted setting in the
1810 system-specific variable.
1811 `system' Use the system command for opening files, like \"open\".
1812 This command is specified by the entry whose car is `system'.
1813 Most likely, the system-specific version of this variable
1814 does define this command, but you can overrule/replace it
1815 here.
1816 string A command to be executed by a shell; %s will be replaced
1817 by the path to the file.
1818 sexp A Lisp form which will be evaluated. The file path will
1819 be available in the Lisp variable `file'.
1820 For more examples, see the system specific constants
1821 `org-file-apps-defaults-macosx'
1822 `org-file-apps-defaults-windowsnt'
1823 `org-file-apps-defaults-gnu'."
1824 :group 'org-link-follow
1825 :type '(repeat
1826 (cons (choice :value ""
1827 (string :tag "Extension")
1828 (const :tag "System command to open files" system)
1829 (const :tag "Default for unrecognized files" t)
1830 (const :tag "Remote file" remote)
1831 (const :tag "Links to a directory" directory)
1832 (const :tag "Any files that have Emacs modes"
1833 auto-mode))
1834 (choice :value ""
1835 (const :tag "Visit with Emacs" emacs)
1836 (const :tag "Use default" default)
1837 (const :tag "Use the system command" system)
1838 (string :tag "Command")
1839 (sexp :tag "Lisp form")))))
1843 (defgroup org-refile nil
1844 "Options concerning refiling entries in Org-mode."
1845 :tag "Org Refile"
1846 :group 'org)
1848 (defcustom org-directory "~/org"
1849 "Directory with org files.
1850 This is just a default location to look for Org files. There is no need
1851 at all to put your files into this directory. It is only used in the
1852 following situations:
1854 1. When a remember template specifies a target file that is not an
1855 absolute path. The path will then be interpreted relative to
1856 `org-directory'
1857 2. When a remember note is filed away in an interactive way (when exiting the
1858 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1859 with `org-directory' as the default path."
1860 :group 'org-refile
1861 :group 'org-remember
1862 :type 'directory)
1864 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1865 "Default target for storing notes.
1866 Used as a fall back file for org-remember.el and org-capture.el, for
1867 templates that do not specify a target file."
1868 :group 'org-refile
1869 :group 'org-remember
1870 :type '(choice
1871 (const :tag "Default from remember-data-file" nil)
1872 file))
1874 (defcustom org-goto-interface 'outline
1875 "The default interface to be used for `org-goto'.
1876 Allowed values are:
1877 outline The interface shows an outline of the relevant file
1878 and the correct heading is found by moving through
1879 the outline or by searching with incremental search.
1880 outline-path-completion Headlines in the current buffer are offered via
1881 completion. This is the interface also used by
1882 the refile command."
1883 :group 'org-refile
1884 :type '(choice
1885 (const :tag "Outline" outline)
1886 (const :tag "Outline-path-completion" outline-path-completion)))
1888 (defcustom org-goto-max-level 5
1889 "Maximum target level when running `org-goto' with refile interface."
1890 :group 'org-refile
1891 :type 'integer)
1893 (defcustom org-reverse-note-order nil
1894 "Non-nil means store new notes at the beginning of a file or entry.
1895 When nil, new notes will be filed to the end of a file or entry.
1896 This can also be a list with cons cells of regular expressions that
1897 are matched against file names, and values."
1898 :group 'org-remember
1899 :group 'org-refile
1900 :type '(choice
1901 (const :tag "Reverse always" t)
1902 (const :tag "Reverse never" nil)
1903 (repeat :tag "By file name regexp"
1904 (cons regexp boolean))))
1906 (defcustom org-log-refile nil
1907 "Information to record when a task is refiled.
1909 Possible values are:
1911 nil Don't add anything
1912 time Add a time stamp to the task
1913 note Prompt for a note and add it with template `org-log-note-headings'
1915 This option can also be set with on a per-file-basis with
1917 #+STARTUP: nologrefile
1918 #+STARTUP: logrefile
1919 #+STARTUP: lognoterefile
1921 You can have local logging settings for a subtree by setting the LOGGING
1922 property to one or more of these keywords.
1924 When bulk-refiling from the agenda, the value `note' is forbidden and
1925 will temporarily be changed to `time'."
1926 :group 'org-refile
1927 :group 'org-progress
1928 :version "24.1"
1929 :type '(choice
1930 (const :tag "No logging" nil)
1931 (const :tag "Record timestamp" time)
1932 (const :tag "Record timestamp with note." note)))
1934 (defcustom org-refile-targets nil
1935 "Targets for refiling entries with \\[org-refile].
1936 This is a list of cons cells. Each cell contains:
1937 - a specification of the files to be considered, either a list of files,
1938 or a symbol whose function or variable value will be used to retrieve
1939 a file name or a list of file names. If you use `org-agenda-files' for
1940 that, all agenda files will be scanned for targets. Nil means consider
1941 headings in the current buffer.
1942 - A specification of how to find candidate refile targets. This may be
1943 any of:
1944 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1945 This tag has to be present in all target headlines, inheritance will
1946 not be considered.
1947 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1948 todo keyword.
1949 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1950 headlines that are refiling targets.
1951 - a cons cell (:level . N). Any headline of level N is considered a target.
1952 Note that, when `org-odd-levels-only' is set, level corresponds to
1953 order in hierarchy, not to the number of stars.
1954 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1955 Note that, when `org-odd-levels-only' is set, level corresponds to
1956 order in hierarchy, not to the number of stars.
1958 Each element of this list generates a set of possible targets.
1959 The union of these sets is presented (with completion) to
1960 the user by `org-refile'.
1962 You can set the variable `org-refile-target-verify-function' to a function
1963 to verify each headline found by the simple criteria above.
1965 When this variable is nil, all top-level headlines in the current buffer
1966 are used, equivalent to the value `((nil . (:level . 1))'."
1967 :group 'org-refile
1968 :type '(repeat
1969 (cons
1970 (choice :value org-agenda-files
1971 (const :tag "All agenda files" org-agenda-files)
1972 (const :tag "Current buffer" nil)
1973 (function) (variable) (file))
1974 (choice :tag "Identify target headline by"
1975 (cons :tag "Specific tag" (const :value :tag) (string))
1976 (cons :tag "TODO keyword" (const :value :todo) (string))
1977 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1978 (cons :tag "Level number" (const :value :level) (integer))
1979 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1981 (defcustom org-refile-target-verify-function nil
1982 "Function to verify if the headline at point should be a refile target.
1983 The function will be called without arguments, with point at the
1984 beginning of the headline. It should return t and leave point
1985 where it is if the headline is a valid target for refiling.
1987 If the target should not be selected, the function must return nil.
1988 In addition to this, it may move point to a place from where the search
1989 should be continued. For example, the function may decide that the entire
1990 subtree of the current entry should be excluded and move point to the end
1991 of the subtree."
1992 :group 'org-refile
1993 :type 'function)
1995 (defcustom org-refile-use-cache nil
1996 "Non-nil means cache refile targets to speed up the process.
1997 The cache for a particular file will be updated automatically when
1998 the buffer has been killed, or when any of the marker used for flagging
1999 refile targets no longer points at a live buffer.
2000 If you have added new entries to a buffer that might themselves be targets,
2001 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2002 find that easier, `C-u C-u C-u C-c C-w'."
2003 :group 'org-refile
2004 :version "24.1"
2005 :type 'boolean)
2007 (defcustom org-refile-use-outline-path nil
2008 "Non-nil means provide refile targets as paths.
2009 So a level 3 headline will be available as level1/level2/level3.
2011 When the value is `file', also include the file name (without directory)
2012 into the path. In this case, you can also stop the completion after
2013 the file name, to get entries inserted as top level in the file.
2015 When `full-file-path', include the full file path."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Not" nil)
2019 (const :tag "Yes" t)
2020 (const :tag "Start with file name" file)
2021 (const :tag "Start with full file path" full-file-path)))
2023 (defcustom org-outline-path-complete-in-steps t
2024 "Non-nil means complete the outline path in hierarchical steps.
2025 When Org-mode uses the refile interface to select an outline path
2026 \(see variable `org-refile-use-outline-path'), the completion of
2027 the path can be done is a single go, or if can be done in steps down
2028 the headline hierarchy. Going in steps is probably the best if you
2029 do not use a special completion package like `ido' or `icicles'.
2030 However, when using these packages, going in one step can be very
2031 fast, while still showing the whole path to the entry."
2032 :group 'org-refile
2033 :type 'boolean)
2035 (defcustom org-refile-allow-creating-parent-nodes nil
2036 "Non-nil means allow to create new nodes as refile targets.
2037 New nodes are then created by adding \"/new node name\" to the completion
2038 of an existing node. When the value of this variable is `confirm',
2039 new node creation must be confirmed by the user (recommended)
2040 When nil, the completion must match an existing entry.
2042 Note that, if the new heading is not seen by the criteria
2043 listed in `org-refile-targets', multiple instances of the same
2044 heading would be created by trying again to file under the new
2045 heading."
2046 :group 'org-refile
2047 :type '(choice
2048 (const :tag "Never" nil)
2049 (const :tag "Always" t)
2050 (const :tag "Prompt for confirmation" confirm)))
2052 (defcustom org-refile-active-region-within-subtree nil
2053 "Non-nil means also refile active region within a subtree.
2055 By default `org-refile' doesn't allow refiling regions if they
2056 don't contain a set of subtrees, but it might be convenient to
2057 do so sometimes: in that case, the first line of the region is
2058 converted to a headline before refiling."
2059 :group 'org-refile
2060 :version "24.1"
2061 :type 'boolean)
2063 (defgroup org-todo nil
2064 "Options concerning TODO items in Org-mode."
2065 :tag "Org TODO"
2066 :group 'org)
2068 (defgroup org-progress nil
2069 "Options concerning Progress logging in Org-mode."
2070 :tag "Org Progress"
2071 :group 'org-time)
2073 (defvar org-todo-interpretation-widgets
2074 '((:tag "Sequence (cycling hits every state)" sequence)
2075 (:tag "Type (cycling directly to DONE)" type))
2076 "The available interpretation symbols for customizing `org-todo-keywords'.
2077 Interested libraries should add to this list.")
2079 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2080 "List of TODO entry keyword sequences and their interpretation.
2081 \\<org-mode-map>This is a list of sequences.
2083 Each sequence starts with a symbol, either `sequence' or `type',
2084 indicating if the keywords should be interpreted as a sequence of
2085 action steps, or as different types of TODO items. The first
2086 keywords are states requiring action - these states will select a headline
2087 for inclusion into the global TODO list Org-mode produces. If one of
2088 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2089 signify that no further action is necessary. If \"|\" is not found,
2090 the last keyword is treated as the only DONE state of the sequence.
2092 The command \\[org-todo] cycles an entry through these states, and one
2093 additional state where no keyword is present. For details about this
2094 cycling, see the manual.
2096 TODO keywords and interpretation can also be set on a per-file basis with
2097 the special #+SEQ_TODO and #+TYP_TODO lines.
2099 Each keyword can optionally specify a character for fast state selection
2100 \(in combination with the variable `org-use-fast-todo-selection')
2101 and specifiers for state change logging, using the same syntax
2102 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2103 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2104 indicates to record a time stamp each time this state is selected.
2106 Each keyword may also specify if a timestamp or a note should be
2107 recorded when entering or leaving the state, by adding additional
2108 characters in the parenthesis after the keyword. This looks like this:
2109 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2110 record only the time of the state change. With X and Y being either
2111 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2112 Y when leaving the state if and only if the *target* state does not
2113 define X. You may omit any of the fast-selection key or X or /Y,
2114 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2116 For backward compatibility, this variable may also be just a list
2117 of keywords - in this case the interpretation (sequence or type) will be
2118 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2119 :group 'org-todo
2120 :group 'org-keywords
2121 :type '(choice
2122 (repeat :tag "Old syntax, just keywords"
2123 (string :tag "Keyword"))
2124 (repeat :tag "New syntax"
2125 (cons
2126 (choice
2127 :tag "Interpretation"
2128 ;;Quick and dirty way to see
2129 ;;`org-todo-interpretations'. This takes the
2130 ;;place of item arguments
2131 :convert-widget
2132 (lambda (widget)
2133 (widget-put widget
2134 :args (mapcar
2135 #'(lambda (x)
2136 (widget-convert
2137 (cons 'const x)))
2138 org-todo-interpretation-widgets))
2139 widget))
2140 (repeat
2141 (string :tag "Keyword"))))))
2143 (defvar org-todo-keywords-1 nil
2144 "All TODO and DONE keywords active in a buffer.")
2145 (make-variable-buffer-local 'org-todo-keywords-1)
2146 (defvar org-todo-keywords-for-agenda nil)
2147 (defvar org-done-keywords-for-agenda nil)
2148 (defvar org-drawers-for-agenda nil)
2149 (defvar org-todo-keyword-alist-for-agenda nil)
2150 (defvar org-tag-alist-for-agenda nil)
2151 (defvar org-agenda-contributing-files nil)
2152 (defvar org-not-done-keywords nil)
2153 (make-variable-buffer-local 'org-not-done-keywords)
2154 (defvar org-done-keywords nil)
2155 (make-variable-buffer-local 'org-done-keywords)
2156 (defvar org-todo-heads nil)
2157 (make-variable-buffer-local 'org-todo-heads)
2158 (defvar org-todo-sets nil)
2159 (make-variable-buffer-local 'org-todo-sets)
2160 (defvar org-todo-log-states nil)
2161 (make-variable-buffer-local 'org-todo-log-states)
2162 (defvar org-todo-kwd-alist nil)
2163 (make-variable-buffer-local 'org-todo-kwd-alist)
2164 (defvar org-todo-key-alist nil)
2165 (make-variable-buffer-local 'org-todo-key-alist)
2166 (defvar org-todo-key-trigger nil)
2167 (make-variable-buffer-local 'org-todo-key-trigger)
2169 (defcustom org-todo-interpretation 'sequence
2170 "Controls how TODO keywords are interpreted.
2171 This variable is in principle obsolete and is only used for
2172 backward compatibility, if the interpretation of todo keywords is
2173 not given already in `org-todo-keywords'. See that variable for
2174 more information."
2175 :group 'org-todo
2176 :group 'org-keywords
2177 :type '(choice (const sequence)
2178 (const type)))
2180 (defcustom org-use-fast-todo-selection t
2181 "Non-nil means use the fast todo selection scheme with C-c C-t.
2182 This variable describes if and under what circumstances the cycling
2183 mechanism for TODO keywords will be replaced by a single-key, direct
2184 selection scheme.
2186 When nil, fast selection is never used.
2188 When the symbol `prefix', it will be used when `org-todo' is called with
2189 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2190 in an agenda buffer.
2192 When t, fast selection is used by default. In this case, the prefix
2193 argument forces cycling instead.
2195 In all cases, the special interface is only used if access keys have actually
2196 been assigned by the user, i.e. if keywords in the configuration are followed
2197 by a letter in parenthesis, like TODO(t)."
2198 :group 'org-todo
2199 :type '(choice
2200 (const :tag "Never" nil)
2201 (const :tag "By default" t)
2202 (const :tag "Only with C-u C-c C-t" prefix)))
2204 (defcustom org-provide-todo-statistics t
2205 "Non-nil means update todo statistics after insert and toggle.
2206 ALL-HEADLINES means update todo statistics by including headlines
2207 with no TODO keyword as well, counting them as not done.
2208 A list of TODO keywords means the same, but skip keywords that are
2209 not in this list.
2211 When this is set, todo statistics is updated in the parent of the
2212 current entry each time a todo state is changed."
2213 :group 'org-todo
2214 :type '(choice
2215 (const :tag "Yes, only for TODO entries" t)
2216 (const :tag "Yes, including all entries" 'all-headlines)
2217 (repeat :tag "Yes, for TODOs in this list"
2218 (string :tag "TODO keyword"))
2219 (other :tag "No TODO statistics" nil)))
2221 (defcustom org-hierarchical-todo-statistics t
2222 "Non-nil means TODO statistics covers just direct children.
2223 When nil, all entries in the subtree are considered.
2224 This has only an effect if `org-provide-todo-statistics' is set.
2225 To set this to nil for only a single subtree, use a COOKIE_DATA
2226 property and include the word \"recursive\" into the value."
2227 :group 'org-todo
2228 :type 'boolean)
2230 (defcustom org-after-todo-state-change-hook nil
2231 "Hook which is run after the state of a TODO item was changed.
2232 The new state (a string with a TODO keyword, or nil) is available in the
2233 Lisp variable `org-state'."
2234 :group 'org-todo
2235 :type 'hook)
2237 (defvar org-blocker-hook nil
2238 "Hook for functions that are allowed to block a state change.
2240 Each function gets as its single argument a property list, see
2241 `org-trigger-hook' for more information about this list.
2243 If any of the functions in this hook returns nil, the state change
2244 is blocked.")
2246 (defvar org-trigger-hook nil
2247 "Hook for functions that are triggered by a state change.
2249 Each function gets as its single argument a property list with at least
2250 the following elements:
2252 (:type type-of-change :position pos-at-entry-start
2253 :from old-state :to new-state)
2255 Depending on the type, more properties may be present.
2257 This mechanism is currently implemented for:
2259 TODO state changes
2260 ------------------
2261 :type todo-state-change
2262 :from previous state (keyword as a string), or nil, or a symbol
2263 'todo' or 'done', to indicate the general type of state.
2264 :to new state, like in :from")
2266 (defcustom org-enforce-todo-dependencies nil
2267 "Non-nil means undone TODO entries will block switching the parent to DONE.
2268 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2269 be blocked if any prior sibling is not yet done.
2270 Finally, if the parent is blocked because of ordered siblings of its own,
2271 the child will also be blocked."
2272 :set (lambda (var val)
2273 (set var val)
2274 (if val
2275 (add-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)
2277 (remove-hook 'org-blocker-hook
2278 'org-block-todo-from-children-or-siblings-or-parent)))
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-enforce-todo-checkbox-dependencies nil
2283 "Non-nil means unchecked boxes will block switching the parent to DONE.
2284 When this is nil, checkboxes have no influence on switching TODO states.
2285 When non-nil, you first need to check off all check boxes before the TODO
2286 entry can be switched to DONE.
2287 This variable needs to be set before org.el is loaded, and you need to
2288 restart Emacs after a change to make the change effective. The only way
2289 to change is while Emacs is running is through the customize interface."
2290 :set (lambda (var val)
2291 (set var val)
2292 (if val
2293 (add-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)
2295 (remove-hook 'org-blocker-hook
2296 'org-block-todo-from-checkboxes)))
2297 :group 'org-todo
2298 :type 'boolean)
2300 (defcustom org-treat-insert-todo-heading-as-state-change nil
2301 "Non-nil means inserting a TODO heading is treated as state change.
2302 So when the command \\[org-insert-todo-heading] is used, state change
2303 logging will apply if appropriate. When nil, the new TODO item will
2304 be inserted directly, and no logging will take place."
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2309 "Non-nil means switching TODO states with S-cursor counts as state change.
2310 This is the default behavior. However, setting this to nil allows a
2311 convenient way to select a TODO state and bypass any logging associated
2312 with that."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-todo-state-tags-triggers nil
2317 "Tag changes that should be triggered by TODO state changes.
2318 This is a list. Each entry is
2320 (state-change (tag . flag) .......)
2322 State-change can be a string with a state, and empty string to indicate the
2323 state that has no TODO keyword, or it can be one of the symbols `todo'
2324 or `done', meaning any not-done or done state, respectively."
2325 :group 'org-todo
2326 :group 'org-tags
2327 :type '(repeat
2328 (cons (choice :tag "When changing to"
2329 (const :tag "Not-done state" todo)
2330 (const :tag "Done state" done)
2331 (string :tag "State"))
2332 (repeat
2333 (cons :tag "Tag action"
2334 (string :tag "Tag")
2335 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2337 (defcustom org-log-done nil
2338 "Information to record when a task moves to the DONE state.
2340 Possible values are:
2342 nil Don't add anything, just change the keyword
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologdone
2349 #+STARTUP: logdone
2350 #+STARTUP: lognotedone
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(choice
2357 (const :tag "No logging" nil)
2358 (const :tag "Record CLOSED timestamp" time)
2359 (const :tag "Record CLOSED timestamp with note." note)))
2361 ;; Normalize old uses of org-log-done.
2362 (cond
2363 ((eq org-log-done t) (setq org-log-done 'time))
2364 ((and (listp org-log-done) (memq 'done org-log-done))
2365 (setq org-log-done 'note)))
2367 (defcustom org-log-reschedule nil
2368 "Information to record when the scheduling date of a tasks is modified.
2370 Possible values are:
2372 nil Don't add anything, just change the date
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologreschedule
2379 #+STARTUP: logreschedule
2380 #+STARTUP: lognotereschedule"
2381 :group 'org-todo
2382 :group 'org-progress
2383 :type '(choice
2384 (const :tag "No logging" nil)
2385 (const :tag "Record timestamp" time)
2386 (const :tag "Record timestamp with note." note)))
2388 (defcustom org-log-redeadline nil
2389 "Information to record when the deadline date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologredeadline
2400 #+STARTUP: logredeadline
2401 #+STARTUP: lognoteredeadline
2403 You can have local logging settings for a subtree by setting the LOGGING
2404 property to one or more of these keywords."
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-log-note-clock-out nil
2413 "Non-nil means record a note when clocking out of an item.
2414 This can also be configured on a per-file basis by adding one of
2415 the following lines anywhere in the buffer:
2417 #+STARTUP: lognoteclock-out
2418 #+STARTUP: nolognoteclock-out"
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-done-with-time t
2424 "Non-nil means the CLOSED time stamp will contain date and time.
2425 When nil, only the date will be recorded."
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-note-headings
2430 '((done . "CLOSING NOTE %t")
2431 (state . "State %-12s from %-12S %t")
2432 (note . "Note taken on %t")
2433 (reschedule . "Rescheduled from %S on %t")
2434 (delschedule . "Not scheduled, was %S on %t")
2435 (redeadline . "New deadline from %S on %t")
2436 (deldeadline . "Removed deadline, was %S on %t")
2437 (refile . "Refiled on %t")
2438 (clock-out . ""))
2439 "Headings for notes added to entries.
2440 The value is an alist, with the car being a symbol indicating the note
2441 context, and the cdr is the heading to be used. The heading may also be the
2442 empty string.
2443 %t in the heading will be replaced by a time stamp.
2444 %T will be an active time stamp instead the default inactive one
2445 %d will be replaced by a short-format time stamp.
2446 %D will be replaced by an active short-format time stamp.
2447 %s will be replaced by the new TODO state, in double quotes.
2448 %S will be replaced by the old TODO state, in double quotes.
2449 %u will be replaced by the user name.
2450 %U will be replaced by the full user name.
2452 In fact, it is not a good idea to change the `state' entry, because
2453 agenda log mode depends on the format of these entries."
2454 :group 'org-todo
2455 :group 'org-progress
2456 :type '(list :greedy t
2457 (cons (const :tag "Heading when closing an item" done) string)
2458 (cons (const :tag
2459 "Heading when changing todo state (todo sequence only)"
2460 state) string)
2461 (cons (const :tag "Heading when just taking a note" note) string)
2462 (cons (const :tag "Heading when clocking out" clock-out) string)
2463 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2464 (cons (const :tag "Heading when rescheduling" reschedule) string)
2465 (cons (const :tag "Heading when changing deadline" redeadline) string)
2466 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2467 (cons (const :tag "Heading when refiling" refile) string)))
2469 (unless (assq 'note org-log-note-headings)
2470 (push '(note . "%t") org-log-note-headings))
2472 (defcustom org-log-into-drawer nil
2473 "Non-nil means insert state change notes and time stamps into a drawer.
2474 When nil, state changes notes will be inserted after the headline and
2475 any scheduling and clock lines, but not inside a drawer.
2477 The value of this variable should be the name of the drawer to use.
2478 LOGBOOK is proposed as the default drawer for this purpose, you can
2479 also set this to a string to define the drawer of your choice.
2481 A value of t is also allowed, representing \"LOGBOOK\".
2483 If this variable is set, `org-log-state-notes-insert-after-drawers'
2484 will be ignored.
2486 You can set the property LOG_INTO_DRAWER to overrule this setting for
2487 a subtree."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "Not into a drawer" nil)
2492 (const :tag "LOGBOOK" t)
2493 (string :tag "Other")))
2495 (if (fboundp 'defvaralias)
2496 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2498 (defun org-log-into-drawer ()
2499 "Return the value of `org-log-into-drawer', but let properties overrule.
2500 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2501 used instead of the default value."
2502 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2503 (cond
2504 ((or (not p) (equal p "nil")) org-log-into-drawer)
2505 ((equal p "t") "LOGBOOK")
2506 (t p))))
2508 (defcustom org-log-state-notes-insert-after-drawers nil
2509 "Non-nil means insert state change notes after any drawers in entry.
2510 Only the drawers that *immediately* follow the headline and the
2511 deadline/scheduled line are skipped.
2512 When nil, insert notes right after the heading and perhaps the line
2513 with deadline/scheduling if present.
2515 This variable will have no effect if `org-log-into-drawer' is
2516 set."
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type 'boolean)
2521 (defcustom org-log-states-order-reversed t
2522 "Non-nil means the latest state note will be directly after heading.
2523 When nil, the state change notes will be ordered according to time."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type 'boolean)
2528 (defcustom org-todo-repeat-to-state nil
2529 "The TODO state to which a repeater should return the repeating task.
2530 By default this is the first task in a TODO sequence, or the previous state
2531 in a TODO_TYP set. But you can specify another task here.
2532 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2533 :group 'org-todo
2534 :version "24.1"
2535 :type '(choice (const :tag "Head of sequence" nil)
2536 (string :tag "Specific state")))
2538 (defcustom org-log-repeat 'time
2539 "Non-nil means record moving through the DONE state when triggering repeat.
2540 An auto-repeating task is immediately switched back to TODO when
2541 marked DONE. If you are not logging state changes (by adding \"@\"
2542 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2543 record a closing note, there will be no record of the task moving
2544 through DONE. This variable forces taking a note anyway.
2546 nil Don't force a record
2547 time Record a time stamp
2548 note Record a note
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: logrepeat
2553 #+STARTUP: lognoterepeat
2554 #+STARTUP: nologrepeat
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "Don't force a record" nil)
2562 (const :tag "Force recording the DONE state" time)
2563 (const :tag "Force recording a note with the DONE state" note)))
2566 (defgroup org-priorities nil
2567 "Priorities in Org-mode."
2568 :tag "Org Priorities"
2569 :group 'org-todo)
2571 (defcustom org-enable-priority-commands t
2572 "Non-nil means priority commands are active.
2573 When nil, these commands will be disabled, so that you never accidentally
2574 set a priority."
2575 :group 'org-priorities
2576 :type 'boolean)
2578 (defcustom org-highest-priority ?A
2579 "The highest priority of TODO items. A character like ?A, ?B etc.
2580 Must have a smaller ASCII number than `org-lowest-priority'."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-lowest-priority ?C
2585 "The lowest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a larger ASCII number than `org-highest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-default-priority ?B
2591 "The default priority of TODO items.
2592 This is the priority an item gets if no explicit priority is given.
2593 When starting to cycle on an empty priority the first step in the cycle
2594 depends on `org-priority-start-cycle-with-default'. The resulting first
2595 step priority must not exceed the range from `org-highest-priority' to
2596 `org-lowest-priority' which means that `org-default-priority' has to be
2597 in this range exclusive or inclusive the range boundaries. Else the
2598 first step refuses to set the default and the second will fall back
2599 to (depending on the command used) the highest or lowest priority."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-priority-start-cycle-with-default t
2604 "Non-nil means start with default priority when starting to cycle.
2605 When this is nil, the first step in the cycle will be (depending on the
2606 command used) one higher or lower than the default priority.
2607 See also `org-default-priority'."
2608 :group 'org-priorities
2609 :type 'boolean)
2611 (defcustom org-get-priority-function nil
2612 "Function to extract the priority from a string.
2613 The string is normally the headline. If this is nil Org computes the
2614 priority from the priority cookie like [#A] in the headline. It returns
2615 an integer, increasing by 1000 for each priority level.
2616 The user can set a different function here, which should take a string
2617 as an argument and return the numeric priority."
2618 :group 'org-priorities
2619 :version "24.1"
2620 :type 'function)
2622 (defgroup org-time nil
2623 "Options concerning time stamps and deadlines in Org-mode."
2624 :tag "Org Time"
2625 :group 'org)
2627 (defcustom org-insert-labeled-timestamps-at-point nil
2628 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2629 When nil, these labeled time stamps are forces into the second line of an
2630 entry, just after the headline. When scheduling from the global TODO list,
2631 the time stamp will always be forced into the second line."
2632 :group 'org-time
2633 :type 'boolean)
2635 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2636 "Formats for `format-time-string' which are used for time stamps.
2637 It is not recommended to change this constant.")
2639 (defcustom org-time-stamp-rounding-minutes '(0 5)
2640 "Number of minutes to round time stamps to.
2641 These are two values, the first applies when first creating a time stamp.
2642 The second applies when changing it with the commands `S-up' and `S-down'.
2643 When changing the time stamp, this means that it will change in steps
2644 of N minutes, as given by the second value.
2646 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2647 numbers should be factors of 60, so for example 5, 10, 15.
2649 When this is larger than 1, you can still force an exact time stamp by using
2650 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2651 and by using a prefix arg to `S-up/down' to specify the exact number
2652 of minutes to shift."
2653 :group 'org-time
2654 :get #'(lambda (var) ; Make sure both elements are there
2655 (if (integerp (default-value var))
2656 (list (default-value var) 5)
2657 (default-value var)))
2658 :type '(list
2659 (integer :tag "when inserting times")
2660 (integer :tag "when modifying times")))
2662 ;; Normalize old customizations of this variable.
2663 (when (integerp org-time-stamp-rounding-minutes)
2664 (setq org-time-stamp-rounding-minutes
2665 (list org-time-stamp-rounding-minutes
2666 org-time-stamp-rounding-minutes)))
2668 (defcustom org-display-custom-times nil
2669 "Non-nil means overlay custom formats over all time stamps.
2670 The formats are defined through the variable `org-time-stamp-custom-formats'.
2671 To turn this on on a per-file basis, insert anywhere in the file:
2672 #+STARTUP: customtime"
2673 :group 'org-time
2674 :set 'set-default
2675 :type 'sexp)
2676 (make-variable-buffer-local 'org-display-custom-times)
2678 (defcustom org-time-stamp-custom-formats
2679 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2680 "Custom formats for time stamps. See `format-time-string' for the syntax.
2681 These are overlaid over the default ISO format if the variable
2682 `org-display-custom-times' is set. Time like %H:%M should be at the
2683 end of the second format. The custom formats are also honored by export
2684 commands, if custom time display is turned on at the time of export."
2685 :group 'org-time
2686 :type 'sexp)
2688 (defun org-time-stamp-format (&optional long inactive)
2689 "Get the right format for a time string."
2690 (let ((f (if long (cdr org-time-stamp-formats)
2691 (car org-time-stamp-formats))))
2692 (if inactive
2693 (concat "[" (substring f 1 -1) "]")
2694 f)))
2696 (defcustom org-time-clocksum-format "%d:%02d"
2697 "The format string used when creating CLOCKSUM lines.
2698 This is also used when org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-time-clocksum-use-fractional nil
2703 "If non-nil, \\[org-clock-display] uses fractional times.
2704 org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'boolean)
2708 (defcustom org-time-clocksum-fractional-format "%.2f"
2709 "The format string used when creating CLOCKSUM lines, or when
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-deadline-warning-days 14
2715 "No. of days before expiration during which a deadline becomes active.
2716 This variable governs the display in sparse trees and in the agenda.
2717 When 0 or negative, it means use this number (the absolute value of it)
2718 even if a deadline has a different individual lead time specified.
2720 Custom commands can set this variable in the options section."
2721 :group 'org-time
2722 :group 'org-agenda-daily/weekly
2723 :type 'integer)
2725 (defcustom org-read-date-prefer-future t
2726 "Non-nil means assume future for incomplete date input from user.
2727 This affects the following situations:
2728 1. The user gives a month but not a year.
2729 For example, if it is April and you enter \"feb 2\", this will be read
2730 as Feb 2, *next* year. \"May 5\", however, will be this year.
2731 2. The user gives a day, but no month.
2732 For example, if today is the 15th, and you enter \"3\", Org-mode will
2733 read this as the third of *next* month. However, if you enter \"17\",
2734 it will be considered as *this* month.
2736 If you set this variable to the symbol `time', then also the following
2737 will work:
2739 3. If the user gives a time, but no day. If the time is before now,
2740 to will be interpreted as tomorrow.
2742 Currently none of this works for ISO week specifications.
2744 When this option is nil, the current day, month and year will always be
2745 used as defaults.
2747 See also `org-agenda-jump-prefer-future'."
2748 :group 'org-time
2749 :type '(choice
2750 (const :tag "Never" nil)
2751 (const :tag "Check month and day" t)
2752 (const :tag "Check month, day, and time" time)))
2754 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2755 "Should the agenda jump command prefer the future for incomplete dates?
2756 The default is to do the same as configured in `org-read-date-prefer-future'.
2757 But you can also set a deviating value here.
2758 This may t or nil, or the symbol `org-read-date-prefer-future'."
2759 :group 'org-agenda
2760 :group 'org-time
2761 :version "24.1"
2762 :type '(choice
2763 (const :tag "Use org-read-date-prefer-future"
2764 org-read-date-prefer-future)
2765 (const :tag "Never" nil)
2766 (const :tag "Always" t)))
2768 (defcustom org-read-date-force-compatible-dates t
2769 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2771 Depending on the system Emacs is running on, certain dates cannot
2772 be represented with the type used internally to represent time.
2773 Dates between 1970-1-1 and 2038-1-1 can always be represented
2774 correctly. Some systems allow for earlier dates, some for later,
2775 some for both. One way to find out it to insert any date into an
2776 Org buffer, putting the cursor on the year and hitting S-up and
2777 S-down to test the range.
2779 When this variable is set to t, the date/time prompt will not let
2780 you specify dates outside the 1970-2037 range, so it is certain that
2781 these dates will work in whatever version of Emacs you are
2782 running, and also that you can move a file from one Emacs implementation
2783 to another. WHenever Org is forcing the year for you, it will display
2784 a message and beep.
2786 When this variable is nil, Org will check if the date is
2787 representable in the specific Emacs implementation you are using.
2788 If not, it will force a year, usually the current year, and beep
2789 to remind you. Currently this setting is not recommended because
2790 the likelihood that you will open your Org files in an Emacs that
2791 has limited date range is not negligible.
2793 A workaround for this problem is to use diary sexp dates for time
2794 stamps outside of this range."
2795 :group 'org-time
2796 :version "24.1"
2797 :type 'boolean)
2799 (defcustom org-read-date-display-live t
2800 "Non-nil means display current interpretation of date prompt live.
2801 This display will be in an overlay, in the minibuffer."
2802 :group 'org-time
2803 :type 'boolean)
2805 (defcustom org-read-date-popup-calendar t
2806 "Non-nil means pop up a calendar when prompting for a date.
2807 In the calendar, the date can be selected with mouse-1. However, the
2808 minibuffer will also be active, and you can simply enter the date as well.
2809 When nil, only the minibuffer will be available."
2810 :group 'org-time
2811 :type 'boolean)
2812 (if (fboundp 'defvaralias)
2813 (defvaralias 'org-popup-calendar-for-date-prompt
2814 'org-read-date-popup-calendar))
2816 (defcustom org-read-date-minibuffer-setup-hook nil
2817 "Hook to be used to set up keys for the date/time interface.
2818 Add key definitions to `minibuffer-local-map', which will be a temporary
2819 copy."
2820 :group 'org-time
2821 :type 'hook)
2823 (defcustom org-extend-today-until 0
2824 "The hour when your day really ends. Must be an integer.
2825 This has influence for the following applications:
2826 - When switching the agenda to \"today\". It it is still earlier than
2827 the time given here, the day recognized as TODAY is actually yesterday.
2828 - When a date is read from the user and it is still before the time given
2829 here, the current date and time will be assumed to be yesterday, 23:59.
2830 Also, timestamps inserted in remember templates follow this rule.
2832 IMPORTANT: This is a feature whose implementation is and likely will
2833 remain incomplete. Really, it is only here because past midnight seems to
2834 be the favorite working time of John Wiegley :-)"
2835 :group 'org-time
2836 :type 'integer)
2838 (defcustom org-use-effective-time nil
2839 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2840 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2841 \"effective time\" of any timestamps between midnight and 8am will be
2842 23:59 of the previous day."
2843 :group 'org-time
2844 :version "24.1"
2845 :type 'boolean)
2847 (defcustom org-edit-timestamp-down-means-later nil
2848 "Non-nil means S-down will increase the time in a time stamp.
2849 When nil, S-up will increase."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defcustom org-calendar-follow-timestamp-change t
2854 "Non-nil means make the calendar window follow timestamp changes.
2855 When a timestamp is modified and the calendar window is visible, it will be
2856 moved to the new date."
2857 :group 'org-time
2858 :type 'boolean)
2860 (defgroup org-tags nil
2861 "Options concerning tags in Org-mode."
2862 :tag "Org Tags"
2863 :group 'org)
2865 (defcustom org-tag-alist nil
2866 "List of tags allowed in Org-mode files.
2867 When this list is nil, Org-mode will base TAG input on what is already in the
2868 buffer.
2869 The value of this variable is an alist, the car of each entry must be a
2870 keyword as a string, the cdr may be a character that is used to select
2871 that tag through the fast-tag-selection interface.
2872 See the manual for details."
2873 :group 'org-tags
2874 :type '(repeat
2875 (choice
2876 (cons (string :tag "Tag name")
2877 (character :tag "Access char"))
2878 (list :tag "Start radio group"
2879 (const :startgroup)
2880 (option (string :tag "Group description")))
2881 (list :tag "End radio group"
2882 (const :endgroup)
2883 (option (string :tag "Group description")))
2884 (const :tag "New line" (:newline)))))
2886 (defcustom org-tag-persistent-alist nil
2887 "List of tags that will always appear in all Org-mode files.
2888 This is in addition to any in buffer settings or customizations
2889 of `org-tag-alist'.
2890 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2891 The value of this variable is an alist, the car of each entry must be a
2892 keyword as a string, the cdr may be a character that is used to select
2893 that tag through the fast-tag-selection interface.
2894 See the manual for details.
2895 To disable these tags on a per-file basis, insert anywhere in the file:
2896 #+STARTUP: noptag"
2897 :group 'org-tags
2898 :type '(repeat
2899 (choice
2900 (cons (string :tag "Tag name")
2901 (character :tag "Access char"))
2902 (const :tag "Start radio group" (:startgroup))
2903 (const :tag "End radio group" (:endgroup))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2907 "If non-nil, always offer completion for all tags of all agenda files.
2908 Instead of customizing this variable directly, you might want to
2909 set it locally for capture buffers, because there no list of
2910 tags in that file can be created dynamically (there are none).
2912 (add-hook 'org-capture-mode-hook
2913 (lambda ()
2914 (set (make-local-variable
2915 'org-complete-tags-always-offer-all-agenda-tags)
2916 t)))"
2917 :group 'org-tags
2918 :version "24.1"
2919 :type 'boolean)
2921 (defvar org-file-tags nil
2922 "List of tags that can be inherited by all entries in the file.
2923 The tags will be inherited if the variable `org-use-tag-inheritance'
2924 says they should be.
2925 This variable is populated from #+FILETAGS lines.")
2927 (defcustom org-use-fast-tag-selection 'auto
2928 "Non-nil means use fast tag selection scheme.
2929 This is a special interface to select and deselect tags with single keys.
2930 When nil, fast selection is never used.
2931 When the symbol `auto', fast selection is used if and only if selection
2932 characters for tags have been configured, either through the variable
2933 `org-tag-alist' or through a #+TAGS line in the buffer.
2934 When t, fast selection is always used and selection keys are assigned
2935 automatically if necessary."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "Always" t)
2939 (const :tag "Never" nil)
2940 (const :tag "When selection characters are configured" 'auto)))
2942 (defcustom org-fast-tag-selection-single-key nil
2943 "Non-nil means fast tag selection exits after first change.
2944 When nil, you have to press RET to exit it.
2945 During fast tag selection, you can toggle this flag with `C-c'.
2946 This variable can also have the value `expert'. In this case, the window
2947 displaying the tags menu is not even shown, until you press C-c again."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "No" nil)
2951 (const :tag "Yes" t)
2952 (const :tag "Expert" expert)))
2954 (defvar org-fast-tag-selection-include-todo nil
2955 "Non-nil means fast tags selection interface will also offer TODO states.
2956 This is an undocumented feature, you should not rely on it.")
2958 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2959 "The column to which tags should be indented in a headline.
2960 If this number is positive, it specifies the column. If it is negative,
2961 it means that the tags should be flushright to that column. For example,
2962 -80 works well for a normal 80 character screen.
2963 When 0, place tags directly after headline text, with only one space in
2964 between."
2965 :group 'org-tags
2966 :type 'integer)
2968 (defcustom org-auto-align-tags t
2969 "Non-nil keeps tags aligned when modifying headlines.
2970 Some operations (i.e. demoting) change the length of a headline and
2971 therefore shift the tags around. With this option turned on, after
2972 each such operation the tags are again aligned to `org-tags-column'."
2973 :group 'org-tags
2974 :type 'boolean)
2976 (defcustom org-use-tag-inheritance t
2977 "Non-nil means tags in levels apply also for sublevels.
2978 When nil, only the tags directly given in a specific line apply there.
2979 This may also be a list of tags that should be inherited, or a regexp that
2980 matches tags that should be inherited. Additional control is possible
2981 with the variable `org-tags-exclude-from-inheritance' which gives an
2982 explicit list of tags to be excluded from inheritance., even if the value of
2983 `org-use-tag-inheritance' would select it for inheritance.
2985 If this option is t, a match early-on in a tree can lead to a large
2986 number of matches in the subtree when constructing the agenda or creating
2987 a sparse tree. If you only want to see the first match in a tree during
2988 a search, check out the variable `org-tags-match-list-sublevels'."
2989 :group 'org-tags
2990 :type '(choice
2991 (const :tag "Not" nil)
2992 (const :tag "Always" t)
2993 (repeat :tag "Specific tags" (string :tag "Tag"))
2994 (regexp :tag "Tags matched by regexp")))
2996 (defcustom org-tags-exclude-from-inheritance nil
2997 "List of tags that should never be inherited.
2998 This is a way to exclude a few tags from inheritance. For way to do
2999 the opposite, to actively allow inheritance for selected tags,
3000 see the variable `org-use-tag-inheritance'."
3001 :group 'org-tags
3002 :type '(repeat (string :tag "Tag")))
3004 (defun org-tag-inherit-p (tag)
3005 "Check if TAG is one that should be inherited."
3006 (cond
3007 ((member tag org-tags-exclude-from-inheritance) nil)
3008 ((eq org-use-tag-inheritance t) t)
3009 ((not org-use-tag-inheritance) nil)
3010 ((stringp org-use-tag-inheritance)
3011 (string-match org-use-tag-inheritance tag))
3012 ((listp org-use-tag-inheritance)
3013 (member tag org-use-tag-inheritance))
3014 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3016 (defcustom org-tags-match-list-sublevels t
3017 "Non-nil means list also sublevels of headlines matching a search.
3018 This variable applies to tags/property searches, and also to stuck
3019 projects because this search is based on a tags match as well.
3021 When set to the symbol `indented', sublevels are indented with
3022 leading dots.
3024 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3025 the sublevels of a headline matching a tag search often also match
3026 the same search. Listing all of them can create very long lists.
3027 Setting this variable to nil causes subtrees of a match to be skipped.
3029 This variable is semi-obsolete and probably should always be true. It
3030 is better to limit inheritance to certain tags using the variables
3031 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3032 :group 'org-tags
3033 :type '(choice
3034 (const :tag "No, don't list them" nil)
3035 (const :tag "Yes, do list them" t)
3036 (const :tag "List them, indented with leading dots" indented)))
3038 (defcustom org-tags-sort-function nil
3039 "When set, tags are sorted using this function as a comparator."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No sorting" nil)
3043 (const :tag "Alphabetical" string<)
3044 (const :tag "Reverse alphabetical" string>)
3045 (function :tag "Custom function" nil)))
3047 (defvar org-tags-history nil
3048 "History of minibuffer reads for tags.")
3049 (defvar org-last-tags-completion-table nil
3050 "The last used completion table for tags.")
3051 (defvar org-after-tags-change-hook nil
3052 "Hook that is run after the tags in a line have changed.")
3054 (defgroup org-properties nil
3055 "Options concerning properties in Org-mode."
3056 :tag "Org Properties"
3057 :group 'org)
3059 (defcustom org-property-format "%-10s %s"
3060 "How property key/value pairs should be formatted by `indent-line'.
3061 When `indent-line' hits a property definition, it will format the line
3062 according to this format, mainly to make sure that the values are
3063 lined-up with respect to each other."
3064 :group 'org-properties
3065 :type 'string)
3067 (defcustom org-properties-postprocess-alist nil
3068 "Alist of properties and functions to adjust inserted values.
3069 Elements of this alist must be of the form
3071 ([string] [function])
3073 where [string] must be a property name and [function] must be a
3074 lambda expression: this lambda expression must take one argument,
3075 the value to adjust, and return the new value as a string.
3077 For example, this element will allow the property \"Remaining\"
3078 to be updated wrt the relation between the \"Effort\" property
3079 and the clock summary:
3081 ((\"Remaining\" (lambda(value)
3082 (let ((clocksum (org-clock-sum-current-item))
3083 (effort (org-duration-string-to-minutes
3084 (org-entry-get (point) \"Effort\"))))
3085 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3086 :group 'org-properties
3087 :version "24.1"
3088 :type '(alist :key-type (string :tag "Property")
3089 :value-type (function :tag "Function")))
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-agenda-action-key [?k]
3287 "The key to be installed in `calendar-mode-map' for agenda-action.
3288 The command `org-agenda-action' will be bound to this key. The
3289 default is the character `k' because we use the same key in the agenda."
3290 :group 'org-agenda
3291 :type 'sexp)
3293 (defcustom org-calendar-insert-diary-entry-key [?i]
3294 "The key to be installed in `calendar-mode-map' for adding diary entries.
3295 This option is irrelevant until `org-agenda-diary-file' has been configured
3296 to point to an Org-mode file. When that is the case, the command
3297 `org-agenda-diary-entry' will be bound to the key given here, by default
3298 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3299 if you want to continue doing this, you need to change this to a different
3300 key."
3301 :group 'org-agenda
3302 :type 'sexp)
3304 (defcustom org-agenda-diary-file 'diary-file
3305 "File to which to add new entries with the `i' key in agenda and calendar.
3306 When this is the symbol `diary-file', the functionality in the Emacs
3307 calendar will be used to add entries to the `diary-file'. But when this
3308 points to a file, `org-agenda-diary-entry' will be used instead."
3309 :group 'org-agenda
3310 :type '(choice
3311 (const :tag "The standard Emacs diary file" diary-file)
3312 (file :tag "Special Org file diary entries")))
3314 (eval-after-load "calendar"
3315 '(progn
3316 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3317 'org-calendar-goto-agenda)
3318 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3319 'org-agenda-action)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defcustom org-latex-create-formula-image-program 'dvipng
3394 "Program to convert LaTeX fragments with.
3396 dvipng Process the LaTeX fragments to dvi file, then convert
3397 dvi files to png files using dvipng.
3398 This will also include processing of non-math environments.
3399 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3400 to convert pdf files to png files"
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "dvipng" dvipng)
3405 (const :tag "imagemagick" imagemagick)))
3407 (defun org-format-latex-mathml-available-p ()
3408 "Return t if `org-latex-to-mathml-convert-command' is usable."
3409 (save-match-data
3410 (when (and (boundp 'org-latex-to-mathml-convert-command)
3411 org-latex-to-mathml-convert-command)
3412 (let ((executable (car (split-string
3413 org-latex-to-mathml-convert-command))))
3414 (when (executable-find executable)
3415 (if (string-match
3416 "%j" org-latex-to-mathml-convert-command)
3417 (file-readable-p org-latex-to-mathml-jar-file)
3418 t))))))
3420 (defcustom org-format-latex-header "\\documentclass{article}
3421 \\usepackage[usenames]{color}
3422 \\usepackage{amsmath}
3423 \\usepackage[mathscr]{eucal}
3424 \\pagestyle{empty} % do not remove
3425 \[PACKAGES]
3426 \[DEFAULT-PACKAGES]
3427 % The settings below are copied from fullpage.sty
3428 \\setlength{\\textwidth}{\\paperwidth}
3429 \\addtolength{\\textwidth}{-3cm}
3430 \\setlength{\\oddsidemargin}{1.5cm}
3431 \\addtolength{\\oddsidemargin}{-2.54cm}
3432 \\setlength{\\evensidemargin}{\\oddsidemargin}
3433 \\setlength{\\textheight}{\\paperheight}
3434 \\addtolength{\\textheight}{-\\headheight}
3435 \\addtolength{\\textheight}{-\\headsep}
3436 \\addtolength{\\textheight}{-\\footskip}
3437 \\addtolength{\\textheight}{-3cm}
3438 \\setlength{\\topmargin}{1.5cm}
3439 \\addtolength{\\topmargin}{-2.54cm}"
3440 "The document header used for processing LaTeX fragments.
3441 It is imperative that this header make sure that no page number
3442 appears on the page. The package defined in the variables
3443 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3444 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3445 will be appended."
3446 :group 'org-latex
3447 :type 'string)
3449 (defvar org-format-latex-header-extra nil)
3451 (defun org-set-packages-alist (var val)
3452 "Set the packages alist and make sure it has 3 elements per entry."
3453 (set var (mapcar (lambda (x)
3454 (if (and (consp x) (= (length x) 2))
3455 (list (car x) (nth 1 x) t)
3457 val)))
3459 (defun org-get-packages-alist (var)
3461 "Get the packages alist and make sure it has 3 elements per entry."
3462 (mapcar (lambda (x)
3463 (if (and (consp x) (= (length x) 2))
3464 (list (car x) (nth 1 x) t)
3466 (default-value var)))
3468 ;; The following variables are defined here because is it also used
3469 ;; when formatting latex fragments. Originally it was part of the
3470 ;; LaTeX exporter, which is why the name includes "export".
3471 (defcustom org-export-latex-default-packages-alist
3472 '(("AUTO" "inputenc" t)
3473 ("T1" "fontenc" t)
3474 ("" "fixltx2e" nil)
3475 ("" "graphicx" t)
3476 ("" "longtable" nil)
3477 ("" "float" nil)
3478 ("" "wrapfig" nil)
3479 ("" "soul" t)
3480 ("" "textcomp" t)
3481 ("" "marvosym" t)
3482 ("" "wasysym" t)
3483 ("" "latexsym" t)
3484 ("" "amssymb" t)
3485 ("" "hyperref" nil)
3486 "\\tolerance=1000"
3488 "Alist of default packages to be inserted in the header.
3489 Change this only if one of the packages here causes an incompatibility
3490 with another package you are using.
3491 The packages in this list are needed by one part or another of Org-mode
3492 to function properly.
3494 - inputenc, fontenc: for basic font and character selection
3495 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3496 for interpreting the entities in `org-entities'. You can skip some of these
3497 packages if you don't use any of the symbols in it.
3498 - graphicx: for including images
3499 - float, wrapfig: for figure placement
3500 - longtable: for long tables
3501 - hyperref: for cross references
3503 Therefore you should not modify this variable unless you know what you
3504 are doing. The one reason to change it anyway is that you might be loading
3505 some other package that conflicts with one of the default packages.
3506 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3507 If SNIPPET-FLAG is t, the package also needs to be included when
3508 compiling LaTeX snippets into images for inclusion into HTML."
3509 :group 'org-export-latex
3510 :set 'org-set-packages-alist
3511 :get 'org-get-packages-alist
3512 :version "24.1"
3513 :type '(repeat
3514 (choice
3515 (list :tag "options/package pair"
3516 (string :tag "options")
3517 (string :tag "package")
3518 (boolean :tag "Snippet"))
3519 (string :tag "A line of LaTeX"))))
3521 (defcustom org-export-latex-packages-alist nil
3522 "Alist of packages to be inserted in every LaTeX header.
3523 These will be inserted after `org-export-latex-default-packages-alist'.
3524 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3525 SNIPPET-FLAG, when t, indicates that this package is also needed when
3526 turning LaTeX snippets into images for inclusion into HTML.
3527 Make sure that you only list packages here which:
3528 - you want in every file
3529 - do not conflict with the default packages in
3530 `org-export-latex-default-packages-alist'
3531 - do not conflict with the setup in `org-format-latex-header'."
3532 :group 'org-export-latex
3533 :set 'org-set-packages-alist
3534 :get 'org-get-packages-alist
3535 :type '(repeat
3536 (choice
3537 (list :tag "options/package pair"
3538 (string :tag "options")
3539 (string :tag "package")
3540 (boolean :tag "Snippet"))
3541 (string :tag "A line of LaTeX"))))
3544 (defgroup org-appearance nil
3545 "Settings for Org-mode appearance."
3546 :tag "Org Appearance"
3547 :group 'org)
3549 (defcustom org-level-color-stars-only nil
3550 "Non-nil means fontify only the stars in each headline.
3551 When nil, the entire headline is fontified.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-leading-stars nil
3558 "Non-nil means hide the first N-1 stars in a headline.
3559 This works by using the face `org-hide' for these stars. This
3560 face is white for a light background, and black for a dark
3561 background. You may have to customize the face `org-hide' to
3562 make this work.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified.
3565 You may also set this on a per-file basis by adding one of the following
3566 lines to the buffer:
3568 #+STARTUP: hidestars
3569 #+STARTUP: showstars"
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defcustom org-hidden-keywords nil
3574 "List of symbols corresponding to keywords to be hidden the org buffer.
3575 For example, a value '(title) for this list will make the document's title
3576 appear in the buffer without the initial #+TITLE: keyword."
3577 :group 'org-appearance
3578 :version "24.1"
3579 :type '(set (const :tag "#+AUTHOR" author)
3580 (const :tag "#+DATE" date)
3581 (const :tag "#+EMAIL" email)
3582 (const :tag "#+TITLE" title)))
3584 (defcustom org-fontify-done-headline nil
3585 "Non-nil means change the face of a headline if it is marked DONE.
3586 Normally, only the TODO/DONE keyword indicates the state of a headline.
3587 When this is non-nil, the headline after the keyword is set to the
3588 `org-headline-done' as an additional indication."
3589 :group 'org-appearance
3590 :type 'boolean)
3592 (defcustom org-fontify-emphasized-text t
3593 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3594 Changing this variable requires a restart of Emacs to take effect."
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-fontify-whole-heading-line nil
3599 "Non-nil means fontify the whole line for headings.
3600 This is useful when setting a background color for the
3601 org-level-* faces."
3602 :group 'org-appearance
3603 :type 'boolean)
3605 (defcustom org-highlight-latex-fragments-and-specials nil
3606 "Non-nil means fontify what is treated specially by the exporters."
3607 :group 'org-appearance
3608 :type 'boolean)
3610 (defcustom org-hide-emphasis-markers nil
3611 "Non-nil mean font-lock should hide the emphasis marker characters."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-pretty-entities nil
3616 "Non-nil means show entities as UTF8 characters.
3617 When nil, the \\name form remains in the buffer."
3618 :group 'org-appearance
3619 :version "24.1"
3620 :type 'boolean)
3622 (defcustom org-pretty-entities-include-sub-superscripts t
3623 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3624 :group 'org-appearance
3625 :version "24.1"
3626 :type 'boolean)
3628 (defvar org-emph-re nil
3629 "Regular expression for matching emphasis.
3630 After a match, the match groups contain these elements:
3631 0 The match of the full regular expression, including the characters
3632 before and after the proper match
3633 1 The character before the proper match, or empty at beginning of line
3634 2 The proper match, including the leading and trailing markers
3635 3 The leading marker like * or /, indicating the type of highlighting
3636 4 The text between the emphasis markers, not including the markers
3637 5 The character after the match, empty at the end of a line")
3638 (defvar org-verbatim-re nil
3639 "Regular expression for matching verbatim text.")
3640 (defvar org-emphasis-regexp-components) ; defined just below
3641 (defvar org-emphasis-alist) ; defined just below
3642 (defun org-set-emph-re (var val)
3643 "Set variable and compute the emphasis regular expression."
3644 (set var val)
3645 (when (and (boundp 'org-emphasis-alist)
3646 (boundp 'org-emphasis-regexp-components)
3647 org-emphasis-alist org-emphasis-regexp-components)
3648 (let* ((e org-emphasis-regexp-components)
3649 (pre (car e))
3650 (post (nth 1 e))
3651 (border (nth 2 e))
3652 (body (nth 3 e))
3653 (nl (nth 4 e))
3654 (body1 (concat body "*?"))
3655 (markers (mapconcat 'car org-emphasis-alist ""))
3656 (vmarkers (mapconcat
3657 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3658 org-emphasis-alist "")))
3659 ;; make sure special characters appear at the right position in the class
3660 (if (string-match "\\^" markers)
3661 (setq markers (concat (replace-match "" t t markers) "^")))
3662 (if (string-match "-" markers)
3663 (setq markers (concat (replace-match "" t t markers) "-")))
3664 (if (string-match "\\^" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3666 (if (string-match "-" vmarkers)
3667 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3668 (if (> nl 0)
3669 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3670 (int-to-string nl) "\\}")))
3671 ;; Make the regexp
3672 (setq org-emph-re
3673 (concat "\\([" pre "]\\|^\\)"
3674 "\\("
3675 "\\([" markers "]\\)"
3676 "\\("
3677 "[^" border "]\\|"
3678 "[^" border "]"
3679 body1
3680 "[^" border "]"
3681 "\\)"
3682 "\\3\\)"
3683 "\\([" post "]\\|$\\)"))
3684 (setq org-verbatim-re
3685 (concat "\\([" pre "]\\|^\\)"
3686 "\\("
3687 "\\([" vmarkers "]\\)"
3688 "\\("
3689 "[^" border "]\\|"
3690 "[^" border "]"
3691 body1
3692 "[^" border "]"
3693 "\\)"
3694 "\\3\\)"
3695 "\\([" post "]\\|$\\)")))))
3697 (defcustom org-emphasis-regexp-components
3698 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3699 "Components used to build the regular expression for emphasis.
3700 This is a list with five entries. Terminology: In an emphasis string
3701 like \" *strong word* \", we call the initial space PREMATCH, the final
3702 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3703 and \"trong wor\" is the body. The different components in this variable
3704 specify what is allowed/forbidden in each part:
3706 pre Chars allowed as prematch. Beginning of line will be allowed too.
3707 post Chars allowed as postmatch. End of line will be allowed too.
3708 border The chars *forbidden* as border characters.
3709 body-regexp A regexp like \".\" to match a body character. Don't use
3710 non-shy groups here, and don't allow newline here.
3711 newline The maximum number of newlines allowed in an emphasis exp.
3713 Use customize to modify this, or restart Emacs after changing it."
3714 :group 'org-appearance
3715 :set 'org-set-emph-re
3716 :type '(list
3717 (sexp :tag "Allowed chars in pre ")
3718 (sexp :tag "Allowed chars in post ")
3719 (sexp :tag "Forbidden chars in border ")
3720 (sexp :tag "Regexp for body ")
3721 (integer :tag "number of newlines allowed")
3722 (option (boolean :tag "Please ignore this button"))))
3724 (defcustom org-emphasis-alist
3725 `(("*" bold "<b>" "</b>")
3726 ("/" italic "<i>" "</i>")
3727 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3728 ("=" org-code "<code>" "</code>" verbatim)
3729 ("~" org-verbatim "<code>" "</code>" verbatim)
3730 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3731 "<del>" "</del>")
3733 "Special syntax for emphasized text.
3734 Text starting and ending with a special character will be emphasized, for
3735 example *bold*, _underlined_ and /italic/. This variable sets the marker
3736 characters, the face to be used by font-lock for highlighting in Org-mode
3737 Emacs buffers, and the HTML tags to be used for this.
3738 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3739 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3740 Use customize to modify this, or restart Emacs after changing it."
3741 :group 'org-appearance
3742 :set 'org-set-emph-re
3743 :type '(repeat
3744 (list
3745 (string :tag "Marker character")
3746 (choice
3747 (face :tag "Font-lock-face")
3748 (plist :tag "Face property list"))
3749 (string :tag "HTML start tag")
3750 (string :tag "HTML end tag")
3751 (option (const verbatim)))))
3753 (defvar org-protecting-blocks
3754 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3755 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3756 This is needed for font-lock setup.")
3758 ;;; Miscellaneous options
3760 (defgroup org-completion nil
3761 "Completion in Org-mode."
3762 :tag "Org Completion"
3763 :group 'org)
3765 (defcustom org-completion-use-ido nil
3766 "Non-nil means use ido completion wherever possible.
3767 Note that `ido-mode' must be active for this variable to be relevant.
3768 If you decide to turn this variable on, you might well want to turn off
3769 `org-outline-path-complete-in-steps'.
3770 See also `org-completion-use-iswitchb'."
3771 :group 'org-completion
3772 :type 'boolean)
3774 (defcustom org-completion-use-iswitchb nil
3775 "Non-nil means use iswitchb completion wherever possible.
3776 Note that `iswitchb-mode' must be active for this variable to be relevant.
3777 If you decide to turn this variable on, you might well want to turn off
3778 `org-outline-path-complete-in-steps'.
3779 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3780 :group 'org-completion
3781 :type 'boolean)
3783 (defcustom org-completion-fallback-command 'hippie-expand
3784 "The expansion command called by \\[pcomplete] in normal context.
3785 Normal means, no org-mode-specific context."
3786 :group 'org-completion
3787 :type 'function)
3789 ;;; Functions and variables from their packages
3790 ;; Declared here to avoid compiler warnings
3792 ;; XEmacs only
3793 (defvar outline-mode-menu-heading)
3794 (defvar outline-mode-menu-show)
3795 (defvar outline-mode-menu-hide)
3796 (defvar zmacs-regions) ; XEmacs regions
3798 ;; Emacs only
3799 (defvar mark-active)
3801 ;; Various packages
3802 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3803 (declare-function calendar-forward-day "cal-move" (arg))
3804 (declare-function calendar-goto-date "cal-move" (date))
3805 (declare-function calendar-goto-today "cal-move" ())
3806 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3807 (defvar calc-embedded-close-formula)
3808 (defvar calc-embedded-open-formula)
3809 (declare-function cdlatex-tab "ext:cdlatex" ())
3810 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3811 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3812 (defvar font-lock-unfontify-region-function)
3813 (declare-function iswitchb-read-buffer "iswitchb"
3814 (prompt &optional default require-match start matches-set))
3815 (defvar iswitchb-temp-buflist)
3816 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3817 (defvar org-agenda-tags-todo-honor-ignore-options)
3818 (declare-function org-agenda-skip "org-agenda" ())
3819 (declare-function
3820 org-agenda-format-item "org-agenda"
3821 (extra txt &optional category tags dotime noprefix remove-re habitp))
3822 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3823 (declare-function org-agenda-change-all-lines "org-agenda"
3824 (newhead hdmarker &optional fixface just-this))
3825 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3826 (declare-function org-agenda-maybe-redo "org-agenda" ())
3827 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3828 (beg end))
3829 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3830 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3831 "org-agenda" (&optional end))
3832 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3833 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3834 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3835 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3836 (declare-function org-indent-mode "org-indent" (&optional arg))
3837 (declare-function parse-time-string "parse-time" (string))
3838 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3839 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3840 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3841 (defvar remember-data-file)
3842 (defvar texmathp-why)
3843 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3844 (declare-function table--at-cell-p "table" (position &optional object at-column))
3846 (defvar w3m-current-url)
3847 (defvar w3m-current-title)
3849 (defvar org-latex-regexps)
3851 ;;; Autoload and prepare some org modules
3853 ;; Some table stuff that needs to be defined here, because it is used
3854 ;; by the functions setting up org-mode or checking for table context.
3856 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3857 "Detect an org-type or table-type table.")
3858 (defconst org-table-line-regexp "^[ \t]*|"
3859 "Detect an org-type table line.")
3860 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3861 "Detect an org-type table line.")
3862 (defconst org-table-hline-regexp "^[ \t]*|-"
3863 "Detect an org-type table hline.")
3864 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3865 "Detect a table-type table hline.")
3866 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3867 "Detect the first line outside a table when searching from within it.
3868 This works for both table types.")
3870 ;; Autoload the functions in org-table.el that are needed by functions here.
3872 (eval-and-compile
3873 (org-autoload "org-table"
3874 '(org-table-align org-table-begin org-table-blank-field
3875 org-table-convert org-table-convert-region org-table-copy-down
3876 org-table-copy-region org-table-create
3877 org-table-create-or-convert-from-region
3878 org-table-create-with-table.el org-table-current-dline
3879 org-table-cut-region org-table-delete-column org-table-edit-field
3880 org-table-edit-formulas org-table-end org-table-eval-formula
3881 org-table-export org-table-field-info
3882 org-table-get-stored-formulas org-table-goto-column
3883 org-table-hline-and-move org-table-import org-table-insert-column
3884 org-table-insert-hline org-table-insert-row org-table-iterate
3885 org-table-justify-field-maybe org-table-kill-row
3886 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3887 org-table-move-column org-table-move-column-left
3888 org-table-move-column-right org-table-move-row
3889 org-table-move-row-down org-table-move-row-up
3890 org-table-next-field org-table-next-row org-table-paste-rectangle
3891 org-table-previous-field org-table-recalculate
3892 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3893 org-table-toggle-coordinate-overlays
3894 org-table-toggle-formula-debugger org-table-wrap-region
3895 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3896 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3897 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3899 (defun org-at-table-p (&optional table-type)
3900 "Return t if the cursor is inside an org-type table.
3901 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3902 (if org-enable-table-editor
3903 (save-excursion
3904 (beginning-of-line 1)
3905 (looking-at (if table-type org-table-any-line-regexp
3906 org-table-line-regexp)))
3907 nil))
3908 (defsubst org-table-p () (org-at-table-p))
3910 (defun org-at-table.el-p ()
3911 "Return t if and only if we are at a table.el table."
3912 (and (org-at-table-p 'any)
3913 (save-excursion
3914 (goto-char (org-table-begin 'any))
3915 (looking-at org-table1-hline-regexp))))
3916 (defun org-table-recognize-table.el ()
3917 "If there is a table.el table nearby, recognize it and move into it."
3918 (if org-table-tab-recognizes-table.el
3919 (if (org-at-table.el-p)
3920 (progn
3921 (beginning-of-line 1)
3922 (if (looking-at org-table-dataline-regexp)
3924 (if (looking-at org-table1-hline-regexp)
3925 (progn
3926 (beginning-of-line 2)
3927 (if (looking-at org-table-any-border-regexp)
3928 (beginning-of-line -1)))))
3929 (if (re-search-forward "|" (org-table-end t) t)
3930 (progn
3931 (require 'table)
3932 (if (table--at-cell-p (point))
3934 (message "recognizing table.el table...")
3935 (table-recognize-table)
3936 (message "recognizing table.el table...done")))
3937 (error "This should not happen"))
3939 nil)
3940 nil))
3942 (defun org-at-table-hline-p ()
3943 "Return t if the cursor is inside a hline in a table."
3944 (if org-enable-table-editor
3945 (save-excursion
3946 (beginning-of-line 1)
3947 (looking-at org-table-hline-regexp))
3948 nil))
3950 (defvar org-table-clean-did-remove-column nil)
3952 (defun org-table-map-tables (function &optional quietly)
3953 "Apply FUNCTION to the start of all tables in the buffer."
3954 (save-excursion
3955 (save-restriction
3956 (widen)
3957 (goto-char (point-min))
3958 (while (re-search-forward org-table-any-line-regexp nil t)
3959 (unless quietly
3960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3961 (beginning-of-line 1)
3962 (when (and (looking-at org-table-line-regexp)
3963 ;; Exclude tables in src/example/verbatim/clocktable blocks
3964 (not (org-in-block-p '("src" "example"))))
3965 (save-excursion (funcall function))
3966 (or (looking-at org-table-line-regexp)
3967 (forward-char 1)))
3968 (re-search-forward org-table-any-border-regexp nil 1))))
3969 (unless quietly (message "Mapping tables: done")))
3971 ;; Declare and autoload functions from org-exp.el & Co
3973 (declare-function org-default-export-plist "org-exp")
3974 (declare-function org-infile-export-plist "org-exp")
3975 (declare-function org-get-current-options "org-exp")
3976 (eval-and-compile
3977 (org-autoload "org-exp"
3978 '(org-export org-export-visible
3979 org-insert-export-options-template
3980 org-table-clean-before-export))
3981 (org-autoload "org-ascii"
3982 '(org-export-as-ascii org-export-ascii-preprocess
3983 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3984 org-export-region-as-ascii))
3985 (org-autoload "org-latex"
3986 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3987 org-replace-region-by-latex org-export-region-as-latex
3988 org-export-as-latex org-export-as-pdf
3989 org-export-as-pdf-and-open))
3990 (org-autoload "org-html"
3991 '(org-export-as-html-and-open
3992 org-export-as-html-batch org-export-as-html-to-buffer
3993 org-replace-region-by-html org-export-region-as-html
3994 org-export-as-html))
3995 (org-autoload "org-docbook"
3996 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3997 org-replace-region-by-docbook org-export-region-as-docbook
3998 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3999 org-export-as-docbook))
4000 (org-autoload "org-icalendar"
4001 '(org-export-icalendar-this-file
4002 org-export-icalendar-all-agenda-files
4003 org-export-icalendar-combine-agenda-files))
4004 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4005 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4007 ;; Declare and autoload functions from org-agenda.el
4009 (eval-and-compile
4010 (org-autoload "org-agenda"
4011 '(org-agenda org-agenda-list org-search-view
4012 org-todo-list org-tags-view org-agenda-list-stuck-projects
4013 org-diary org-agenda-to-appt
4014 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4016 ;; Autoload org-remember
4018 (eval-and-compile
4019 (org-autoload "org-remember"
4020 '(org-remember-insinuate org-remember-annotation
4021 org-remember-apply-template org-remember org-remember-handler)))
4023 (eval-and-compile
4024 (org-autoload "org-capture"
4025 '(org-capture org-capture-insert-template-here
4026 org-capture-import-remember-templates)))
4028 ;; Autoload org-clock.el
4030 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4031 (beg end))
4032 (declare-function org-clock-update-mode-line "org-clock" ())
4033 (declare-function org-resolve-clocks "org-clock"
4034 (&optional also-non-dangling-p prompt last-valid))
4035 (defvar org-clock-start-time)
4036 (defvar org-clock-marker (make-marker)
4037 "Marker recording the last clock-in.")
4038 (defvar org-clock-hd-marker (make-marker)
4039 "Marker recording the last clock-in, but the headline position.")
4040 (defvar org-clock-heading ""
4041 "The heading of the current clock entry.")
4042 (defun org-clock-is-active ()
4043 "Return non-nil if clock is currently running.
4044 The return value is actually the clock marker."
4045 (marker-buffer org-clock-marker))
4047 (eval-and-compile
4048 (org-autoload
4049 "org-clock"
4050 '(org-clock-in org-clock-out org-clock-cancel
4051 org-clock-goto org-clock-sum org-clock-display
4052 org-clock-remove-overlays org-clock-report
4053 org-clocktable-shift org-dblock-write:clocktable
4054 org-get-clocktable org-resolve-clocks)))
4056 (defun org-clock-update-time-maybe ()
4057 "If this is a CLOCK line, update it and return t.
4058 Otherwise, return nil."
4059 (interactive)
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (skip-chars-forward " \t")
4063 (when (looking-at org-clock-string)
4064 (let ((re (concat "[ \t]*" org-clock-string
4065 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4066 "\\([ \t]*=>.*\\)?\\)?"))
4067 ts te h m s neg)
4068 (cond
4069 ((not (looking-at re))
4070 nil)
4071 ((not (match-end 2))
4072 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4073 (> org-clock-marker (point))
4074 (<= org-clock-marker (point-at-eol)))
4075 ;; The clock is running here
4076 (setq org-clock-start-time
4077 (apply 'encode-time
4078 (org-parse-time-string (match-string 1))))
4079 (org-clock-update-mode-line)))
4081 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4082 (end-of-line 1)
4083 (setq ts (match-string 1)
4084 te (match-string 3))
4085 (setq s (- (org-float-time
4086 (apply 'encode-time (org-parse-time-string te)))
4087 (org-float-time
4088 (apply 'encode-time (org-parse-time-string ts))))
4089 neg (< s 0)
4090 s (abs s)
4091 h (floor (/ s 3600))
4092 s (- s (* 3600 h))
4093 m (floor (/ s 60))
4094 s (- s (* 60 s)))
4095 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4096 t))))))
4098 (defun org-check-running-clock ()
4099 "Check if the current buffer contains the running clock.
4100 If yes, offer to stop it and to save the buffer with the changes."
4101 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4102 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4103 (buffer-name))))
4104 (org-clock-out)
4105 (when (y-or-n-p "Save changed buffer?")
4106 (save-buffer))))
4108 (defun org-clocktable-try-shift (dir n)
4109 "Check if this line starts a clock table, if yes, shift the time block."
4110 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4111 (org-clocktable-shift dir n)))
4113 ;; Autoload org-timer.el
4115 (eval-and-compile
4116 (org-autoload
4117 "org-timer"
4118 '(org-timer-start org-timer org-timer-item
4119 org-timer-change-times-in-region
4120 org-timer-set-timer
4121 org-timer-reset-timers
4122 org-timer-show-remaining-time)))
4124 ;; Autoload org-feed.el
4126 (eval-and-compile
4127 (org-autoload
4128 "org-feed"
4129 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4132 ;; Autoload org-indent.el
4134 ;; Define the variable already here, to make sure we have it.
4135 (defvar org-indent-mode nil
4136 "Non-nil if Org-Indent mode is enabled.
4137 Use the command `org-indent-mode' to change this variable.")
4139 (eval-and-compile
4140 (org-autoload
4141 "org-indent"
4142 '(org-indent-mode)))
4144 ;; Autoload org-mobile.el
4146 (eval-and-compile
4147 (org-autoload
4148 "org-mobile"
4149 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4151 ;; Autoload archiving code
4152 ;; The stuff that is needed for cycling and tags has to be defined here.
4154 (defgroup org-archive nil
4155 "Options concerning archiving in Org-mode."
4156 :tag "Org Archive"
4157 :group 'org-structure)
4159 (defcustom org-archive-location "%s_archive::"
4160 "The location where subtrees should be archived.
4162 The value of this variable is a string, consisting of two parts,
4163 separated by a double-colon. The first part is a filename and
4164 the second part is a headline.
4166 When the filename is omitted, archiving happens in the same file.
4167 %s in the filename will be replaced by the current file
4168 name (without the directory part). Archiving to a different file
4169 is useful to keep archived entries from contributing to the
4170 Org-mode Agenda.
4172 The archived entries will be filed as subtrees of the specified
4173 headline. When the headline is omitted, the subtrees are simply
4174 filed away at the end of the file, as top-level entries. Also in
4175 the heading you can use %s to represent the file name, this can be
4176 useful when using the same archive for a number of different files.
4178 Here are a few examples:
4179 \"%s_archive::\"
4180 If the current file is Projects.org, archive in file
4181 Projects.org_archive, as top-level trees. This is the default.
4183 \"::* Archived Tasks\"
4184 Archive in the current file, under the top-level headline
4185 \"* Archived Tasks\".
4187 \"~/org/archive.org::\"
4188 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4190 \"~/org/archive.org::* From %s\"
4191 Archive in file ~/org/archive.org (absolute path), under headlines
4192 \"From FILENAME\" where file name is the current file name.
4194 \"~/org/datetree.org::datetree/* Finished Tasks\"
4195 The \"datetree/\" string is special, signifying to archive
4196 items to the datetree. Items are placed in either the CLOSED
4197 date of the item, or the current date if there is no CLOSED date.
4198 The heading will be a subentry to the current date. There doesn't
4199 need to be a heading, but there always needs to be a slash after
4200 datetree. For example, to store archived items directly in the
4201 datetree, use \"~/org/datetree.org::datetree/\".
4203 \"basement::** Finished Tasks\"
4204 Archive in file ./basement (relative path), as level 3 trees
4205 below the level 2 heading \"** Finished Tasks\".
4207 You may set this option on a per-file basis by adding to the buffer a
4208 line like
4210 #+ARCHIVE: basement::** Finished Tasks
4212 You may also define it locally for a subtree by setting an ARCHIVE property
4213 in the entry. If such a property is found in an entry, or anywhere up
4214 the hierarchy, it will be used."
4215 :group 'org-archive
4216 :type 'string)
4218 (defcustom org-archive-tag "ARCHIVE"
4219 "The tag that marks a subtree as archived.
4220 An archived subtree does not open during visibility cycling, and does
4221 not contribute to the agenda listings.
4222 After changing this, font-lock must be restarted in the relevant buffers to
4223 get the proper fontification."
4224 :group 'org-archive
4225 :group 'org-keywords
4226 :type 'string)
4228 (defcustom org-agenda-skip-archived-trees t
4229 "Non-nil means the agenda will skip any items located in archived trees.
4230 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4231 variable is no longer recommended, you should leave it at the value t.
4232 Instead, use the key `v' to cycle the archives-mode in the agenda."
4233 :group 'org-archive
4234 :group 'org-agenda-skip
4235 :type 'boolean)
4237 (defcustom org-columns-skip-archived-trees t
4238 "Non-nil means ignore archived trees when creating column view."
4239 :group 'org-archive
4240 :group 'org-properties
4241 :type 'boolean)
4243 (defcustom org-cycle-open-archived-trees nil
4244 "Non-nil means `org-cycle' will open archived trees.
4245 An archived tree is a tree marked with the tag ARCHIVE.
4246 When nil, archived trees will stay folded. You can still open them with
4247 normal outline commands like `show-all', but not with the cycling commands."
4248 :group 'org-archive
4249 :group 'org-cycle
4250 :type 'boolean)
4252 (defcustom org-sparse-tree-open-archived-trees nil
4253 "Non-nil means sparse tree construction shows matches in archived trees.
4254 When nil, matches in these trees are highlighted, but the trees are kept in
4255 collapsed state."
4256 :group 'org-archive
4257 :group 'org-sparse-trees
4258 :type 'boolean)
4260 (defun org-cycle-hide-archived-subtrees (state)
4261 "Re-hide all archived subtrees after a visibility state change."
4262 (when (and (not org-cycle-open-archived-trees)
4263 (not (memq state '(overview folded))))
4264 (save-excursion
4265 (let* ((globalp (memq state '(contents all)))
4266 (beg (if globalp (point-min) (point)))
4267 (end (if globalp (point-max) (org-end-of-subtree t))))
4268 (org-hide-archived-subtrees beg end)
4269 (goto-char beg)
4270 (if (looking-at (concat ".*:" org-archive-tag ":"))
4271 (message "%s" (substitute-command-keys
4272 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4274 (defun org-force-cycle-archived ()
4275 "Cycle subtree even if it is archived."
4276 (interactive)
4277 (setq this-command 'org-cycle)
4278 (let ((org-cycle-open-archived-trees t))
4279 (call-interactively 'org-cycle)))
4281 (defun org-hide-archived-subtrees (beg end)
4282 "Re-hide all archived subtrees after a visibility state change."
4283 (save-excursion
4284 (let* ((re (concat ":" org-archive-tag ":")))
4285 (goto-char beg)
4286 (while (re-search-forward re end t)
4287 (when (org-at-heading-p)
4288 (org-flag-subtree t)
4289 (org-end-of-subtree t))))))
4291 (defun org-flag-subtree (flag)
4292 (save-excursion
4293 (org-back-to-heading t)
4294 (outline-end-of-heading)
4295 (outline-flag-region (point)
4296 (progn (org-end-of-subtree t) (point))
4297 flag)))
4299 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4301 (eval-and-compile
4302 (org-autoload "org-archive"
4303 '(org-add-archive-files org-archive-subtree
4304 org-archive-to-archive-sibling org-toggle-archive-tag
4305 org-archive-subtree-default
4306 org-archive-subtree-default-with-confirmation)))
4308 ;; Autoload Column View Code
4310 (declare-function org-columns-number-to-string "org-colview")
4311 (declare-function org-columns-get-format-and-top-level "org-colview")
4312 (declare-function org-columns-compute "org-colview")
4314 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4315 '(org-columns-number-to-string org-columns-get-format-and-top-level
4316 org-columns-compute org-agenda-columns org-columns-remove-overlays
4317 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4319 ;; Autoload ID code
4321 (declare-function org-id-store-link "org-id")
4322 (declare-function org-id-locations-load "org-id")
4323 (declare-function org-id-locations-save "org-id")
4324 (defvar org-id-track-globally)
4325 (org-autoload "org-id"
4326 '(org-id-get-create org-id-new org-id-copy org-id-get
4327 org-id-get-with-outline-path-completion
4328 org-id-get-with-outline-drilling org-id-store-link
4329 org-id-goto org-id-find org-id-store-link))
4331 ;; Autoload Plotting Code
4333 (org-autoload "org-plot"
4334 '(org-plot/gnuplot))
4336 ;;; Variables for pre-computed regular expressions, all buffer local
4338 (defvar org-drawer-regexp nil
4339 "Matches first line of a hidden block.")
4340 (make-variable-buffer-local 'org-drawer-regexp)
4341 (defvar org-todo-regexp nil
4342 "Matches any of the TODO state keywords.")
4343 (make-variable-buffer-local 'org-todo-regexp)
4344 (defvar org-not-done-regexp nil
4345 "Matches any of the TODO state keywords except the last one.")
4346 (make-variable-buffer-local 'org-not-done-regexp)
4347 (defvar org-not-done-heading-regexp nil
4348 "Matches a TODO headline that is not done.")
4349 (make-variable-buffer-local 'org-not-done-regexp)
4350 (defvar org-todo-line-regexp nil
4351 "Matches a headline and puts TODO state into group 2 if present.")
4352 (make-variable-buffer-local 'org-todo-line-regexp)
4353 (defvar org-complex-heading-regexp nil
4354 "Matches a headline and puts everything into groups:
4355 group 1: the stars
4356 group 2: The todo keyword, maybe
4357 group 3: Priority cookie
4358 group 4: True headline
4359 group 5: Tags")
4360 (make-variable-buffer-local 'org-complex-heading-regexp)
4361 (defvar org-complex-heading-regexp-format nil
4362 "Printf format to make regexp to match an exact headline.
4363 This regexp will match the headline of any node which has the
4364 exact headline text that is put into the format, but may have any
4365 TODO state, priority and tags.")
4366 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4367 (defvar org-todo-line-tags-regexp nil
4368 "Matches a headline and puts TODO state into group 2 if present.
4369 Also put tags into group 4 if tags are present.")
4370 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4371 (defvar org-ds-keyword-length 12
4372 "Maximum length of the Deadline and SCHEDULED keywords.")
4373 (make-variable-buffer-local 'org-ds-keyword-length)
4374 (defvar org-deadline-regexp nil
4375 "Matches the DEADLINE keyword.")
4376 (make-variable-buffer-local 'org-deadline-regexp)
4377 (defvar org-deadline-time-regexp nil
4378 "Matches the DEADLINE keyword together with a time stamp.")
4379 (make-variable-buffer-local 'org-deadline-time-regexp)
4380 (defvar org-deadline-line-regexp nil
4381 "Matches the DEADLINE keyword and the rest of the line.")
4382 (make-variable-buffer-local 'org-deadline-line-regexp)
4383 (defvar org-scheduled-regexp nil
4384 "Matches the SCHEDULED keyword.")
4385 (make-variable-buffer-local 'org-scheduled-regexp)
4386 (defvar org-scheduled-time-regexp nil
4387 "Matches the SCHEDULED keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-scheduled-time-regexp)
4389 (defvar org-closed-time-regexp nil
4390 "Matches the CLOSED keyword together with a time stamp.")
4391 (make-variable-buffer-local 'org-closed-time-regexp)
4393 (defvar org-keyword-time-regexp nil
4394 "Matches any of the 4 keywords, together with the time stamp.")
4395 (make-variable-buffer-local 'org-keyword-time-regexp)
4396 (defvar org-keyword-time-not-clock-regexp nil
4397 "Matches any of the 3 keywords, together with the time stamp.")
4398 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4399 (defvar org-maybe-keyword-time-regexp nil
4400 "Matches a timestamp, possibly preceded by a keyword.")
4401 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4402 (defvar org-planning-or-clock-line-re nil
4403 "Matches a line with planning or clock info.")
4404 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4405 (defvar org-all-time-keywords nil
4406 "List of time keywords.")
4407 (make-variable-buffer-local 'org-all-time-keywords)
4409 (defconst org-plain-time-of-day-regexp
4410 (concat
4411 "\\(\\<[012]?[0-9]"
4412 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4413 "\\(--?"
4414 "\\(\\<[012]?[0-9]"
4415 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4416 "\\)?")
4417 "Regular expression to match a plain time or time range.
4418 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4419 groups carry important information:
4420 0 the full match
4421 1 the first time, range or not
4422 8 the second time, if it is a range.")
4424 (defconst org-plain-time-extension-regexp
4425 (concat
4426 "\\(\\<[012]?[0-9]"
4427 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4428 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4429 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4430 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4431 groups carry important information:
4432 0 the full match
4433 7 hours of duration
4434 9 minutes of duration")
4436 (defconst org-stamp-time-of-day-regexp
4437 (concat
4438 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4439 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4440 "\\(--?"
4441 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4442 "Regular expression to match a timestamp time or time range.
4443 After a match, the following groups carry important information:
4444 0 the full match
4445 1 date plus weekday, for back referencing to make sure both times are on the same day
4446 2 the first time, range or not
4447 4 the second time, if it is a range.")
4449 (defconst org-startup-options
4450 '(("fold" org-startup-folded t)
4451 ("overview" org-startup-folded t)
4452 ("nofold" org-startup-folded nil)
4453 ("showall" org-startup-folded nil)
4454 ("showeverything" org-startup-folded showeverything)
4455 ("content" org-startup-folded content)
4456 ("indent" org-startup-indented t)
4457 ("noindent" org-startup-indented nil)
4458 ("hidestars" org-hide-leading-stars t)
4459 ("showstars" org-hide-leading-stars nil)
4460 ("odd" org-odd-levels-only t)
4461 ("oddeven" org-odd-levels-only nil)
4462 ("align" org-startup-align-all-tables t)
4463 ("noalign" org-startup-align-all-tables nil)
4464 ("inlineimages" org-startup-with-inline-images t)
4465 ("noinlineimages" org-startup-with-inline-images nil)
4466 ("customtime" org-display-custom-times t)
4467 ("logdone" org-log-done time)
4468 ("lognotedone" org-log-done note)
4469 ("nologdone" org-log-done nil)
4470 ("lognoteclock-out" org-log-note-clock-out t)
4471 ("nolognoteclock-out" org-log-note-clock-out nil)
4472 ("logrepeat" org-log-repeat state)
4473 ("lognoterepeat" org-log-repeat note)
4474 ("nologrepeat" org-log-repeat nil)
4475 ("logreschedule" org-log-reschedule time)
4476 ("lognotereschedule" org-log-reschedule note)
4477 ("nologreschedule" org-log-reschedule nil)
4478 ("logredeadline" org-log-redeadline time)
4479 ("lognoteredeadline" org-log-redeadline note)
4480 ("nologredeadline" org-log-redeadline nil)
4481 ("logrefile" org-log-refile time)
4482 ("lognoterefile" org-log-refile note)
4483 ("nologrefile" org-log-refile nil)
4484 ("fninline" org-footnote-define-inline t)
4485 ("nofninline" org-footnote-define-inline nil)
4486 ("fnlocal" org-footnote-section nil)
4487 ("fnauto" org-footnote-auto-label t)
4488 ("fnprompt" org-footnote-auto-label nil)
4489 ("fnconfirm" org-footnote-auto-label confirm)
4490 ("fnplain" org-footnote-auto-label plain)
4491 ("fnadjust" org-footnote-auto-adjust t)
4492 ("nofnadjust" org-footnote-auto-adjust nil)
4493 ("constcgs" constants-unit-system cgs)
4494 ("constSI" constants-unit-system SI)
4495 ("noptag" org-tag-persistent-alist nil)
4496 ("hideblocks" org-hide-block-startup t)
4497 ("nohideblocks" org-hide-block-startup nil)
4498 ("beamer" org-startup-with-beamer-mode t)
4499 ("entitiespretty" org-pretty-entities t)
4500 ("entitiesplain" org-pretty-entities nil))
4501 "Variable associated with STARTUP options for org-mode.
4502 Each element is a list of three items: The startup options as written
4503 in the #+STARTUP line, the corresponding variable, and the value to
4504 set this variable to if the option is found. An optional forth element PUSH
4505 means to push this value onto the list in the variable.")
4507 (defun org-update-property-plist (key val props)
4508 "Update PROPS with KEY and VAL."
4509 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4510 (key (if appending (substring key 0 (- (length key) 1)) key))
4511 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4512 (previous (cdr (assoc key props))))
4513 (if appending
4514 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4515 (cons (cons key val) remainder))))
4517 (defconst org-block-regexp
4518 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4519 "Regular expression for hiding blocks.")
4520 (defconst org-heading-keyword-regexp-format
4521 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4522 "Printf format for a regexp matching an headline with some keyword.
4523 This regexp will match the headline of any node which has the
4524 exact keyword that is put into the format. The keyword isn't in
4525 any group by default, but the stars and the body are.")
4526 (defconst org-heading-keyword-maybe-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline, possibly with some keyword.
4529 This regexp can match any headline with the specified keyword, or
4530 without a keyword. The keyword isn't in any group by default,
4531 but the stars and the body are.")
4533 (defun org-set-regexps-and-options ()
4534 "Precompute regular expressions for current buffer."
4535 (when (derived-mode-p 'org-mode)
4536 (org-set-local 'org-todo-kwd-alist nil)
4537 (org-set-local 'org-todo-key-alist nil)
4538 (org-set-local 'org-todo-key-trigger nil)
4539 (org-set-local 'org-todo-keywords-1 nil)
4540 (org-set-local 'org-done-keywords nil)
4541 (org-set-local 'org-todo-heads nil)
4542 (org-set-local 'org-todo-sets nil)
4543 (org-set-local 'org-todo-log-states nil)
4544 (org-set-local 'org-file-properties nil)
4545 (org-set-local 'org-file-tags nil)
4546 (let ((re (org-make-options-regexp
4547 '("CATEGORY" "TODO" "COLUMNS"
4548 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4549 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4550 "OPTIONS")
4551 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4552 (splitre "[ \t]+")
4553 (scripts org-use-sub-superscripts)
4554 kwds kws0 kwsa key log value cat arch tags const links hw dws
4555 tail sep kws1 prio props ftags drawers beamer-p
4556 ext-setup-or-nil setup-contents (start 0))
4557 (save-excursion
4558 (save-restriction
4559 (widen)
4560 (goto-char (point-min))
4561 (while (or (and ext-setup-or-nil
4562 (string-match re ext-setup-or-nil start)
4563 (setq start (match-end 0)))
4564 (and (setq ext-setup-or-nil nil start 0)
4565 (re-search-forward re nil t)))
4566 (setq key (upcase (match-string 1 ext-setup-or-nil))
4567 value (org-match-string-no-properties 2 ext-setup-or-nil))
4568 (if (stringp value) (setq value (org-trim value)))
4569 (cond
4570 ((equal key "CATEGORY")
4571 (setq cat value))
4572 ((member key '("SEQ_TODO" "TODO"))
4573 (push (cons 'sequence (org-split-string value splitre)) kwds))
4574 ((equal key "TYP_TODO")
4575 (push (cons 'type (org-split-string value splitre)) kwds))
4576 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4577 ;; general TODO-like setup
4578 (push (cons (intern (downcase (match-string 1 key)))
4579 (org-split-string value splitre)) kwds))
4580 ((equal key "TAGS")
4581 (setq tags (append tags (if tags '("\\n") nil)
4582 (org-split-string value splitre))))
4583 ((equal key "COLUMNS")
4584 (org-set-local 'org-columns-default-format value))
4585 ((equal key "LINK")
4586 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4587 (push (cons (match-string 1 value)
4588 (org-trim (match-string 2 value)))
4589 links)))
4590 ((equal key "PRIORITIES")
4591 (setq prio (org-split-string value " +")))
4592 ((equal key "PROPERTY")
4593 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4594 (setq props (org-update-property-plist (match-string 1 value)
4595 (match-string 2 value)
4596 props))))
4597 ((equal key "FILETAGS")
4598 (when (string-match "\\S-" value)
4599 (setq ftags
4600 (append
4601 ftags
4602 (apply 'append
4603 (mapcar (lambda (x) (org-split-string x ":"))
4604 (org-split-string value)))))))
4605 ((equal key "DRAWERS")
4606 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4607 ((equal key "CONSTANTS")
4608 (setq const (append const (org-split-string value splitre))))
4609 ((equal key "STARTUP")
4610 (let ((opts (org-split-string value splitre))
4611 l var val)
4612 (while (setq l (pop opts))
4613 (when (setq l (assoc l org-startup-options))
4614 (setq var (nth 1 l) val (nth 2 l))
4615 (if (not (nth 3 l))
4616 (set (make-local-variable var) val)
4617 (if (not (listp (symbol-value var)))
4618 (set (make-local-variable var) nil))
4619 (set (make-local-variable var) (symbol-value var))
4620 (add-to-list var val))))))
4621 ((equal key "ARCHIVE")
4622 (setq arch value)
4623 (remove-text-properties 0 (length arch)
4624 '(face t fontified t) arch))
4625 ((equal key "LATEX_CLASS")
4626 (setq beamer-p (equal value "beamer")))
4627 ((equal key "OPTIONS")
4628 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4629 (setq scripts (read (match-string 2 value)))))
4630 ((equal key "SETUPFILE")
4631 (setq setup-contents (org-file-contents
4632 (expand-file-name
4633 (org-remove-double-quotes value))
4634 'noerror))
4635 (if (not ext-setup-or-nil)
4636 (setq ext-setup-or-nil setup-contents start 0)
4637 (setq ext-setup-or-nil
4638 (concat (substring ext-setup-or-nil 0 start)
4639 "\n" setup-contents "\n"
4640 (substring ext-setup-or-nil start)))))))
4641 ;; search for property blocks
4642 (goto-char (point-min))
4643 (while (re-search-forward org-block-regexp nil t)
4644 (when (equal "PROPERTY" (upcase (match-string 1)))
4645 (setq value (replace-regexp-in-string
4646 "[\n\r]" " " (match-string 4)))
4647 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4648 (setq props (org-update-property-plist (match-string 1 value)
4649 (match-string 2 value)
4650 props)))))))
4651 (org-set-local 'org-use-sub-superscripts scripts)
4652 (when cat
4653 (org-set-local 'org-category (intern cat))
4654 (push (cons "CATEGORY" cat) props))
4655 (when prio
4656 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4657 (setq prio (mapcar 'string-to-char prio))
4658 (org-set-local 'org-highest-priority (nth 0 prio))
4659 (org-set-local 'org-lowest-priority (nth 1 prio))
4660 (org-set-local 'org-default-priority (nth 2 prio)))
4661 (and props (org-set-local 'org-file-properties (nreverse props)))
4662 (and ftags (org-set-local 'org-file-tags
4663 (mapcar 'org-add-prop-inherited ftags)))
4664 (and drawers (org-set-local 'org-drawers drawers))
4665 (and arch (org-set-local 'org-archive-location arch))
4666 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4667 ;; Process the TODO keywords
4668 (unless kwds
4669 ;; Use the global values as if they had been given locally.
4670 (setq kwds (default-value 'org-todo-keywords))
4671 (if (stringp (car kwds))
4672 (setq kwds (list (cons org-todo-interpretation
4673 (default-value 'org-todo-keywords)))))
4674 (setq kwds (reverse kwds)))
4675 (setq kwds (nreverse kwds))
4676 (let (inter kws kw)
4677 (while (setq kws (pop kwds))
4678 (let ((kws (or
4679 (run-hook-with-args-until-success
4680 'org-todo-setup-filter-hook kws)
4681 kws)))
4682 (setq inter (pop kws) sep (member "|" kws)
4683 kws0 (delete "|" (copy-sequence kws))
4684 kwsa nil
4685 kws1 (mapcar
4686 (lambda (x)
4687 ;; 1 2
4688 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4689 (progn
4690 (setq kw (match-string 1 x)
4691 key (and (match-end 2) (match-string 2 x))
4692 log (org-extract-log-state-settings x))
4693 (push (cons kw (and key (string-to-char key))) kwsa)
4694 (and log (push log org-todo-log-states))
4696 (error "Invalid TODO keyword %s" x)))
4697 kws0)
4698 kwsa (if kwsa (append '((:startgroup))
4699 (nreverse kwsa)
4700 '((:endgroup))))
4701 hw (car kws1)
4702 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4703 tail (list inter hw (car dws) (org-last dws))))
4704 (add-to-list 'org-todo-heads hw 'append)
4705 (push kws1 org-todo-sets)
4706 (setq org-done-keywords (append org-done-keywords dws nil))
4707 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4708 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4709 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4710 (setq org-todo-sets (nreverse org-todo-sets)
4711 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4712 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4713 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4714 ;; Process the constants
4715 (when const
4716 (let (e cst)
4717 (while (setq e (pop const))
4718 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4719 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4720 (setq org-table-formula-constants-local cst)))
4722 ;; Process the tags.
4723 (when tags
4724 (let (e tgs)
4725 (while (setq e (pop tags))
4726 (cond
4727 ((equal e "{") (push '(:startgroup) tgs))
4728 ((equal e "}") (push '(:endgroup) tgs))
4729 ((equal e "\\n") (push '(:newline) tgs))
4730 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4731 (push (cons (match-string 1 e)
4732 (string-to-char (match-string 2 e)))
4733 tgs))
4734 (t (push (list e) tgs))))
4735 (org-set-local 'org-tag-alist nil)
4736 (while (setq e (pop tgs))
4737 (or (and (stringp (car e))
4738 (assoc (car e) org-tag-alist))
4739 (push e org-tag-alist)))))
4741 ;; Compute the regular expressions and other local variables.
4742 ;; Using `org-outline-regexp-bol' would complicate them much,
4743 ;; because of the fixed white space at the end of that string.
4744 (if (not org-done-keywords)
4745 (setq org-done-keywords (and org-todo-keywords-1
4746 (list (org-last org-todo-keywords-1)))))
4747 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4748 (length org-scheduled-string)
4749 (length org-clock-string)
4750 (length org-closed-string)))
4751 org-drawer-regexp
4752 (concat "^[ \t]*:\\("
4753 (mapconcat 'regexp-quote org-drawers "\\|")
4754 "\\):[ \t]*$")
4755 org-not-done-keywords
4756 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4757 org-todo-regexp
4758 (concat "\\("
4759 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4760 "\\)")
4761 org-not-done-regexp
4762 (concat "\\("
4763 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4764 "\\)")
4765 org-not-done-heading-regexp
4766 (format org-heading-keyword-regexp-format org-not-done-regexp)
4767 org-todo-line-regexp
4768 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4769 org-complex-heading-regexp
4770 (concat "^\\(\\*+\\)"
4771 "\\(?: +" org-todo-regexp "\\)?"
4772 "\\(?: +\\(\\[#.\\]\\)\\)?"
4773 "\\(?: +\\(.*?\\)\\)?"
4774 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4775 "[ \t]*$")
4776 org-complex-heading-regexp-format
4777 (concat "^\\(\\*+\\)"
4778 "\\(?: +" org-todo-regexp "\\)?"
4779 "\\(?: +\\(\\[#.\\]\\)\\)?"
4780 "\\(?: +"
4781 ;; Stats cookies can be stuck to body.
4782 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4783 "\\(%s\\)"
4784 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4785 "\\)"
4786 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4787 "[ \t]*$")
4788 org-todo-line-tags-regexp
4789 (concat "^\\(\\*+\\)"
4790 "\\(?: +" org-todo-regexp "\\)?"
4791 "\\(?: +\\(.*?\\)\\)?"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-deadline-regexp (concat "\\<" org-deadline-string)
4795 org-deadline-time-regexp
4796 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4797 org-deadline-line-regexp
4798 (concat "\\<\\(" org-deadline-string "\\).*")
4799 org-scheduled-regexp
4800 (concat "\\<" org-scheduled-string)
4801 org-scheduled-time-regexp
4802 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4803 org-closed-time-regexp
4804 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4805 org-keyword-time-regexp
4806 (concat "\\<\\(" org-scheduled-string
4807 "\\|" org-deadline-string
4808 "\\|" org-closed-string
4809 "\\|" org-clock-string "\\)"
4810 " *[[<]\\([^]>]+\\)[]>]")
4811 org-keyword-time-not-clock-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-maybe-keyword-time-regexp
4818 (concat "\\(\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\|" org-clock-string "\\)\\)?"
4822 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4823 org-planning-or-clock-line-re
4824 (concat "^[ \t]*\\("
4825 org-scheduled-string "\\|"
4826 org-deadline-string "\\|"
4827 org-closed-string "\\|"
4828 org-clock-string "\\)")
4829 org-all-time-keywords
4830 (mapcar (lambda (w) (substring w 0 -1))
4831 (list org-scheduled-string org-deadline-string
4832 org-clock-string org-closed-string))
4834 (org-compute-latex-and-specials-regexp)
4835 (org-set-font-lock-defaults))))
4837 (defun org-file-contents (file &optional noerror)
4838 "Return the contents of FILE, as a string."
4839 (if (or (not file)
4840 (not (file-readable-p file)))
4841 (if noerror
4842 (progn
4843 (message "Cannot read file \"%s\"" file)
4844 (ding) (sit-for 2)
4846 (error "Cannot read file \"%s\"" file))
4847 (with-temp-buffer
4848 (insert-file-contents file)
4849 (buffer-string))))
4851 (defun org-extract-log-state-settings (x)
4852 "Extract the log state setting from a TODO keyword string.
4853 This will extract info from a string like \"WAIT(w@/!)\"."
4854 (let (kw key log1 log2)
4855 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log1 (and (match-end 3) (match-string 3 x))
4859 log2 (and (match-end 4) (match-string 4 x)))
4860 (and (or log1 log2)
4861 (list kw
4862 (and log1 (if (equal log1 "!") 'time 'note))
4863 (and log2 (if (equal log2 "!") 'time 'note)))))))
4865 (defun org-remove-keyword-keys (list)
4866 "Remove a pair of parenthesis at the end of each string in LIST."
4867 (mapcar (lambda (x)
4868 (if (string-match "(.*)$" x)
4869 (substring x 0 (match-beginning 0))
4871 list))
4873 (defun org-assign-fast-keys (alist)
4874 "Assign fast keys to a keyword-key alist.
4875 Respect keys that are already there."
4876 (let (new e (alt ?0))
4877 (while (setq e (pop alist))
4878 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4879 (cdr e)) ;; Key already assigned.
4880 (push e new)
4881 (let ((clist (string-to-list (downcase (car e))))
4882 (used (append new alist)))
4883 (when (= (car clist) ?@)
4884 (pop clist))
4885 (while (and clist (rassoc (car clist) used))
4886 (pop clist))
4887 (unless clist
4888 (while (rassoc alt used)
4889 (incf alt)))
4890 (push (cons (car e) (or (car clist) alt)) new))))
4891 (nreverse new)))
4893 ;;; Some variables used in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-selected-window nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like remember.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4907 (defvar org-last-state)
4908 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar org-entities) ;; defined in org-entities.el
4912 (defvar org-struct-menu)
4913 (defvar org-org-menu)
4914 (defvar org-tbl-menu)
4916 ;;;; Define the Org-mode
4918 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4919 (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"))
4922 ;; We use a before-change function to check if a table might need
4923 ;; an update.
4924 (defvar org-table-may-need-update t
4925 "Indicates that a table might need an update.
4926 This variable is set by `org-before-change-function'.
4927 `org-table-align' sets it back to nil.")
4928 (defun org-before-change-function (beg end)
4929 "Every change indicates that a table might need an update."
4930 (setq org-table-may-need-update t))
4931 (defvar org-mode-map)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4933 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4934 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4935 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4936 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4937 (defvar org-table-buffer-is-an nil)
4939 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4940 ;; some places -- e.g. see the macro org-with-limited-levels.
4942 ;; In Org buffers, the value of `outline-regexp' is that of
4943 ;; `org-outline-regexp'. The only function still directly relying on
4944 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4945 ;; job when `orgstruct-mode' is active.
4946 (defvar org-outline-regexp "\\*+ "
4947 "Regexp to match Org headlines.")
4948 (defconst org-outline-regexp-bol "^\\*+ "
4949 "Regexp to match Org headlines.
4950 This is similar to `org-outline-regexp' but additionally makes
4951 sure that we are at the beginning of the line.")
4953 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4954 "Matches an headline, putting stars and text into groups.
4955 Stars are put in group 1 and the trimmed body in group 2.")
4957 (defvar bidi-paragraph-direction)
4958 (defvar buffer-face-mode-face)
4960 ;;;###autoload
4961 (define-derived-mode org-mode outline-mode "Org"
4962 "Outline-based notes management and organizer, alias
4963 \"Carsten's outline-mode for keeping track of everything.\"
4965 Org-mode develops organizational tasks around a NOTES file which
4966 contains information about projects as plain text. Org-mode is
4967 implemented on top of outline-mode, which is ideal to keep the content
4968 of large files well structured. It supports ToDo items, deadlines and
4969 time stamps, which magically appear in the diary listing of the Emacs
4970 calendar. Tables are easily created with a built-in table editor.
4971 Plain text URL-like links connect to websites, emails (VM), Usenet
4972 messages (Gnus), BBDB entries, and any files related to the project.
4973 For printing and sharing of notes, an Org-mode file (or a part of it)
4974 can be exported as a structured ASCII or HTML file.
4976 The following commands are available:
4978 \\{org-mode-map}"
4980 ;; Get rid of Outline menus, they are not needed
4981 ;; Need to do this here because define-derived-mode sets up
4982 ;; the keymap so late. Still, it is a waste to call this each time
4983 ;; we switch another buffer into org-mode.
4984 (if (featurep 'xemacs)
4985 (when (boundp 'outline-mode-menu-heading)
4986 ;; Assume this is Greg's port, it uses easymenu
4987 (easy-menu-remove outline-mode-menu-heading)
4988 (easy-menu-remove outline-mode-menu-show)
4989 (easy-menu-remove outline-mode-menu-hide))
4990 (define-key org-mode-map [menu-bar headings] 'undefined)
4991 (define-key org-mode-map [menu-bar hide] 'undefined)
4992 (define-key org-mode-map [menu-bar show] 'undefined))
4994 (org-load-modules-maybe)
4995 (easy-menu-add org-org-menu)
4996 (easy-menu-add org-tbl-menu)
4997 (org-install-agenda-files-menu)
4998 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4999 (add-to-invisibility-spec '(org-cwidth))
5000 (add-to-invisibility-spec '(org-hide-block . t))
5001 (when (featurep 'xemacs)
5002 (org-set-local 'line-move-ignore-invisible t))
5003 (org-set-local 'outline-regexp org-outline-regexp)
5004 (org-set-local 'outline-level 'org-outline-level)
5005 (setq bidi-paragraph-direction 'left-to-right)
5006 (when (and org-ellipsis
5007 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5008 (fboundp 'make-glyph-code))
5009 (unless org-display-table
5010 (setq org-display-table (make-display-table)))
5011 (set-display-table-slot
5012 org-display-table 4
5013 (vconcat (mapcar
5014 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5015 org-ellipsis)))
5016 (if (stringp org-ellipsis) org-ellipsis "..."))))
5017 (setq buffer-display-table org-display-table))
5018 (org-set-regexps-and-options)
5019 (when (and org-tag-faces (not org-tags-special-faces-re))
5020 ;; tag faces set outside customize.... force initialization.
5021 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5022 ;; Calc embedded
5023 (org-set-local 'calc-embedded-open-mode "# ")
5024 (modify-syntax-entry ?@ "w")
5025 (if org-startup-truncated (setq truncate-lines t))
5026 (org-set-local 'font-lock-unfontify-region-function
5027 'org-unfontify-region)
5028 ;; Activate before-change-function
5029 (org-set-local 'org-table-may-need-update t)
5030 (org-add-hook 'before-change-functions 'org-before-change-function nil
5031 'local)
5032 ;; Check for running clock before killing a buffer
5033 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5034 ;; Paragraphs and auto-filling
5035 (org-set-autofill-regexps)
5036 (setq indent-line-function 'org-indent-line-function)
5037 (org-update-radio-target-regexp)
5038 ;; Beginning/end of defun
5039 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5040 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5041 ;; Next error for sparse trees
5042 (org-set-local 'next-error-function 'org-occur-next-match)
5043 ;; Make sure dependence stuff works reliably, even for users who set it
5044 ;; too late :-(
5045 (if org-enforce-todo-dependencies
5046 (add-hook 'org-blocker-hook
5047 'org-block-todo-from-children-or-siblings-or-parent)
5048 (remove-hook 'org-blocker-hook
5049 'org-block-todo-from-children-or-siblings-or-parent))
5050 (if org-enforce-todo-checkbox-dependencies
5051 (add-hook 'org-blocker-hook
5052 'org-block-todo-from-checkboxes)
5053 (remove-hook 'org-blocker-hook
5054 'org-block-todo-from-checkboxes))
5056 ;; Comment characters
5057 (org-set-local 'comment-start "#")
5058 (org-set-local 'comment-padding " ")
5060 ;; Align options lines
5061 (org-set-local
5062 'align-mode-rules-list
5063 '((org-in-buffer-settings
5064 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5065 (modes . '(org-mode)))))
5067 ;; Imenu
5068 (org-set-local 'imenu-create-index-function
5069 'org-imenu-get-tree)
5071 ;; Make isearch reveal context
5072 (if (or (featurep 'xemacs)
5073 (not (boundp 'outline-isearch-open-invisible-function)))
5074 ;; Emacs 21 and XEmacs make use of the hook
5075 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5076 ;; Emacs 22 deals with this through a special variable
5077 (org-set-local 'outline-isearch-open-invisible-function
5078 (lambda (&rest ignore) (org-show-context 'isearch))))
5080 ;; Turn on org-beamer-mode?
5081 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5083 ;; Setup the pcomplete hooks
5084 (set (make-local-variable 'pcomplete-command-completion-function)
5085 'org-pcomplete-initial)
5086 (set (make-local-variable 'pcomplete-command-name-function)
5087 'org-command-at-point)
5088 (set (make-local-variable 'pcomplete-default-completion-function)
5089 'ignore)
5090 (set (make-local-variable 'pcomplete-parse-arguments-function)
5091 'org-parse-arguments)
5092 (set (make-local-variable 'pcomplete-termination-string) "")
5093 (when (>= emacs-major-version 23)
5094 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5096 ;; If empty file that did not turn on org-mode automatically, make it to.
5097 (if (and org-insert-mode-line-in-empty-file
5098 (org-called-interactively-p 'any)
5099 (= (point-min) (point-max)))
5100 (insert "# -*- mode: org -*-\n\n"))
5101 (unless org-inhibit-startup
5102 (when org-startup-align-all-tables
5103 (let ((bmp (buffer-modified-p)))
5104 (org-table-map-tables 'org-table-align 'quietly)
5105 (set-buffer-modified-p bmp)))
5106 (when org-startup-with-inline-images
5107 (org-display-inline-images))
5108 (when org-startup-indented
5109 (require 'org-indent)
5110 (org-indent-mode 1))
5111 (unless org-inhibit-startup-visibility-stuff
5112 (org-set-startup-visibility))))
5114 (when (fboundp 'abbrev-table-put)
5115 (abbrev-table-put org-mode-abbrev-table
5116 :parents (list text-mode-abbrev-table)))
5118 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5120 (defun org-current-time ()
5121 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5122 (if (> (car org-time-stamp-rounding-minutes) 1)
5123 (let ((r (car org-time-stamp-rounding-minutes))
5124 (time (decode-time)))
5125 (apply 'encode-time
5126 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5127 (nthcdr 2 time))))
5128 (current-time)))
5130 (defun org-today ()
5131 "Return today date, considering `org-extend-today-until'."
5132 (time-to-days
5133 (time-subtract (current-time)
5134 (list 0 (* 3600 org-extend-today-until) 0))))
5136 ;;;; Font-Lock stuff, including the activators
5138 (defvar org-mouse-map (make-sparse-keymap))
5139 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5140 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5141 (when org-mouse-1-follows-link
5142 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5143 (when org-tab-follows-link
5144 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5145 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5147 (require 'font-lock)
5149 (defconst org-non-link-chars "]\t\n\r<>")
5150 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5151 "shell" "elisp" "doi" "message"))
5152 (defvar org-link-types-re nil
5153 "Matches a link that has a url-like prefix like \"http:\"")
5154 (defvar org-link-re-with-space nil
5155 "Matches a link with spaces, optional angular brackets around it.")
5156 (defvar org-link-re-with-space2 nil
5157 "Matches a link with spaces, optional angular brackets around it.")
5158 (defvar org-link-re-with-space3 nil
5159 "Matches a link with spaces, only for internal part in bracket links.")
5160 (defvar org-angle-link-re nil
5161 "Matches link with angular brackets, spaces are allowed.")
5162 (defvar org-plain-link-re nil
5163 "Matches plain link, without spaces.")
5164 (defvar org-bracket-link-regexp nil
5165 "Matches a link in double brackets.")
5166 (defvar org-bracket-link-analytic-regexp nil
5167 "Regular expression used to analyze links.
5168 Here is what the match groups contain after a match:
5169 1: http:
5170 2: http
5171 3: path
5172 4: [desc]
5173 5: desc")
5174 (defvar org-bracket-link-analytic-regexp++ nil
5175 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5176 (defvar org-any-link-re nil
5177 "Regular expression matching any link.")
5179 (defcustom org-match-sexp-depth 3
5180 "Number of stacked braces for sub/superscript matching.
5181 This has to be set before loading org.el to be effective."
5182 :group 'org-export-translation ; ??????????????????????????/
5183 :type 'integer)
5185 (defun org-create-multibrace-regexp (left right n)
5186 "Create a regular expression which will match a balanced sexp.
5187 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5188 as single character strings.
5189 The regexp returned will match the entire expression including the
5190 delimiters. It will also define a single group which contains the
5191 match except for the outermost delimiters. The maximum depth of
5192 stacked delimiters is N. Escaping delimiters is not possible."
5193 (let* ((nothing (concat "[^" left right "]*?"))
5194 (or "\\|")
5195 (re nothing)
5196 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5197 (while (> n 1)
5198 (setq n (1- n)
5199 re (concat re or next)
5200 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5201 (concat left "\\(" re "\\)" right)))
5203 (defvar org-match-substring-regexp
5204 (concat
5205 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5206 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5207 "\\|"
5208 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5209 "\\|"
5210 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5211 "The regular expression matching a sub- or superscript.")
5213 (defvar org-match-substring-with-braces-regexp
5214 (concat
5215 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5216 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5217 "\\)")
5218 "The regular expression matching a sub- or superscript, forcing braces.")
5220 (defun org-make-link-regexps ()
5221 "Update the link regular expressions.
5222 This should be called after the variable `org-link-types' has changed."
5223 (setq org-link-types-re
5224 (concat
5225 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5226 org-link-re-with-space
5227 (concat
5228 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5229 "\\([^" org-non-link-chars " ]"
5230 "[^" org-non-link-chars "]*"
5231 "[^" org-non-link-chars " ]\\)>?")
5232 org-link-re-with-space2
5233 (concat
5234 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5235 "\\([^" org-non-link-chars " ]"
5236 "[^\t\n\r]*"
5237 "[^" org-non-link-chars " ]\\)>?")
5238 org-link-re-with-space3
5239 (concat
5240 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5241 "\\([^" org-non-link-chars " ]"
5242 "[^\t\n\r]*\\)")
5243 org-angle-link-re
5244 (concat
5245 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5246 "\\([^" org-non-link-chars " ]"
5247 "[^" org-non-link-chars "]*"
5248 "\\)>")
5249 org-plain-link-re
5250 (concat
5251 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5252 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5253 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5254 org-bracket-link-regexp
5255 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5256 org-bracket-link-analytic-regexp
5257 (concat
5258 "\\[\\["
5259 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5260 "\\([^]]+\\)"
5261 "\\]"
5262 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5263 "\\]")
5264 org-bracket-link-analytic-regexp++
5265 (concat
5266 "\\[\\["
5267 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5268 "\\([^]]+\\)"
5269 "\\]"
5270 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5271 "\\]")
5272 org-any-link-re
5273 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5274 org-angle-link-re "\\)\\|\\("
5275 org-plain-link-re "\\)")))
5277 (org-make-link-regexps)
5279 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5280 "Regular expression for fast time stamp matching.")
5281 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5282 "Regular expression for fast time stamp matching.")
5283 (defconst org-ts-regexp0
5284 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5285 "Regular expression matching time strings for analysis.
5286 This one does not require the space after the date, so it can be used
5287 on a string that terminates immediately after the date.")
5288 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5289 "Regular expression matching time strings for analysis.")
5290 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5291 "Regular expression matching time stamps, with groups.")
5292 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5293 "Regular expression matching time stamps (also [..]), with groups.")
5294 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5295 "Regular expression matching a time stamp range.")
5296 (defconst org-tr-regexp-both
5297 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5298 "Regular expression matching a time stamp range.")
5299 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5300 org-ts-regexp "\\)?")
5301 "Regular expression matching a time stamp or time stamp range.")
5302 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5303 org-ts-regexp-both "\\)?")
5304 "Regular expression matching a time stamp or time stamp range.
5305 The time stamps may be either active or inactive.")
5307 (defvar org-emph-face nil)
5309 (defun org-do-emphasis-faces (limit)
5310 "Run through the buffer and add overlays to emphasized strings."
5311 (let (rtn a)
5312 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5313 (if (not (= (char-after (match-beginning 3))
5314 (char-after (match-beginning 4))))
5315 (progn
5316 (setq rtn t)
5317 (setq a (assoc (match-string 3) org-emphasis-alist))
5318 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5319 'face
5320 (nth 1 a))
5321 (and (nth 4 a)
5322 (org-remove-flyspell-overlays-in
5323 (match-beginning 0) (match-end 0)))
5324 (add-text-properties (match-beginning 2) (match-end 2)
5325 '(font-lock-multiline t org-emphasis t))
5326 (when org-hide-emphasis-markers
5327 (add-text-properties (match-end 4) (match-beginning 5)
5328 '(invisible org-link))
5329 (add-text-properties (match-beginning 3) (match-end 3)
5330 '(invisible org-link)))))
5331 (backward-char 1))
5332 rtn))
5334 (defun org-emphasize (&optional char)
5335 "Insert or change an emphasis, i.e. a font like bold or italic.
5336 If there is an active region, change that region to a new emphasis.
5337 If there is no region, just insert the marker characters and position
5338 the cursor between them.
5339 CHAR should be either the marker character, or the first character of the
5340 HTML tag associated with that emphasis. If CHAR is a space, the means
5341 to remove the emphasis of the selected region.
5342 If char is not given (for example in an interactive call) it
5343 will be prompted for."
5344 (interactive)
5345 (let ((eal org-emphasis-alist) e det
5346 (erc org-emphasis-regexp-components)
5347 (prompt "")
5348 (string "") beg end move tag c s)
5349 (if (org-region-active-p)
5350 (setq beg (region-beginning) end (region-end)
5351 string (buffer-substring beg end))
5352 (setq move t))
5354 (while (setq e (pop eal))
5355 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5356 c (aref tag 0))
5357 (push (cons c (string-to-char (car e))) det)
5358 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5359 (substring tag 1)))))
5360 (setq det (nreverse det))
5361 (unless char
5362 (message "%s" (concat "Emphasis marker or tag:" prompt))
5363 (setq char (read-char-exclusive)))
5364 (setq char (or (cdr (assoc char det)) char))
5365 (if (equal char ?\ )
5366 (setq s "" move nil)
5367 (unless (assoc (char-to-string char) org-emphasis-alist)
5368 (error "No such emphasis marker: \"%c\"" char))
5369 (setq s (char-to-string char)))
5370 (while (and (> (length string) 1)
5371 (equal (substring string 0 1) (substring string -1))
5372 (assoc (substring string 0 1) org-emphasis-alist))
5373 (setq string (substring string 1 -1)))
5374 (setq string (concat s string s))
5375 (if beg (delete-region beg end))
5376 (unless (or (bolp)
5377 (string-match (concat "[" (nth 0 erc) "\n]")
5378 (char-to-string (char-before (point)))))
5379 (insert " "))
5380 (unless (or (eobp)
5381 (string-match (concat "[" (nth 1 erc) "\n]")
5382 (char-to-string (char-after (point)))))
5383 (insert " ") (backward-char 1))
5384 (insert string)
5385 (and move (backward-char 1))))
5387 (defconst org-nonsticky-props
5388 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5390 (defsubst org-rear-nonsticky-at (pos)
5391 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5393 (defun org-activate-plain-links (limit)
5394 "Run through the buffer and add overlays to links."
5395 (catch 'exit
5396 (let (f)
5397 (if (re-search-forward org-plain-link-re limit t)
5398 (progn
5399 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5400 (setq f (get-text-property (match-beginning 0) 'face))
5401 (if (or (eq f 'org-tag)
5402 (and (listp f) (memq 'org-tag f)))
5404 (add-text-properties (match-beginning 0) (match-end 0)
5405 (list 'mouse-face 'highlight
5406 'face 'org-link
5407 'keymap org-mouse-map))
5408 (org-rear-nonsticky-at (match-end 0)))
5409 t)))))
5411 (defun org-activate-code (limit)
5412 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5413 (progn
5414 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 t)))
5419 (defcustom org-src-fontify-natively nil
5420 "When non-nil, fontify code in code blocks."
5421 :type 'boolean
5422 :version "24.1"
5423 :group 'org-appearance
5424 :group 'org-babel)
5426 (defcustom org-src-prevent-auto-filling nil
5427 "When non-nil, prevent auto-filling in src blocks."
5428 :type 'boolean
5429 :version "24.1"
5430 :group 'org-appearance
5431 :group 'org-babel)
5433 (defcustom org-allow-promoting-top-level-subtree nil
5434 "When non-nil, allow promoting a top level subtree.
5435 The leading star of the top level headline will be replaced
5436 by a #."
5437 :type 'boolean
5438 :version "24.1"
5439 :group 'org-appearance)
5441 (defun org-fontify-meta-lines-and-blocks (limit)
5442 (condition-case nil
5443 (org-fontify-meta-lines-and-blocks-1 limit)
5444 (error (message "org-mode fontification error"))))
5446 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5447 "Fontify #+ lines and blocks, in the correct ways."
5448 (let ((case-fold-search t))
5449 (if (re-search-forward
5450 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5451 limit t)
5452 (let ((beg (match-beginning 0))
5453 (block-start (match-end 0))
5454 (block-end nil)
5455 (lang (match-string 7))
5456 (beg1 (line-beginning-position 2))
5457 (dc1 (downcase (match-string 2)))
5458 (dc3 (downcase (match-string 3)))
5459 end end1 quoting block-type ovl)
5460 (cond
5461 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5462 ;; a single line of backend-specific content
5463 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5464 (remove-text-properties (match-beginning 0) (match-end 0)
5465 '(display t invisible t intangible t))
5466 (add-text-properties (match-beginning 1) (match-end 3)
5467 '(font-lock-fontified t face org-meta-line))
5468 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5469 '(font-lock-fontified t face org-block))
5470 ; for backend-specific code
5472 ((and (match-end 4) (equal dc3 "begin"))
5473 ;; Truly a block
5474 (setq block-type (downcase (match-string 5))
5475 quoting (member block-type org-protecting-blocks))
5476 (when (re-search-forward
5477 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5478 nil t) ;; on purpose, we look further than LIMIT
5479 (setq end (min (point-max) (match-end 0))
5480 end1 (min (point-max) (1- (match-beginning 0))))
5481 (setq block-end (match-beginning 0))
5482 (when quoting
5483 (remove-text-properties beg end
5484 '(display t invisible t intangible t)))
5485 (add-text-properties
5486 beg end
5487 '(font-lock-fontified t font-lock-multiline t))
5488 (add-text-properties beg beg1 '(face org-meta-line))
5489 (add-text-properties end1 (min (point-max) (1+ end))
5490 '(face org-meta-line)) ; for end_src
5491 (cond
5492 ((and lang (not (string= lang "")) org-src-fontify-natively)
5493 (org-src-font-lock-fontify-block lang block-start block-end)
5494 ;; remove old background overlays
5495 (mapc (lambda (ov)
5496 (if (eq (overlay-get ov 'face) 'org-block-background)
5497 (delete-overlay ov)))
5498 (overlays-at (/ (+ beg1 block-end) 2)))
5499 ;; add a background overlay
5500 (setq ovl (make-overlay beg1 block-end))
5501 (overlay-put ovl 'face 'org-block-background)
5502 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5503 (quoting
5504 (add-text-properties beg1 (min (point-max) (1+ end1))
5505 '(face org-block))) ; end of source block
5506 ((not org-fontify-quote-and-verse-blocks))
5507 ((string= block-type "quote")
5508 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5509 ((string= block-type "verse")
5510 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5511 (add-text-properties beg beg1 '(face org-block-begin-line))
5512 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5513 '(face org-block-end-line))
5515 ((member dc1 '("title:" "author:" "email:" "date:"))
5516 (add-text-properties
5517 beg (match-end 3)
5518 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5519 '(font-lock-fontified t invisible t)
5520 '(font-lock-fontified t face org-document-info-keyword)))
5521 (add-text-properties
5522 (match-beginning 6) (match-end 6)
5523 (if (string-equal dc1 "title:")
5524 '(font-lock-fontified t face org-document-title)
5525 '(font-lock-fontified t face org-document-info))))
5526 ((not (member (char-after beg) '(?\ ?\t)))
5527 ;; just any other in-buffer setting, but not indented
5528 (add-text-properties
5529 beg (match-end 0)
5530 '(font-lock-fontified t face org-meta-line))
5532 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5533 "orgtbl:" "tblfm:" "tblname:" "results:"
5534 "call:" "header:" "headers:" "name:"))
5535 (and (match-end 4) (equal dc3 "attr")))
5536 (add-text-properties
5537 beg (match-end 0)
5538 '(font-lock-fontified t face org-meta-line))
5540 ((member dc3 '(" " ""))
5541 (add-text-properties
5542 beg (match-end 0)
5543 '(font-lock-fontified t face font-lock-comment-face)))
5544 (t nil))))))
5546 (defun org-strip-protective-commas (beg end)
5547 "Strip protective commas between BEG and END in the current buffer."
5548 (interactive "r")
5549 (save-excursion
5550 (save-match-data
5551 (goto-char beg)
5552 (let ((front-line (save-excursion
5553 (re-search-forward
5554 "[^[:space:]]" end t)
5555 (goto-char (match-beginning 0))
5556 (current-column))))
5557 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t)
5558 (goto-char (match-beginning 1))
5559 (when (= (current-column) front-line)
5560 (replace-match "" nil nil nil 1)))))))
5562 (defun org-activate-angle-links (limit)
5563 "Run through the buffer and add overlays to links."
5564 (if (re-search-forward org-angle-link-re limit t)
5565 (progn
5566 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5567 (add-text-properties (match-beginning 0) (match-end 0)
5568 (list 'mouse-face 'highlight
5569 'keymap org-mouse-map))
5570 (org-rear-nonsticky-at (match-end 0))
5571 t)))
5573 (defun org-activate-footnote-links (limit)
5574 "Run through the buffer and add overlays to footnotes."
5575 (let ((fn (org-footnote-next-reference-or-definition limit)))
5576 (when fn
5577 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5578 (org-remove-flyspell-overlays-in beg end)
5579 (add-text-properties beg end
5580 (list 'mouse-face 'highlight
5581 'keymap org-mouse-map
5582 'help-echo
5583 (if (= (point-at-bol) beg)
5584 "Footnote definition"
5585 "Footnote reference")
5586 'font-lock-fontified t
5587 'font-lock-multiline t
5588 'face 'org-footnote))))))
5590 (defun org-activate-bracket-links (limit)
5591 "Run through the buffer and add overlays to bracketed links."
5592 (if (re-search-forward org-bracket-link-regexp limit t)
5593 (let* ((help (concat "LINK: "
5594 (org-match-string-no-properties 1)))
5595 ;; FIXME: above we should remove the escapes.
5596 ;; but that requires another match, protecting match data,
5597 ;; a lot of overhead for font-lock.
5598 (ip (org-maybe-intangible
5599 (list 'invisible 'org-link
5600 'keymap org-mouse-map 'mouse-face 'highlight
5601 'font-lock-multiline t 'help-echo help)))
5602 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5603 'font-lock-multiline t 'help-echo help)))
5604 ;; We need to remove the invisible property here. Table narrowing
5605 ;; may have made some of this invisible.
5606 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5607 (remove-text-properties (match-beginning 0) (match-end 0)
5608 '(invisible nil))
5609 (if (match-end 3)
5610 (progn
5611 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5612 (org-rear-nonsticky-at (match-beginning 3))
5613 (add-text-properties (match-beginning 3) (match-end 3) vp)
5614 (org-rear-nonsticky-at (match-end 3))
5615 (add-text-properties (match-end 3) (match-end 0) ip)
5616 (org-rear-nonsticky-at (match-end 0)))
5617 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5618 (org-rear-nonsticky-at (match-beginning 1))
5619 (add-text-properties (match-beginning 1) (match-end 1) vp)
5620 (org-rear-nonsticky-at (match-end 1))
5621 (add-text-properties (match-end 1) (match-end 0) ip)
5622 (org-rear-nonsticky-at (match-end 0)))
5623 t)))
5625 (defun org-activate-dates (limit)
5626 "Run through the buffer and add overlays to dates."
5627 (if (re-search-forward org-tsr-regexp-both limit t)
5628 (progn
5629 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5630 (add-text-properties (match-beginning 0) (match-end 0)
5631 (list 'mouse-face 'highlight
5632 'keymap org-mouse-map))
5633 (org-rear-nonsticky-at (match-end 0))
5634 (when org-display-custom-times
5635 (if (match-end 3)
5636 (org-display-custom-time (match-beginning 3) (match-end 3)))
5637 (org-display-custom-time (match-beginning 1) (match-end 1)))
5638 t)))
5640 (defvar org-target-link-regexp nil
5641 "Regular expression matching radio targets in plain text.")
5642 (make-variable-buffer-local 'org-target-link-regexp)
5643 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5644 "Regular expression matching a link target.")
5645 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5646 "Regular expression matching a radio target.")
5647 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5648 "Regular expression matching any target.")
5650 (defun org-activate-target-links (limit)
5651 "Run through the buffer and add overlays to target matches."
5652 (when org-target-link-regexp
5653 (let ((case-fold-search t))
5654 (if (re-search-forward org-target-link-regexp limit t)
5655 (progn
5656 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5657 (add-text-properties (match-beginning 0) (match-end 0)
5658 (list 'mouse-face 'highlight
5659 'keymap org-mouse-map
5660 'help-echo "Radio target link"
5661 'org-linked-text t))
5662 (org-rear-nonsticky-at (match-end 0))
5663 t)))))
5665 (defun org-update-radio-target-regexp ()
5666 "Find all radio targets in this file and update the regular expression."
5667 (interactive)
5668 (when (memq 'radio org-activate-links)
5669 (setq org-target-link-regexp
5670 (org-make-target-link-regexp (org-all-targets 'radio)))
5671 (org-restart-font-lock)))
5673 (defun org-hide-wide-columns (limit)
5674 (let (s e)
5675 (setq s (text-property-any (point) (or limit (point-max))
5676 'org-cwidth t))
5677 (when s
5678 (setq e (next-single-property-change s 'org-cwidth))
5679 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5680 (goto-char e)
5681 t)))
5683 (defvar org-latex-and-specials-regexp nil
5684 "Regular expression for highlighting export special stuff.")
5685 (defvar org-match-substring-regexp)
5686 (defvar org-match-substring-with-braces-regexp)
5688 ;; This should be with the exporter code, but we also use if for font-locking
5689 (defconst org-export-html-special-string-regexps
5690 '(("\\\\-" . "&shy;")
5691 ("---\\([^-]\\)" . "&mdash;\\1")
5692 ("--\\([^-]\\)" . "&ndash;\\1")
5693 ("\\.\\.\\." . "&hellip;"))
5694 "Regular expressions for special string conversion.")
5697 (defun org-compute-latex-and-specials-regexp ()
5698 "Compute regular expression for stuff treated specially by exporters."
5699 (if (not org-highlight-latex-fragments-and-specials)
5700 (org-set-local 'org-latex-and-specials-regexp nil)
5701 (require 'org-exp)
5702 (let*
5703 ((matchers (plist-get org-format-latex-options :matchers))
5704 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5705 org-latex-regexps)))
5706 (org-export-allow-BIND nil)
5707 (options (org-combine-plists (org-default-export-plist)
5708 (org-infile-export-plist)))
5709 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5710 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5711 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5712 (org-export-html-expand (plist-get options :expand-quoted-html))
5713 (org-export-with-special-strings (plist-get options :special-strings))
5714 (re-sub
5715 (cond
5716 ((equal org-export-with-sub-superscripts '{})
5717 (list org-match-substring-with-braces-regexp))
5718 (org-export-with-sub-superscripts
5719 (list org-match-substring-regexp))
5720 (t nil)))
5721 (re-latex
5722 (if org-export-with-LaTeX-fragments
5723 (mapcar (lambda (x) (nth 1 x)) latexs)))
5724 (re-macros
5725 (if org-export-with-TeX-macros
5726 (list (concat "\\\\"
5727 (regexp-opt
5728 (append
5730 (delq nil
5731 (mapcar 'car-safe
5732 (append org-entities-user
5733 org-entities)))
5734 (if (boundp 'org-latex-entities)
5735 (mapcar (lambda (x)
5736 (or (car-safe x) x))
5737 org-latex-entities)
5738 nil))
5739 'words))) ; FIXME
5741 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5742 (re-special (if org-export-with-special-strings
5743 (mapcar (lambda (x) (car x))
5744 org-export-html-special-string-regexps)))
5745 (re-rest
5746 (delq nil
5747 (list
5748 (if org-export-html-expand "@<[^>\n]+>")
5749 ))))
5750 (org-set-local
5751 'org-latex-and-specials-regexp
5752 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5753 re-rest) "\\|")))))
5755 (defun org-do-latex-and-special-faces (limit)
5756 "Run through the buffer and add overlays to links."
5757 (when org-latex-and-specials-regexp
5758 (let (rtn d)
5759 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5760 limit t))
5761 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5762 'face))
5763 '(org-code org-verbatim underline)))
5764 (progn
5765 (setq rtn t
5766 d (cond ((member (char-after (1+ (match-beginning 0)))
5767 '(?_ ?^)) 1)
5768 (t 0)))
5769 (font-lock-prepend-text-property
5770 (+ d (match-beginning 0)) (match-end 0)
5771 'face 'org-latex-and-export-specials)
5772 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5773 '(font-lock-multiline t)))))
5774 rtn)))
5776 (defun org-restart-font-lock ()
5777 "Restart `font-lock-mode', to force refontification."
5778 (when (and (boundp 'font-lock-mode) font-lock-mode)
5779 (font-lock-mode -1)
5780 (font-lock-mode 1)))
5782 (defun org-all-targets (&optional radio)
5783 "Return a list of all targets in this file.
5784 With optional argument RADIO, only find radio targets."
5785 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5786 rtn)
5787 (save-excursion
5788 (goto-char (point-min))
5789 (while (re-search-forward re nil t)
5790 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5791 rtn)))
5793 (defun org-make-target-link-regexp (targets)
5794 "Make regular expression matching all strings in TARGETS.
5795 The regular expression finds the targets also if there is a line break
5796 between words."
5797 (and targets
5798 (concat
5799 "\\<\\("
5800 (mapconcat
5801 (lambda (x)
5802 (setq x (regexp-quote x))
5803 (while (string-match " +" x)
5804 (setq x (replace-match "\\s-+" t t x)))
5806 targets
5807 "\\|")
5808 "\\)\\>")))
5810 (defun org-activate-tags (limit)
5811 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5812 (progn
5813 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5814 (add-text-properties (match-beginning 1) (match-end 1)
5815 (list 'mouse-face 'highlight
5816 'keymap org-mouse-map))
5817 (org-rear-nonsticky-at (match-end 1))
5818 t)))
5820 (defun org-outline-level ()
5821 "Compute the outline level of the heading at point.
5822 This function assumes that the cursor is at the beginning of a line matched
5823 by `outline-regexp'. Otherwise it returns garbage.
5824 If this is called at a normal headline, the level is the number of stars.
5825 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5826 (save-excursion
5827 (looking-at org-outline-regexp)
5828 (1- (- (match-end 0) (match-beginning 0)))))
5830 (defvar org-font-lock-keywords nil)
5832 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5833 "Regular expression matching a property line.")
5835 (defvar org-font-lock-hook nil
5836 "Functions to be called for special font lock stuff.")
5838 (defvar org-font-lock-set-keywords-hook nil
5839 "Functions that can manipulate `org-font-lock-extra-keywords'.
5840 This is called after `org-font-lock-extra-keywords' is defined, but before
5841 it is installed to be used by font lock. This can be useful if something
5842 needs to be inserted at a specific position in the font-lock sequence.")
5844 (defun org-font-lock-hook (limit)
5845 (run-hook-with-args 'org-font-lock-hook limit))
5847 (defun org-set-font-lock-defaults ()
5848 (let* ((em org-fontify-emphasized-text)
5849 (lk org-activate-links)
5850 (org-font-lock-extra-keywords
5851 (list
5852 ;; Call the hook
5853 '(org-font-lock-hook)
5854 ;; Headlines
5855 `(,(if org-fontify-whole-heading-line
5856 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5857 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5858 (1 (org-get-level-face 1))
5859 (2 (org-get-level-face 2))
5860 (3 (org-get-level-face 3)))
5861 ;; Table lines
5862 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5863 (1 'org-table t))
5864 ;; Table internals
5865 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5866 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5867 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5868 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5869 ;; Drawers
5870 (list org-drawer-regexp '(0 'org-special-keyword t))
5871 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5872 ;; Properties
5873 (list org-property-re
5874 '(1 'org-special-keyword t)
5875 '(3 'org-property-value t))
5876 ;; Links
5877 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5878 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5879 (if (memq 'plain lk) '(org-activate-plain-links))
5880 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5881 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5882 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5883 (if (memq 'footnote lk) '(org-activate-footnote-links))
5884 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5885 '(org-hide-wide-columns (0 nil append))
5886 ;; TODO keyword
5887 (list (format org-heading-keyword-regexp-format
5888 org-todo-regexp)
5889 '(2 (org-get-todo-face 2) t))
5890 ;; DONE
5891 (if org-fontify-done-headline
5892 (list (format org-heading-keyword-regexp-format
5893 (concat
5894 "\\(?:"
5895 (mapconcat 'regexp-quote org-done-keywords "\\|")
5896 "\\)"))
5897 '(2 'org-headline-done t))
5898 nil)
5899 ;; Priorities
5900 '(org-font-lock-add-priority-faces)
5901 ;; Tags
5902 '(org-font-lock-add-tag-faces)
5903 ;; Special keywords
5904 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5905 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5906 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5907 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5908 ;; Emphasis
5909 (if em
5910 (if (featurep 'xemacs)
5911 '(org-do-emphasis-faces (0 nil append))
5912 '(org-do-emphasis-faces)))
5913 ;; Checkboxes
5914 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5915 1 'org-checkbox prepend)
5916 (if (cdr (assq 'checkbox org-list-automatic-rules))
5917 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5918 (0 (org-get-checkbox-statistics-face) t)))
5919 ;; Description list items
5920 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5921 1 'org-list-dt prepend)
5922 ;; ARCHIVEd headings
5923 (list (concat
5924 org-outline-regexp-bol
5925 "\\(.*:" org-archive-tag ":.*\\)")
5926 '(1 'org-archived prepend))
5927 ;; Specials
5928 '(org-do-latex-and-special-faces)
5929 '(org-fontify-entities)
5930 '(org-raise-scripts)
5931 ;; Code
5932 '(org-activate-code (1 'org-code t))
5933 ;; COMMENT
5934 (list (format org-heading-keyword-regexp-format
5935 (concat "\\("
5936 org-comment-string "\\|" org-quote-string
5937 "\\)"))
5938 '(2 'org-special-keyword t))
5939 '("^#.*" (0 'font-lock-comment-face t))
5940 ;; Blocks and meta lines
5941 '(org-fontify-meta-lines-and-blocks)
5943 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5944 (run-hooks 'org-font-lock-set-keywords-hook)
5945 ;; Now set the full font-lock-keywords
5946 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5947 (org-set-local 'font-lock-defaults
5948 '(org-font-lock-keywords t nil nil backward-paragraph))
5949 (kill-local-variable 'font-lock-keywords) nil))
5951 (defun org-toggle-pretty-entities ()
5952 "Toggle the composition display of entities as UTF8 characters."
5953 (interactive)
5954 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5955 (org-restart-font-lock)
5956 (if org-pretty-entities
5957 (message "Entities are displayed as UTF8 characters")
5958 (save-restriction
5959 (widen)
5960 (org-decompose-region (point-min) (point-max))
5961 (message "Entities are displayed plain"))))
5963 (defun org-fontify-entities (limit)
5964 "Find an entity to fontify."
5965 (let (ee)
5966 (when org-pretty-entities
5967 (catch 'match
5968 (while (re-search-forward
5969 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5970 limit t)
5971 (if (and (not (org-in-indented-comment-line))
5972 (setq ee (org-entity-get (match-string 1)))
5973 (= (length (nth 6 ee)) 1))
5974 (let*
5975 ((end (if (equal (match-string 2) "{}")
5976 (match-end 2)
5977 (match-end 1))))
5978 (add-text-properties
5979 (match-beginning 0) end
5980 (list 'font-lock-fontified t))
5981 (compose-region (match-beginning 0) end
5982 (nth 6 ee) nil)
5983 (backward-char 1)
5984 (throw 'match t))))
5985 nil))))
5987 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5988 "Fontify string S like in Org-mode."
5989 (with-temp-buffer
5990 (insert s)
5991 (let ((org-odd-levels-only odd-levels))
5992 (org-mode)
5993 (font-lock-fontify-buffer)
5994 (buffer-string))))
5996 (defvar org-m nil)
5997 (defvar org-l nil)
5998 (defvar org-f nil)
5999 (defun org-get-level-face (n)
6000 "Get the right face for match N in font-lock matching of headlines."
6001 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6002 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6003 (if org-cycle-level-faces
6004 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6005 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6006 (cond
6007 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6008 ((eq n 2) org-f)
6009 (t (if org-level-color-stars-only nil org-f))))
6012 (defun org-get-todo-face (kwd)
6013 "Get the right face for a TODO keyword KWD.
6014 If KWD is a number, get the corresponding match group."
6015 (if (numberp kwd) (setq kwd (match-string kwd)))
6016 (or (org-face-from-face-or-color
6017 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6018 (and (member kwd org-done-keywords) 'org-done)
6019 'org-todo))
6021 (defun org-face-from-face-or-color (context inherit face-or-color)
6022 "Create a face list that inherits INHERIT, but sets the foreground color.
6023 When FACE-OR-COLOR is not a string, just return it."
6024 (if (stringp face-or-color)
6025 (list :inherit inherit
6026 (cdr (assoc context org-faces-easy-properties))
6027 face-or-color)
6028 face-or-color))
6030 (defun org-font-lock-add-tag-faces (limit)
6031 "Add the special tag faces."
6032 (when (and org-tag-faces org-tags-special-faces-re)
6033 (while (re-search-forward org-tags-special-faces-re limit t)
6034 (add-text-properties (match-beginning 1) (match-end 1)
6035 (list 'face (org-get-tag-face 1)
6036 'font-lock-fontified t))
6037 (backward-char 1))))
6039 (defun org-font-lock-add-priority-faces (limit)
6040 "Add the special priority faces."
6041 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6042 (add-text-properties
6043 (match-beginning 0) (match-end 0)
6044 (list 'face (or (org-face-from-face-or-color
6045 'priority 'org-special-keyword
6046 (cdr (assoc (char-after (match-beginning 1))
6047 org-priority-faces)))
6048 'org-special-keyword)
6049 'font-lock-fontified t))))
6051 (defun org-get-tag-face (kwd)
6052 "Get the right face for a TODO keyword KWD.
6053 If KWD is a number, get the corresponding match group."
6054 (if (numberp kwd) (setq kwd (match-string kwd)))
6055 (or (org-face-from-face-or-color
6056 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6057 'org-tag))
6059 (defun org-unfontify-region (beg end &optional maybe_loudly)
6060 "Remove fontification and activation overlays from links."
6061 (font-lock-default-unfontify-region beg end)
6062 (let* ((buffer-undo-list t)
6063 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6064 (inhibit-modification-hooks t)
6065 deactivate-mark buffer-file-name buffer-file-truename)
6066 (org-decompose-region beg end)
6067 (remove-text-properties beg end
6068 '(mouse-face t keymap t org-linked-text t
6069 invisible t intangible t
6070 org-no-flyspell t org-emphasis t))
6071 (org-remove-font-lock-display-properties beg end)))
6073 (defconst org-script-display '(((raise -0.3) (height 0.7))
6074 ((raise 0.3) (height 0.7))
6075 ((raise -0.5))
6076 ((raise 0.5)))
6077 "Display properties for showing superscripts and subscripts.")
6079 (defun org-remove-font-lock-display-properties (beg end)
6080 "Remove specific display properties that have been added by font lock.
6081 The will remove the raise properties that are used to show superscripts
6082 and subscripts."
6083 (let (next prop)
6084 (while (< beg end)
6085 (setq next (next-single-property-change beg 'display nil end)
6086 prop (get-text-property beg 'display))
6087 (if (member prop org-script-display)
6088 (put-text-property beg next 'display nil))
6089 (setq beg next))))
6091 (defun org-raise-scripts (limit)
6092 "Add raise properties to sub/superscripts."
6093 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6094 (if (re-search-forward
6095 (if (eq org-use-sub-superscripts t)
6096 org-match-substring-regexp
6097 org-match-substring-with-braces-regexp)
6098 limit t)
6099 (let* ((pos (point)) table-p comment-p
6100 (mpos (match-beginning 3))
6101 (emph-p (get-text-property mpos 'org-emphasis))
6102 (link-p (get-text-property mpos 'mouse-face))
6103 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6104 (goto-char (point-at-bol))
6105 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6106 comment-p (org-looking-at-p "[ \t]*#"))
6107 (goto-char pos)
6108 ;; FIXME: Should we go back one character here, for a_b^c
6109 ;; (goto-char (1- pos)) ;????????????????????
6110 (if (or comment-p emph-p link-p keyw-p)
6112 (put-text-property (match-beginning 3) (match-end 0)
6113 'display
6114 (if (equal (char-after (match-beginning 2)) ?^)
6115 (nth (if table-p 3 1) org-script-display)
6116 (nth (if table-p 2 0) org-script-display)))
6117 (add-text-properties (match-beginning 2) (match-end 2)
6118 (list 'invisible t
6119 'org-dwidth t 'org-dwidth-n 1))
6120 (if (and (eq (char-after (match-beginning 3)) ?{)
6121 (eq (char-before (match-end 3)) ?}))
6122 (progn
6123 (add-text-properties
6124 (match-beginning 3) (1+ (match-beginning 3))
6125 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6126 (add-text-properties
6127 (1- (match-end 3)) (match-end 3)
6128 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6129 t)))))
6131 ;;;; Visibility cycling, including org-goto and indirect buffer
6133 ;;; Cycling
6135 (defvar org-cycle-global-status nil)
6136 (make-variable-buffer-local 'org-cycle-global-status)
6137 (defvar org-cycle-subtree-status nil)
6138 (make-variable-buffer-local 'org-cycle-subtree-status)
6140 ;;;###autoload
6142 (defvar org-inlinetask-min-level)
6144 (defun org-cycle (&optional arg)
6145 "TAB-action and visibility cycling for Org-mode.
6147 This is the command invoked in Org-mode by the TAB key. Its main purpose
6148 is outline visibility cycling, but it also invokes other actions
6149 in special contexts.
6151 - When this function is called with a prefix argument, rotate the entire
6152 buffer through 3 states (global cycling)
6153 1. OVERVIEW: Show only top-level headlines.
6154 2. CONTENTS: Show all headlines of all levels, but no body text.
6155 3. SHOW ALL: Show everything.
6156 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6157 determined by the variable `org-startup-folded', and by any VISIBILITY
6158 properties in the buffer.
6159 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6160 including any drawers.
6162 - When inside a table, re-align the table and move to the next field.
6164 - When point is at the beginning of a headline, rotate the subtree started
6165 by this line through 3 different states (local cycling)
6166 1. FOLDED: Only the main headline is shown.
6167 2. CHILDREN: The main headline and the direct children are shown.
6168 From this state, you can move to one of the children
6169 and zoom in further.
6170 3. SUBTREE: Show the entire subtree, including body text.
6171 If there is no subtree, switch directly from CHILDREN to FOLDED.
6173 - When point is at the beginning of an empty headline and the variable
6174 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6175 of the headline by demoting and promoting it to likely levels. This
6176 speeds up creation document structure by pressing TAB once or several
6177 times right after creating a new headline.
6179 - When there is a numeric prefix, go up to a heading with level ARG, do
6180 a `show-subtree' and return to the previous cursor position. If ARG
6181 is negative, go up that many levels.
6183 - When point is not at the beginning of a headline, execute the global
6184 binding for TAB, which is re-indenting the line. See the option
6185 `org-cycle-emulate-tab' for details.
6187 - Special case: if point is at the beginning of the buffer and there is
6188 no headline in line 1, this function will act as if called with prefix arg
6189 (C-u TAB, same as S-TAB) also when called without prefix arg.
6190 But only if also the variable `org-cycle-global-at-bob' is t."
6191 (interactive "P")
6192 (org-load-modules-maybe)
6193 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6194 (and org-cycle-level-after-item/entry-creation
6195 (or (org-cycle-level)
6196 (org-cycle-item-indentation))))
6197 (let* ((limit-level
6198 (or org-cycle-max-level
6199 (and (boundp 'org-inlinetask-min-level)
6200 org-inlinetask-min-level
6201 (1- org-inlinetask-min-level))))
6202 (nstars (and limit-level
6203 (if org-odd-levels-only
6204 (and limit-level (1- (* limit-level 2)))
6205 limit-level)))
6206 (org-outline-regexp
6207 (if (not (derived-mode-p 'org-mode))
6208 outline-regexp
6209 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6210 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6211 (not (looking-at org-outline-regexp))))
6212 (org-cycle-hook
6213 (if bob-special
6214 (delq 'org-optimize-window-after-visibility-change
6215 (copy-sequence org-cycle-hook))
6216 org-cycle-hook))
6217 (pos (point)))
6219 (if (or bob-special (equal arg '(4)))
6220 ;; special case: use global cycling
6221 (setq arg t))
6223 (cond
6225 ((equal arg '(16))
6226 (setq last-command 'dummy)
6227 (org-set-startup-visibility)
6228 (message "Startup visibility, plus VISIBILITY properties"))
6230 ((equal arg '(64))
6231 (show-all)
6232 (message "Entire buffer visible, including drawers"))
6234 ;; Table: enter it or move to the next field.
6235 ((org-at-table-p 'any)
6236 (if (org-at-table.el-p)
6237 (message "Use C-c ' to edit table.el tables")
6238 (if arg (org-table-edit-field t)
6239 (org-table-justify-field-maybe)
6240 (call-interactively 'org-table-next-field))))
6242 ((run-hook-with-args-until-success
6243 'org-tab-after-check-for-table-hook))
6245 ;; Global cycling: delegate to `org-cycle-internal-global'.
6246 ((eq arg t) (org-cycle-internal-global))
6248 ;; Drawers: delegate to `org-flag-drawer'.
6249 ((and org-drawers org-drawer-regexp
6250 (save-excursion
6251 (beginning-of-line 1)
6252 (looking-at org-drawer-regexp)))
6253 (org-flag-drawer ; toggle block visibility
6254 (not (get-char-property (match-end 0) 'invisible))))
6256 ;; Show-subtree, ARG levels up from here.
6257 ((integerp arg)
6258 (save-excursion
6259 (org-back-to-heading)
6260 (outline-up-heading (if (< arg 0) (- arg)
6261 (- (funcall outline-level) arg)))
6262 (org-show-subtree)))
6264 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6265 ((and (featurep 'org-inlinetask)
6266 (org-inlinetask-at-task-p)
6267 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6268 (org-inlinetask-toggle-visibility))
6270 ((org-try-cdlatex-tab))
6272 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6273 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6274 (save-excursion (beginning-of-line 1)
6275 (looking-at org-outline-regexp)))
6276 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6277 (org-cycle-internal-local))
6279 ;; From there: TAB emulation and template completion.
6280 (buffer-read-only (org-back-to-heading))
6282 ((run-hook-with-args-until-success
6283 'org-tab-after-check-for-cycling-hook))
6285 ((org-try-structure-completion))
6287 ((run-hook-with-args-until-success
6288 'org-tab-before-tab-emulation-hook))
6290 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6291 (or (not (bolp))
6292 (not (looking-at org-outline-regexp))))
6293 (call-interactively (global-key-binding "\t")))
6295 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6296 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6297 (or (and (eq org-cycle-emulate-tab 'white)
6298 (= (match-end 0) (point-at-eol)))
6299 (and (eq org-cycle-emulate-tab 'whitestart)
6300 (>= (match-end 0) pos))))
6302 (eq org-cycle-emulate-tab t))
6303 (call-interactively (global-key-binding "\t")))
6305 (t (save-excursion
6306 (org-back-to-heading)
6307 (org-cycle)))))))
6309 (defun org-cycle-internal-global ()
6310 "Do the global cycling action."
6311 ;; Hack to avoid display of messages for .org attachments in Gnus
6312 (let ((ga (string-match "\\*fontification" (buffer-name))))
6313 (cond
6314 ((and (eq last-command this-command)
6315 (eq org-cycle-global-status 'overview))
6316 ;; We just created the overview - now do table of contents
6317 ;; This can be slow in very large buffers, so indicate action
6318 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6319 (unless ga (message "CONTENTS..."))
6320 (org-content)
6321 (unless ga (message "CONTENTS...done"))
6322 (setq org-cycle-global-status 'contents)
6323 (run-hook-with-args 'org-cycle-hook 'contents))
6325 ((and (eq last-command this-command)
6326 (eq org-cycle-global-status 'contents))
6327 ;; We just showed the table of contents - now show everything
6328 (run-hook-with-args 'org-pre-cycle-hook 'all)
6329 (show-all)
6330 (unless ga (message "SHOW ALL"))
6331 (setq org-cycle-global-status 'all)
6332 (run-hook-with-args 'org-cycle-hook 'all))
6335 ;; Default action: go to overview
6336 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6337 (org-overview)
6338 (unless ga (message "OVERVIEW"))
6339 (setq org-cycle-global-status 'overview)
6340 (run-hook-with-args 'org-cycle-hook 'overview)))))
6342 (defun org-cycle-internal-local ()
6343 "Do the local cycling action."
6344 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6345 ;; First, determine end of headline (EOH), end of subtree or item
6346 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6347 (save-excursion
6348 (if (org-at-item-p)
6349 (progn
6350 (beginning-of-line)
6351 (setq struct (org-list-struct))
6352 (setq eoh (point-at-eol))
6353 (setq eos (org-list-get-item-end-before-blank (point) struct))
6354 (setq has-children (org-list-has-child-p (point) struct)))
6355 (org-back-to-heading)
6356 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6357 (setq eos (save-excursion
6358 (org-end-of-subtree t)
6359 (unless (eobp)
6360 (skip-chars-forward " \t\n"))
6361 (if (eobp) (point) (1- (point)))))
6362 (setq has-children
6363 (or (save-excursion
6364 (let ((level (funcall outline-level)))
6365 (outline-next-heading)
6366 (and (org-at-heading-p t)
6367 (> (funcall outline-level) level))))
6368 (save-excursion
6369 (org-list-search-forward (org-item-beginning-re) eos t)))))
6370 ;; Determine end invisible part of buffer (EOL)
6371 (beginning-of-line 2)
6372 ;; XEmacs doesn't have `next-single-char-property-change'
6373 (if (featurep 'xemacs)
6374 (while (and (not (eobp)) ;; this is like `next-line'
6375 (get-char-property (1- (point)) 'invisible))
6376 (beginning-of-line 2))
6377 (while (and (not (eobp)) ;; this is like `next-line'
6378 (get-char-property (1- (point)) 'invisible))
6379 (goto-char (next-single-char-property-change (point) 'invisible))
6380 (and (eolp) (beginning-of-line 2))))
6381 (setq eol (point)))
6382 ;; Find out what to do next and set `this-command'
6383 (cond
6384 ((= eos eoh)
6385 ;; Nothing is hidden behind this heading
6386 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6387 (message "EMPTY ENTRY")
6388 (setq org-cycle-subtree-status nil)
6389 (save-excursion
6390 (goto-char eos)
6391 (outline-next-heading)
6392 (if (outline-invisible-p) (org-flag-heading nil))))
6393 ((and (or (>= eol eos)
6394 (not (string-match "\\S-" (buffer-substring eol eos))))
6395 (or has-children
6396 (not (setq children-skipped
6397 org-cycle-skip-children-state-if-no-children))))
6398 ;; Entire subtree is hidden in one line: children view
6399 (run-hook-with-args 'org-pre-cycle-hook 'children)
6400 (if (org-at-item-p)
6401 (org-list-set-item-visibility (point-at-bol) struct 'children)
6402 (org-show-entry)
6403 (org-with-limited-levels (show-children))
6404 ;; FIXME: This slows down the func way too much.
6405 ;; How keep drawers hidden in subtree anyway?
6406 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6407 ;; (org-cycle-hide-drawers 'subtree))
6409 ;; Fold every list in subtree to top-level items.
6410 (when (eq org-cycle-include-plain-lists 'integrate)
6411 (save-excursion
6412 (org-back-to-heading)
6413 (while (org-list-search-forward (org-item-beginning-re) eos t)
6414 (beginning-of-line 1)
6415 (let* ((struct (org-list-struct))
6416 (prevs (org-list-prevs-alist struct))
6417 (end (org-list-get-bottom-point struct)))
6418 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6419 (org-list-get-all-items (point) struct prevs))
6420 (goto-char end))))))
6421 (message "CHILDREN")
6422 (save-excursion
6423 (goto-char eos)
6424 (outline-next-heading)
6425 (if (outline-invisible-p) (org-flag-heading nil)))
6426 (setq org-cycle-subtree-status 'children)
6427 (run-hook-with-args 'org-cycle-hook 'children))
6428 ((or children-skipped
6429 (and (eq last-command this-command)
6430 (eq org-cycle-subtree-status 'children)))
6431 ;; We just showed the children, or no children are there,
6432 ;; now show everything.
6433 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6434 (outline-flag-region eoh eos nil)
6435 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6436 (setq org-cycle-subtree-status 'subtree)
6437 (run-hook-with-args 'org-cycle-hook 'subtree))
6439 ;; Default action: hide the subtree.
6440 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6441 (outline-flag-region eoh eos t)
6442 (message "FOLDED")
6443 (setq org-cycle-subtree-status 'folded)
6444 (run-hook-with-args 'org-cycle-hook 'folded)))))
6446 ;;;###autoload
6447 (defun org-global-cycle (&optional arg)
6448 "Cycle the global visibility. For details see `org-cycle'.
6449 With \\[universal-argument] prefix arg, switch to startup visibility.
6450 With a numeric prefix, show all headlines up to that level."
6451 (interactive "P")
6452 (let ((org-cycle-include-plain-lists
6453 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6454 (cond
6455 ((integerp arg)
6456 (show-all)
6457 (hide-sublevels arg)
6458 (setq org-cycle-global-status 'contents))
6459 ((equal arg '(4))
6460 (org-set-startup-visibility)
6461 (message "Startup visibility, plus VISIBILITY properties."))
6463 (org-cycle '(4))))))
6465 (defun org-set-startup-visibility ()
6466 "Set the visibility required by startup options and properties."
6467 (cond
6468 ((eq org-startup-folded t)
6469 (org-cycle '(4)))
6470 ((eq org-startup-folded 'content)
6471 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6472 (org-cycle '(4)) (org-cycle '(4)))))
6473 (unless (eq org-startup-folded 'showeverything)
6474 (if org-hide-block-startup (org-hide-block-all))
6475 (org-set-visibility-according-to-property 'no-cleanup)
6476 (org-cycle-hide-archived-subtrees 'all)
6477 (org-cycle-hide-drawers 'all)
6478 (org-cycle-show-empty-lines t)))
6480 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6481 "Switch subtree visibilities according to :VISIBILITY: property."
6482 (interactive)
6483 (let (org-show-entry-below state)
6484 (save-excursion
6485 (goto-char (point-min))
6486 (while (re-search-forward
6487 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6488 nil t)
6489 (setq state (match-string 1))
6490 (save-excursion
6491 (org-back-to-heading t)
6492 (hide-subtree)
6493 (org-reveal)
6494 (cond
6495 ((equal state '("fold" "folded"))
6496 (hide-subtree))
6497 ((equal state "children")
6498 (org-show-hidden-entry)
6499 (show-children))
6500 ((equal state "content")
6501 (save-excursion
6502 (save-restriction
6503 (org-narrow-to-subtree)
6504 (org-content))))
6505 ((member state '("all" "showall"))
6506 (show-subtree)))))
6507 (unless no-cleanup
6508 (org-cycle-hide-archived-subtrees 'all)
6509 (org-cycle-hide-drawers 'all)
6510 (org-cycle-show-empty-lines 'all)))))
6512 ;; This function uses outline-regexp instead of the more fundamental
6513 ;; org-outline-regexp so that org-cycle-global works outside of Org
6514 ;; buffers, where outline-regexp is needed.
6515 (defun org-overview ()
6516 "Switch to overview mode, showing only top-level headlines.
6517 Really, this shows all headlines with level equal or greater than the level
6518 of the first headline in the buffer. This is important, because if the
6519 first headline is not level one, then (hide-sublevels 1) gives confusing
6520 results."
6521 (interactive)
6522 (let ((level (save-excursion
6523 (goto-char (point-min))
6524 (if (re-search-forward (concat "^" outline-regexp) nil t)
6525 (progn
6526 (goto-char (match-beginning 0))
6527 (funcall outline-level))))))
6528 (and level (hide-sublevels level))))
6530 (defun org-content (&optional arg)
6531 "Show all headlines in the buffer, like a table of contents.
6532 With numerical argument N, show content up to level N."
6533 (interactive "P")
6534 (save-excursion
6535 ;; Visit all headings and show their offspring
6536 (and (integerp arg) (org-overview))
6537 (goto-char (point-max))
6538 (catch 'exit
6539 (while (and (progn (condition-case nil
6540 (outline-previous-visible-heading 1)
6541 (error (goto-char (point-min))))
6543 (looking-at org-outline-regexp))
6544 (if (integerp arg)
6545 (show-children (1- arg))
6546 (show-branches))
6547 (if (bobp) (throw 'exit nil))))))
6550 (defun org-optimize-window-after-visibility-change (state)
6551 "Adjust the window after a change in outline visibility.
6552 This function is the default value of the hook `org-cycle-hook'."
6553 (when (get-buffer-window (current-buffer))
6554 (cond
6555 ((eq state 'content) nil)
6556 ((eq state 'all) nil)
6557 ((eq state 'folded) nil)
6558 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6559 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6561 (defun org-remove-empty-overlays-at (pos)
6562 "Remove outline overlays that do not contain non-white stuff."
6563 (mapc
6564 (lambda (o)
6565 (and (eq 'outline (overlay-get o 'invisible))
6566 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6567 (overlay-end o))))
6568 (delete-overlay o)))
6569 (overlays-at pos)))
6571 (defun org-clean-visibility-after-subtree-move ()
6572 "Fix visibility issues after moving a subtree."
6573 ;; First, find a reasonable region to look at:
6574 ;; Start two siblings above, end three below
6575 (let* ((beg (save-excursion
6576 (and (org-get-last-sibling)
6577 (org-get-last-sibling))
6578 (point)))
6579 (end (save-excursion
6580 (and (org-get-next-sibling)
6581 (org-get-next-sibling)
6582 (org-get-next-sibling))
6583 (if (org-at-heading-p)
6584 (point-at-eol)
6585 (point))))
6586 (level (looking-at "\\*+"))
6587 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6588 (save-excursion
6589 (save-restriction
6590 (narrow-to-region beg end)
6591 (when re
6592 ;; Properly fold already folded siblings
6593 (goto-char (point-min))
6594 (while (re-search-forward re nil t)
6595 (if (and (not (outline-invisible-p))
6596 (save-excursion
6597 (goto-char (point-at-eol)) (outline-invisible-p)))
6598 (hide-entry))))
6599 (org-cycle-show-empty-lines 'overview)
6600 (org-cycle-hide-drawers 'overview)))))
6602 (defun org-cycle-show-empty-lines (state)
6603 "Show empty lines above all visible headlines.
6604 The region to be covered depends on STATE when called through
6605 `org-cycle-hook'. Lisp program can use t for STATE to get the
6606 entire buffer covered. Note that an empty line is only shown if there
6607 are at least `org-cycle-separator-lines' empty lines before the headline."
6608 (when (not (= org-cycle-separator-lines 0))
6609 (save-excursion
6610 (let* ((n (abs org-cycle-separator-lines))
6611 (re (cond
6612 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6613 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6614 (t (let ((ns (number-to-string (- n 2))))
6615 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6616 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6617 beg end b e)
6618 (cond
6619 ((memq state '(overview contents t))
6620 (setq beg (point-min) end (point-max)))
6621 ((memq state '(children folded))
6622 (setq beg (point) end (progn (org-end-of-subtree t t)
6623 (beginning-of-line 2)
6624 (point)))))
6625 (when beg
6626 (goto-char beg)
6627 (while (re-search-forward re end t)
6628 (unless (get-char-property (match-end 1) 'invisible)
6629 (setq e (match-end 1))
6630 (if (< org-cycle-separator-lines 0)
6631 (setq b (save-excursion
6632 (goto-char (match-beginning 0))
6633 (org-back-over-empty-lines)
6634 (if (save-excursion
6635 (goto-char (max (point-min) (1- (point))))
6636 (org-at-heading-p))
6637 (1- (point))
6638 (point))))
6639 (setq b (match-beginning 1)))
6640 (outline-flag-region b e nil)))))))
6641 ;; Never hide empty lines at the end of the file.
6642 (save-excursion
6643 (goto-char (point-max))
6644 (outline-previous-heading)
6645 (outline-end-of-heading)
6646 (if (and (looking-at "[ \t\n]+")
6647 (= (match-end 0) (point-max)))
6648 (outline-flag-region (point) (match-end 0) nil))))
6650 (defun org-show-empty-lines-in-parent ()
6651 "Move to the parent and re-show empty lines before visible headlines."
6652 (save-excursion
6653 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6654 (org-cycle-show-empty-lines context))))
6656 (defun org-files-list ()
6657 "Return `org-agenda-files' list, plus all open org-mode files.
6658 This is useful for operations that need to scan all of a user's
6659 open and agenda-wise Org files."
6660 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6661 (dolist (buf (buffer-list))
6662 (with-current-buffer buf
6663 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6664 (let ((file (expand-file-name (buffer-file-name))))
6665 (unless (member file files)
6666 (push file files))))))
6667 files))
6669 (defsubst org-entry-beginning-position ()
6670 "Return the beginning position of the current entry."
6671 (save-excursion (outline-back-to-heading t) (point)))
6673 (defsubst org-entry-end-position ()
6674 "Return the end position of the current entry."
6675 (save-excursion (outline-next-heading) (point)))
6677 (defun org-cycle-hide-drawers (state)
6678 "Re-hide all drawers after a visibility state change."
6679 (when (and (derived-mode-p 'org-mode)
6680 (not (memq state '(overview folded contents))))
6681 (save-excursion
6682 (let* ((globalp (memq state '(contents all)))
6683 (beg (if globalp (point-min) (point)))
6684 (end (if globalp (point-max)
6685 (if (eq state 'children)
6686 (save-excursion (outline-next-heading) (point))
6687 (org-end-of-subtree t)))))
6688 (goto-char beg)
6689 (while (re-search-forward org-drawer-regexp end t)
6690 (org-flag-drawer t))))))
6692 (defun org-flag-drawer (flag)
6693 (save-excursion
6694 (beginning-of-line 1)
6695 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6696 (let ((b (match-end 0)))
6697 (if (re-search-forward
6698 "^[ \t]*:END:"
6699 (save-excursion (outline-next-heading) (point)) t)
6700 (outline-flag-region b (point-at-eol) flag)
6701 (error ":END: line missing at position %s" b))))))
6703 (defun org-subtree-end-visible-p ()
6704 "Is the end of the current subtree visible?"
6705 (pos-visible-in-window-p
6706 (save-excursion (org-end-of-subtree t) (point))))
6708 (defun org-first-headline-recenter (&optional N)
6709 "Move cursor to the first headline and recenter the headline.
6710 Optional argument N means put the headline into the Nth line of the window."
6711 (goto-char (point-min))
6712 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6713 (beginning-of-line)
6714 (recenter (prefix-numeric-value N))))
6716 ;;; Saving and restoring visibility
6718 (defun org-outline-overlay-data (&optional use-markers)
6719 "Return a list of the locations of all outline overlays.
6720 These are overlays with the `invisible' property value `outline'.
6721 The return value is a list of cons cells, with start and stop
6722 positions for each overlay.
6723 If USE-MARKERS is set, return the positions as markers."
6724 (let (beg end)
6725 (save-excursion
6726 (save-restriction
6727 (widen)
6728 (delq nil
6729 (mapcar (lambda (o)
6730 (when (eq (overlay-get o 'invisible) 'outline)
6731 (setq beg (overlay-start o)
6732 end (overlay-end o))
6733 (and beg end (> end beg)
6734 (if use-markers
6735 (cons (move-marker (make-marker) beg)
6736 (move-marker (make-marker) end))
6737 (cons beg end)))))
6738 (overlays-in (point-min) (point-max))))))))
6740 (defun org-set-outline-overlay-data (data)
6741 "Create visibility overlays for all positions in DATA.
6742 DATA should have been made by `org-outline-overlay-data'."
6743 (let (o)
6744 (save-excursion
6745 (save-restriction
6746 (widen)
6747 (show-all)
6748 (mapc (lambda (c)
6749 (outline-flag-region (car c) (cdr c) t))
6750 data)))))
6752 ;;; Folding of blocks
6754 (defvar org-hide-block-overlays nil
6755 "Overlays hiding blocks.")
6756 (make-variable-buffer-local 'org-hide-block-overlays)
6758 (defun org-block-map (function &optional start end)
6759 "Call FUNCTION at the head of all source blocks in the current buffer.
6760 Optional arguments START and END can be used to limit the range."
6761 (let ((start (or start (point-min)))
6762 (end (or end (point-max))))
6763 (save-excursion
6764 (goto-char start)
6765 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6766 (save-excursion
6767 (save-match-data
6768 (goto-char (match-beginning 0))
6769 (funcall function)))))))
6771 (defun org-hide-block-toggle-all ()
6772 "Toggle the visibility of all blocks in the current buffer."
6773 (org-block-map #'org-hide-block-toggle))
6775 (defun org-hide-block-all ()
6776 "Fold all blocks in the current buffer."
6777 (interactive)
6778 (org-show-block-all)
6779 (org-block-map #'org-hide-block-toggle-maybe))
6781 (defun org-show-block-all ()
6782 "Unfold all blocks in the current buffer."
6783 (interactive)
6784 (mapc 'delete-overlay org-hide-block-overlays)
6785 (setq org-hide-block-overlays nil))
6787 (defun org-hide-block-toggle-maybe ()
6788 "Toggle visibility of block at point."
6789 (interactive)
6790 (let ((case-fold-search t))
6791 (if (save-excursion
6792 (beginning-of-line 1)
6793 (looking-at org-block-regexp))
6794 (progn (org-hide-block-toggle)
6795 t) ;; to signal that we took action
6796 nil))) ;; to signal that we did not
6798 (defun org-hide-block-toggle (&optional force)
6799 "Toggle the visibility of the current block."
6800 (interactive)
6801 (save-excursion
6802 (beginning-of-line)
6803 (if (re-search-forward org-block-regexp nil t)
6804 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6805 (end (match-end 0)) ;; end of entire body
6807 (if (memq t (mapcar (lambda (overlay)
6808 (eq (overlay-get overlay 'invisible)
6809 'org-hide-block))
6810 (overlays-at start)))
6811 (if (or (not force) (eq force 'off))
6812 (mapc (lambda (ov)
6813 (when (member ov org-hide-block-overlays)
6814 (setq org-hide-block-overlays
6815 (delq ov org-hide-block-overlays)))
6816 (when (eq (overlay-get ov 'invisible)
6817 'org-hide-block)
6818 (delete-overlay ov)))
6819 (overlays-at start)))
6820 (setq ov (make-overlay start end))
6821 (overlay-put ov 'invisible 'org-hide-block)
6822 ;; make the block accessible to isearch
6823 (overlay-put
6824 ov 'isearch-open-invisible
6825 (lambda (ov)
6826 (when (member ov org-hide-block-overlays)
6827 (setq org-hide-block-overlays
6828 (delq ov org-hide-block-overlays)))
6829 (when (eq (overlay-get ov 'invisible)
6830 'org-hide-block)
6831 (delete-overlay ov))))
6832 (push ov org-hide-block-overlays)))
6833 (error "Not looking at a source block"))))
6835 ;; org-tab-after-check-for-cycling-hook
6836 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6837 ;; Remove overlays when changing major mode
6838 (add-hook 'org-mode-hook
6839 (lambda () (org-add-hook 'change-major-mode-hook
6840 'org-show-block-all 'append 'local)))
6842 ;;; Org-goto
6844 (defvar org-goto-window-configuration nil)
6845 (defvar org-goto-marker nil)
6846 (defvar org-goto-map
6847 (let ((map (make-sparse-keymap)))
6848 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6849 (while (setq cmd (pop cmds))
6850 (substitute-key-definition cmd cmd map global-map)))
6851 (suppress-keymap map)
6852 (org-defkey map "\C-m" 'org-goto-ret)
6853 (org-defkey map [(return)] 'org-goto-ret)
6854 (org-defkey map [(left)] 'org-goto-left)
6855 (org-defkey map [(right)] 'org-goto-right)
6856 (org-defkey map [(control ?g)] 'org-goto-quit)
6857 (org-defkey map "\C-i" 'org-cycle)
6858 (org-defkey map [(tab)] 'org-cycle)
6859 (org-defkey map [(down)] 'outline-next-visible-heading)
6860 (org-defkey map [(up)] 'outline-previous-visible-heading)
6861 (if org-goto-auto-isearch
6862 (if (fboundp 'define-key-after)
6863 (define-key-after map [t] 'org-goto-local-auto-isearch)
6864 nil)
6865 (org-defkey map "q" 'org-goto-quit)
6866 (org-defkey map "n" 'outline-next-visible-heading)
6867 (org-defkey map "p" 'outline-previous-visible-heading)
6868 (org-defkey map "f" 'outline-forward-same-level)
6869 (org-defkey map "b" 'outline-backward-same-level)
6870 (org-defkey map "u" 'outline-up-heading))
6871 (org-defkey map "/" 'org-occur)
6872 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6873 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6874 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6875 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6876 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6877 map))
6879 (defconst org-goto-help
6880 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6881 RET=jump to location [Q]uit and return to previous location
6882 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6884 (defvar org-goto-start-pos) ; dynamically scoped parameter
6886 ;; FIXME: Docstring does not mention both interfaces
6887 (defun org-goto (&optional alternative-interface)
6888 "Look up a different location in the current file, keeping current visibility.
6890 When you want look-up or go to a different location in a
6891 document, the fastest way is often to fold the entire buffer and
6892 then dive into the tree. This method has the disadvantage, that
6893 the previous location will be folded, which may not be what you
6894 want.
6896 This command works around this by showing a copy of the current
6897 buffer in an indirect buffer, in overview mode. You can dive
6898 into the tree in that copy, use org-occur and incremental search
6899 to find a location. When pressing RET or `Q', the command
6900 returns to the original buffer in which the visibility is still
6901 unchanged. After RET it will also jump to the location selected
6902 in the indirect buffer and expose the headline hierarchy above.
6904 With a prefix argument, use the alternative interface: e.g. if
6905 `org-goto-interface' is 'outline use 'outline-path-completion."
6906 (interactive "P")
6907 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6908 (org-refile-use-outline-path t)
6909 (org-refile-target-verify-function nil)
6910 (interface
6911 (if (not alternative-interface)
6912 org-goto-interface
6913 (if (eq org-goto-interface 'outline)
6914 'outline-path-completion
6915 'outline)))
6916 (org-goto-start-pos (point))
6917 (selected-point
6918 (if (eq interface 'outline)
6919 (car (org-get-location (current-buffer) org-goto-help))
6920 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6921 (org-refile-check-position pa)
6922 (nth 3 pa)))))
6923 (if selected-point
6924 (progn
6925 (org-mark-ring-push org-goto-start-pos)
6926 (goto-char selected-point)
6927 (if (or (outline-invisible-p) (org-invisible-p2))
6928 (org-show-context 'org-goto)))
6929 (message "Quit"))))
6931 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6932 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6933 (defvar org-goto-local-auto-isearch-map) ; defined below
6935 (defun org-get-location (buf help)
6936 "Let the user select a location in the Org-mode buffer BUF.
6937 This function uses a recursive edit. It returns the selected position
6938 or nil."
6939 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6940 (isearch-hide-immediately nil)
6941 (isearch-search-fun-function
6942 (lambda () 'org-goto-local-search-headings))
6943 (org-goto-selected-point org-goto-exit-command)
6944 (pop-up-frames nil)
6945 (special-display-buffer-names nil)
6946 (special-display-regexps nil)
6947 (special-display-function nil))
6948 (save-excursion
6949 (save-window-excursion
6950 (delete-other-windows)
6951 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6952 (org-pop-to-buffer-same-window
6953 (condition-case nil
6954 (make-indirect-buffer (current-buffer) "*org-goto*")
6955 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6956 (with-output-to-temp-buffer "*Help*"
6957 (princ help))
6958 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6959 (setq buffer-read-only nil)
6960 (let ((org-startup-truncated t)
6961 (org-startup-folded nil)
6962 (org-startup-align-all-tables nil))
6963 (org-mode)
6964 (org-overview))
6965 (setq buffer-read-only t)
6966 (if (and (boundp 'org-goto-start-pos)
6967 (integer-or-marker-p org-goto-start-pos))
6968 (let ((org-show-hierarchy-above t)
6969 (org-show-siblings t)
6970 (org-show-following-heading t))
6971 (goto-char org-goto-start-pos)
6972 (and (outline-invisible-p) (org-show-context)))
6973 (goto-char (point-min)))
6974 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6975 (message "Select location and press RET")
6976 (use-local-map org-goto-map)
6977 (recursive-edit)
6979 (kill-buffer "*org-goto*")
6980 (cons org-goto-selected-point org-goto-exit-command)))
6982 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6983 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6984 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6985 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6987 (defun org-goto-local-search-headings (string bound noerror)
6988 "Search and make sure that any matches are in headlines."
6989 (catch 'return
6990 (while (if isearch-forward
6991 (search-forward string bound noerror)
6992 (search-backward string bound noerror))
6993 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6994 (and (member :headline context)
6995 (not (member :tags context))))
6996 (throw 'return (point))))))
6998 (defun org-goto-local-auto-isearch ()
6999 "Start isearch."
7000 (interactive)
7001 (goto-char (point-min))
7002 (let ((keys (this-command-keys)))
7003 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7004 (isearch-mode t)
7005 (isearch-process-search-char (string-to-char keys)))))
7007 (defun org-goto-ret (&optional arg)
7008 "Finish `org-goto' by going to the new location."
7009 (interactive "P")
7010 (setq org-goto-selected-point (point)
7011 org-goto-exit-command 'return)
7012 (throw 'exit nil))
7014 (defun org-goto-left ()
7015 "Finish `org-goto' by going to the new location."
7016 (interactive)
7017 (if (org-at-heading-p)
7018 (progn
7019 (beginning-of-line 1)
7020 (setq org-goto-selected-point (point)
7021 org-goto-exit-command 'left)
7022 (throw 'exit nil))
7023 (error "Not on a heading")))
7025 (defun org-goto-right ()
7026 "Finish `org-goto' by going to the new location."
7027 (interactive)
7028 (if (org-at-heading-p)
7029 (progn
7030 (setq org-goto-selected-point (point)
7031 org-goto-exit-command 'right)
7032 (throw 'exit nil))
7033 (error "Not on a heading")))
7035 (defun org-goto-quit ()
7036 "Finish `org-goto' without cursor motion."
7037 (interactive)
7038 (setq org-goto-selected-point nil)
7039 (setq org-goto-exit-command 'quit)
7040 (throw 'exit nil))
7042 ;;; Indirect buffer display of subtrees
7044 (defvar org-indirect-dedicated-frame nil
7045 "This is the frame being used for indirect tree display.")
7046 (defvar org-last-indirect-buffer nil)
7048 (defun org-tree-to-indirect-buffer (&optional arg)
7049 "Create indirect buffer and narrow it to current subtree.
7050 With numerical prefix ARG, go up to this level and then take that tree.
7051 If ARG is negative, go up that many levels.
7052 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7053 indirect buffer previously made with this command, to avoid proliferation of
7054 indirect buffers. However, when you call the command with a \
7055 \\[universal-argument] prefix, or
7056 when `org-indirect-buffer-display' is `new-frame', the last buffer
7057 is kept so that you can work with several indirect buffers at the same time.
7058 If `org-indirect-buffer-display' is `dedicated-frame', the \
7059 \\[universal-argument] prefix also
7060 requests that a new frame be made for the new buffer, so that the dedicated
7061 frame is not changed."
7062 (interactive "P")
7063 (let ((cbuf (current-buffer))
7064 (cwin (selected-window))
7065 (pos (point))
7066 beg end level heading ibuf)
7067 (save-excursion
7068 (org-back-to-heading t)
7069 (when (numberp arg)
7070 (setq level (org-outline-level))
7071 (if (< arg 0) (setq arg (+ level arg)))
7072 (while (> (setq level (org-outline-level)) arg)
7073 (outline-up-heading 1 t)))
7074 (setq beg (point)
7075 heading (org-get-heading))
7076 (org-end-of-subtree t t)
7077 (if (org-at-heading-p) (backward-char 1))
7078 (setq end (point)))
7079 (if (and (buffer-live-p org-last-indirect-buffer)
7080 (not (eq org-indirect-buffer-display 'new-frame))
7081 (not arg))
7082 (kill-buffer org-last-indirect-buffer))
7083 (setq ibuf (org-get-indirect-buffer cbuf)
7084 org-last-indirect-buffer ibuf)
7085 (cond
7086 ((or (eq org-indirect-buffer-display 'new-frame)
7087 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7088 (select-frame (make-frame))
7089 (delete-other-windows)
7090 (org-pop-to-buffer-same-window ibuf)
7091 (org-set-frame-title heading))
7092 ((eq org-indirect-buffer-display 'dedicated-frame)
7093 (raise-frame
7094 (select-frame (or (and org-indirect-dedicated-frame
7095 (frame-live-p org-indirect-dedicated-frame)
7096 org-indirect-dedicated-frame)
7097 (setq org-indirect-dedicated-frame (make-frame)))))
7098 (delete-other-windows)
7099 (org-pop-to-buffer-same-window ibuf)
7100 (org-set-frame-title (concat "Indirect: " heading)))
7101 ((eq org-indirect-buffer-display 'current-window)
7102 (org-pop-to-buffer-same-window ibuf))
7103 ((eq org-indirect-buffer-display 'other-window)
7104 (pop-to-buffer ibuf))
7105 (t (error "Invalid value")))
7106 (if (featurep 'xemacs)
7107 (save-excursion (org-mode) (turn-on-font-lock)))
7108 (narrow-to-region beg end)
7109 (show-all)
7110 (goto-char pos)
7111 (run-hook-with-args 'org-cycle-hook 'all)
7112 (and (window-live-p cwin) (select-window cwin))))
7114 (defun org-get-indirect-buffer (&optional buffer)
7115 (setq buffer (or buffer (current-buffer)))
7116 (let ((n 1) (base (buffer-name buffer)) bname)
7117 (while (buffer-live-p
7118 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7119 (setq n (1+ n)))
7120 (condition-case nil
7121 (make-indirect-buffer buffer bname 'clone)
7122 (error (make-indirect-buffer buffer bname)))))
7124 (defun org-set-frame-title (title)
7125 "Set the title of the current frame to the string TITLE."
7126 ;; FIXME: how to name a single frame in XEmacs???
7127 (unless (featurep 'xemacs)
7128 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7130 ;;;; Structure editing
7132 ;;; Inserting headlines
7134 (defun org-previous-line-empty-p ()
7135 (save-excursion
7136 (and (not (bobp))
7137 (or (beginning-of-line 0) t)
7138 (save-match-data
7139 (looking-at "[ \t]*$")))))
7141 (defun org-insert-heading (&optional force-heading invisible-ok)
7142 "Insert a new heading or item with same depth at point.
7143 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7144 If point is at the beginning of a headline, insert a sibling before the
7145 current headline. If point is not at the beginning, split the line,
7146 create the new headline with the text in the current line after point
7147 \(but see also the variable `org-M-RET-may-split-line').
7149 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7150 This is important for non-interactive uses of the command."
7151 (interactive "P")
7152 (if (or (= (buffer-size) 0)
7153 (and (not (save-excursion
7154 (and (ignore-errors (org-back-to-heading invisible-ok))
7155 (org-at-heading-p))))
7156 (or force-heading (not (org-in-item-p)))))
7157 (progn
7158 (insert "\n* ")
7159 (run-hooks 'org-insert-heading-hook))
7160 (when (or force-heading (not (org-insert-item)))
7161 (let* ((empty-line-p nil)
7162 (level nil)
7163 (on-heading (org-at-heading-p))
7164 (head (save-excursion
7165 (condition-case nil
7166 (progn
7167 (org-back-to-heading invisible-ok)
7168 (when (and (not on-heading)
7169 (featurep 'org-inlinetask)
7170 (integerp org-inlinetask-min-level)
7171 (>= (length (match-string 0))
7172 org-inlinetask-min-level))
7173 ;; Find a heading level before the inline task
7174 (while (and (setq level (org-up-heading-safe))
7175 (>= level org-inlinetask-min-level)))
7176 (if (org-at-heading-p)
7177 (org-back-to-heading invisible-ok)
7178 (error "This should not happen")))
7179 (setq empty-line-p (org-previous-line-empty-p))
7180 (match-string 0))
7181 (error "*"))))
7182 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7183 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7184 pos hide-previous previous-pos)
7185 (cond
7186 ((and (org-at-heading-p) (bolp)
7187 (or (bobp)
7188 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7189 ;; insert before the current line
7190 (open-line (if blank 2 1)))
7191 ((and (bolp)
7192 (not org-insert-heading-respect-content)
7193 (or (bobp)
7194 (save-excursion
7195 (backward-char 1) (not (outline-invisible-p)))))
7196 ;; insert right here
7197 nil)
7199 ;; somewhere in the line
7200 (save-excursion
7201 (setq previous-pos (point-at-bol))
7202 (end-of-line)
7203 (setq hide-previous (outline-invisible-p)))
7204 (and org-insert-heading-respect-content (org-show-subtree))
7205 (let ((split
7206 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7207 (save-excursion
7208 (let ((p (point)))
7209 (goto-char (point-at-bol))
7210 (and (looking-at org-complex-heading-regexp)
7211 (match-beginning 4)
7212 (> p (match-beginning 4)))))))
7213 tags pos)
7214 (cond
7215 (org-insert-heading-respect-content
7216 (org-end-of-subtree nil t)
7217 (when (featurep 'org-inlinetask)
7218 (while (and (not (eobp))
7219 (looking-at "\\(\\*+\\)[ \t]+")
7220 (>= (length (match-string 1))
7221 org-inlinetask-min-level))
7222 (org-end-of-subtree nil t)))
7223 (or (bolp) (newline))
7224 (or (org-previous-line-empty-p)
7225 (and blank (newline)))
7226 (open-line 1))
7227 ((org-at-heading-p)
7228 (when hide-previous
7229 (show-children)
7230 (org-show-entry))
7231 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7232 (setq tags (and (match-end 2) (match-string 2)))
7233 (and (match-end 1)
7234 (delete-region (match-beginning 1) (match-end 1)))
7235 (setq pos (point-at-bol))
7236 (or split (end-of-line 1))
7237 (delete-horizontal-space)
7238 (if (string-match "\\`\\*+\\'"
7239 (buffer-substring (point-at-bol) (point)))
7240 (insert " "))
7241 (newline (if blank 2 1))
7242 (when tags
7243 (save-excursion
7244 (goto-char pos)
7245 (end-of-line 1)
7246 (insert " " tags)
7247 (org-set-tags nil 'align))))
7249 (or split (end-of-line 1))
7250 (newline (if blank 2 1)))))))
7251 (insert head) (just-one-space)
7252 (setq pos (point))
7253 (end-of-line 1)
7254 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7255 (when (and org-insert-heading-respect-content hide-previous)
7256 (save-excursion
7257 (goto-char previous-pos)
7258 (hide-subtree)))
7259 (run-hooks 'org-insert-heading-hook)))))
7261 (defun org-get-heading (&optional no-tags no-todo)
7262 "Return the heading of the current entry, without the stars.
7263 When NO-TAGS is non-nil, don't include tags.
7264 When NO-TODO is non-nil, don't include TODO keywords."
7265 (save-excursion
7266 (org-back-to-heading t)
7267 (cond
7268 ((and no-tags no-todo)
7269 (looking-at org-complex-heading-regexp)
7270 (match-string 4))
7271 (no-tags
7272 (looking-at (concat org-outline-regexp
7273 "\\(.*?\\)"
7274 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7275 (match-string 1))
7276 (no-todo
7277 (looking-at org-todo-line-regexp)
7278 (match-string 3))
7279 (t (looking-at org-heading-regexp)
7280 (match-string 2)))))
7282 (defun org-heading-components ()
7283 "Return the components of the current heading.
7284 This is a list with the following elements:
7285 - the level as an integer
7286 - the reduced level, different if `org-odd-levels-only' is set.
7287 - the TODO keyword, or nil
7288 - the priority character, like ?A, or nil if no priority is given
7289 - the headline text itself, or the tags string if no headline text
7290 - the tags string, or nil."
7291 (save-excursion
7292 (org-back-to-heading t)
7293 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7294 (list (length (match-string 1))
7295 (org-reduced-level (length (match-string 1)))
7296 (org-match-string-no-properties 2)
7297 (and (match-end 3) (aref (match-string 3) 2))
7298 (org-match-string-no-properties 4)
7299 (org-match-string-no-properties 5)))))
7301 (defun org-get-entry ()
7302 "Get the entry text, after heading, entire subtree."
7303 (save-excursion
7304 (org-back-to-heading t)
7305 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7307 (defun org-insert-heading-after-current ()
7308 "Insert a new heading with same level as current, after current subtree."
7309 (interactive)
7310 (org-back-to-heading)
7311 (org-insert-heading)
7312 (org-move-subtree-down)
7313 (end-of-line 1))
7315 (defun org-insert-heading-respect-content ()
7316 (interactive)
7317 (let ((org-insert-heading-respect-content t))
7318 (org-insert-heading t)))
7320 (defun org-insert-todo-heading-respect-content (&optional force-state)
7321 (interactive "P")
7322 (let ((org-insert-heading-respect-content t))
7323 (org-insert-todo-heading force-state t)))
7325 (defun org-insert-todo-heading (arg &optional force-heading)
7326 "Insert a new heading with the same level and TODO state as current heading.
7327 If the heading has no TODO state, or if the state is DONE, use the first
7328 state (TODO by default). Also with prefix arg, force first state."
7329 (interactive "P")
7330 (when (or force-heading (not (org-insert-item 'checkbox)))
7331 (org-insert-heading force-heading)
7332 (save-excursion
7333 (org-back-to-heading)
7334 (outline-previous-heading)
7335 (looking-at org-todo-line-regexp))
7336 (let*
7337 ((new-mark-x
7338 (if (or arg
7339 (not (match-beginning 2))
7340 (member (match-string 2) org-done-keywords))
7341 (car org-todo-keywords-1)
7342 (match-string 2)))
7343 (new-mark
7345 (run-hook-with-args-until-success
7346 'org-todo-get-default-hook new-mark-x nil)
7347 new-mark-x)))
7348 (beginning-of-line 1)
7349 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7350 (if org-treat-insert-todo-heading-as-state-change
7351 (org-todo new-mark)
7352 (insert new-mark " "))))
7353 (when org-provide-todo-statistics
7354 (org-update-parent-todo-statistics))))
7356 (defun org-insert-subheading (arg)
7357 "Insert a new subheading and demote it.
7358 Works for outline headings and for plain lists alike."
7359 (interactive "P")
7360 (org-insert-heading arg)
7361 (cond
7362 ((org-at-heading-p) (org-do-demote))
7363 ((org-at-item-p) (org-indent-item))))
7365 (defun org-insert-todo-subheading (arg)
7366 "Insert a new subheading with TODO keyword or checkbox and demote it.
7367 Works for outline headings and for plain lists alike."
7368 (interactive "P")
7369 (org-insert-todo-heading arg)
7370 (cond
7371 ((org-at-heading-p) (org-do-demote))
7372 ((org-at-item-p) (org-indent-item))))
7374 ;;; Promotion and Demotion
7376 (defvar org-after-demote-entry-hook nil
7377 "Hook run after an entry has been demoted.
7378 The cursor will be at the beginning of the entry.
7379 When a subtree is being demoted, the hook will be called for each node.")
7381 (defvar org-after-promote-entry-hook nil
7382 "Hook run after an entry has been promoted.
7383 The cursor will be at the beginning of the entry.
7384 When a subtree is being promoted, the hook will be called for each node.")
7386 (defun org-promote-subtree ()
7387 "Promote the entire subtree.
7388 See also `org-promote'."
7389 (interactive)
7390 (save-excursion
7391 (org-with-limited-levels (org-map-tree 'org-promote)))
7392 (org-fix-position-after-promote))
7394 (defun org-demote-subtree ()
7395 "Demote the entire subtree. See `org-demote'.
7396 See also `org-promote'."
7397 (interactive)
7398 (save-excursion
7399 (org-with-limited-levels (org-map-tree 'org-demote)))
7400 (org-fix-position-after-promote))
7403 (defun org-do-promote ()
7404 "Promote the current heading higher up the tree.
7405 If the region is active in `transient-mark-mode', promote all headings
7406 in the region."
7407 (interactive)
7408 (save-excursion
7409 (if (org-region-active-p)
7410 (org-map-region 'org-promote (region-beginning) (region-end))
7411 (org-promote)))
7412 (org-fix-position-after-promote))
7414 (defun org-do-demote ()
7415 "Demote the current heading lower down the tree.
7416 If the region is active in `transient-mark-mode', demote all headings
7417 in the region."
7418 (interactive)
7419 (save-excursion
7420 (if (org-region-active-p)
7421 (org-map-region 'org-demote (region-beginning) (region-end))
7422 (org-demote)))
7423 (org-fix-position-after-promote))
7425 (defun org-fix-position-after-promote ()
7426 "Make sure that after pro/demotion cursor position is right."
7427 (let ((pos (point)))
7428 (when (save-excursion
7429 (beginning-of-line 1)
7430 (looking-at org-todo-line-regexp)
7431 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7432 (cond ((eobp) (insert " "))
7433 ((eolp) (insert " "))
7434 ((equal (char-after) ?\ ) (forward-char 1))))))
7436 (defun org-current-level ()
7437 "Return the level of the current entry, or nil if before the first headline.
7438 The level is the number of stars at the beginning of the headline."
7439 (save-excursion
7440 (org-with-limited-levels
7441 (if (ignore-errors (org-back-to-heading t))
7442 (funcall outline-level)))))
7444 (defun org-get-previous-line-level ()
7445 "Return the outline depth of the last headline before the current line.
7446 Returns 0 for the first headline in the buffer, and nil if before the
7447 first headline."
7448 (let ((current-level (org-current-level))
7449 (prev-level (when (> (line-number-at-pos) 1)
7450 (save-excursion
7451 (beginning-of-line 0)
7452 (org-current-level)))))
7453 (cond ((null current-level) nil) ; Before first headline
7454 ((null prev-level) 0) ; At first headline
7455 (prev-level))))
7457 (defun org-reduced-level (l)
7458 "Compute the effective level of a heading.
7459 This takes into account the setting of `org-odd-levels-only'."
7460 (cond
7461 ((zerop l) 0)
7462 (org-odd-levels-only (1+ (floor (/ l 2))))
7463 (t l)))
7465 (defun org-level-increment ()
7466 "Return the number of stars that will be added or removed at a
7467 time to headlines when structure editing, based on the value of
7468 `org-odd-levels-only'."
7469 (if org-odd-levels-only 2 1))
7471 (defun org-get-valid-level (level &optional change)
7472 "Rectify a level change under the influence of `org-odd-levels-only'
7473 LEVEL is a current level, CHANGE is by how much the level should be
7474 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7475 even level numbers will become the next higher odd number."
7476 (if org-odd-levels-only
7477 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7478 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7479 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7480 (max 1 (+ level (or change 0)))))
7482 (if (boundp 'define-obsolete-function-alias)
7483 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7484 (define-obsolete-function-alias 'org-get-legal-level
7485 'org-get-valid-level)
7486 (define-obsolete-function-alias 'org-get-legal-level
7487 'org-get-valid-level "23.1")))
7489 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7490 ;; ̀org-with-limited-levels'
7491 (defun org-promote ()
7492 "Promote the current heading higher up the tree.
7493 If the region is active in `transient-mark-mode', promote all headings
7494 in the region."
7495 (org-back-to-heading t)
7496 (let* ((level (save-match-data (funcall outline-level)))
7497 (after-change-functions (remove 'flyspell-after-change-function
7498 after-change-functions))
7499 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7500 (diff (abs (- level (length up-head) -1))))
7501 (cond ((and (= level 1) org-called-with-limited-levels
7502 org-allow-promoting-top-level-subtree)
7503 (replace-match "# " nil t))
7504 ((= level 1)
7505 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7506 (t (replace-match up-head nil t)))
7507 ;; Fixup tag positioning
7508 (unless (= level 1)
7509 (and org-auto-align-tags (org-set-tags nil t))
7510 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7511 (run-hooks 'org-after-promote-entry-hook)))
7513 (defun org-demote ()
7514 "Demote the current heading lower down the tree.
7515 If the region is active in `transient-mark-mode', demote all headings
7516 in the region."
7517 (org-back-to-heading t)
7518 (let* ((level (save-match-data (funcall outline-level)))
7519 (after-change-functions (remove 'flyspell-after-change-function
7520 after-change-functions))
7521 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7522 (diff (abs (- level (length down-head) -1))))
7523 (replace-match down-head nil t)
7524 ;; Fixup tag positioning
7525 (and org-auto-align-tags (org-set-tags nil t))
7526 (if org-adapt-indentation (org-fixup-indentation diff))
7527 (run-hooks 'org-after-demote-entry-hook)))
7529 (defun org-cycle-level ()
7530 "Cycle the level of an empty headline through possible states.
7531 This goes first to child, then to parent, level, then up the hierarchy.
7532 After top level, it switches back to sibling level."
7533 (interactive)
7534 (let ((org-adapt-indentation nil))
7535 (when (org-point-at-end-of-empty-headline)
7536 (setq this-command 'org-cycle-level) ; Only needed for caching
7537 (let ((cur-level (org-current-level))
7538 (prev-level (org-get-previous-line-level)))
7539 (cond
7540 ;; If first headline in file, promote to top-level.
7541 ((= prev-level 0)
7542 (loop repeat (/ (- cur-level 1) (org-level-increment))
7543 do (org-do-promote)))
7544 ;; If same level as prev, demote one.
7545 ((= prev-level cur-level)
7546 (org-do-demote))
7547 ;; If parent is top-level, promote to top level if not already.
7548 ((= prev-level 1)
7549 (loop repeat (/ (- cur-level 1) (org-level-increment))
7550 do (org-do-promote)))
7551 ;; If top-level, return to prev-level.
7552 ((= cur-level 1)
7553 (loop repeat (/ (- prev-level 1) (org-level-increment))
7554 do (org-do-demote)))
7555 ;; If less than prev-level, promote one.
7556 ((< cur-level prev-level)
7557 (org-do-promote))
7558 ;; If deeper than prev-level, promote until higher than
7559 ;; prev-level.
7560 ((> cur-level prev-level)
7561 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7562 do (org-do-promote))))
7563 t))))
7565 (defun org-map-tree (fun)
7566 "Call FUN for every heading underneath the current one."
7567 (org-back-to-heading)
7568 (let ((level (funcall outline-level)))
7569 (save-excursion
7570 (funcall fun)
7571 (while (and (progn
7572 (outline-next-heading)
7573 (> (funcall outline-level) level))
7574 (not (eobp)))
7575 (funcall fun)))))
7577 (defun org-map-region (fun beg end)
7578 "Call FUN for every heading between BEG and END."
7579 (let ((org-ignore-region t))
7580 (save-excursion
7581 (setq end (copy-marker end))
7582 (goto-char beg)
7583 (if (and (re-search-forward org-outline-regexp-bol nil t)
7584 (< (point) end))
7585 (funcall fun))
7586 (while (and (progn
7587 (outline-next-heading)
7588 (< (point) end))
7589 (not (eobp)))
7590 (funcall fun)))))
7592 (defvar org-property-end-re) ; silence byte-compiler
7593 (defun org-fixup-indentation (diff)
7594 "Change the indentation in the current entry by DIFF.
7595 However, if any line in the current entry has no indentation, or if it
7596 would end up with no indentation after the change, nothing at all is done."
7597 (save-excursion
7598 (let ((end (save-excursion (outline-next-heading)
7599 (point-marker)))
7600 (prohibit (if (> diff 0)
7601 "^\\S-"
7602 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7603 col)
7604 (unless (save-excursion (end-of-line 1)
7605 (re-search-forward prohibit end t))
7606 (while (and (< (point) end)
7607 (re-search-forward "^[ \t]+" end t))
7608 (goto-char (match-end 0))
7609 (setq col (current-column))
7610 (if (< diff 0) (replace-match ""))
7611 (org-indent-to-column (+ diff col))))
7612 (move-marker end nil))))
7614 (defun org-convert-to-odd-levels ()
7615 "Convert an org-mode file with all levels allowed to one with odd levels.
7616 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7617 level 5 etc."
7618 (interactive)
7619 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7620 (let ((outline-level 'org-outline-level)
7621 (org-odd-levels-only nil) n)
7622 (save-excursion
7623 (goto-char (point-min))
7624 (while (re-search-forward "^\\*\\*+ " nil t)
7625 (setq n (- (length (match-string 0)) 2))
7626 (while (>= (setq n (1- n)) 0)
7627 (org-demote))
7628 (end-of-line 1))))))
7630 (defun org-convert-to-oddeven-levels ()
7631 "Convert an org-mode file with only odd levels to one with odd/even levels.
7632 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7633 file contains a section with an even level, conversion would
7634 destroy the structure of the file. An error is signaled in this
7635 case."
7636 (interactive)
7637 (goto-char (point-min))
7638 ;; First check if there are no even levels
7639 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7640 (org-show-context t)
7641 (error "Not all levels are odd in this file. Conversion not possible"))
7642 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7643 (let ((outline-regexp org-outline-regexp)
7644 (outline-level 'org-outline-level)
7645 (org-odd-levels-only nil) n)
7646 (save-excursion
7647 (goto-char (point-min))
7648 (while (re-search-forward "^\\*\\*+ " nil t)
7649 (setq n (/ (1- (length (match-string 0))) 2))
7650 (while (>= (setq n (1- n)) 0)
7651 (org-promote))
7652 (end-of-line 1))))))
7654 (defun org-tr-level (n)
7655 "Make N odd if required."
7656 (if org-odd-levels-only (1+ (/ n 2)) n))
7658 ;;; Vertical tree motion, cutting and pasting of subtrees
7660 (defun org-move-subtree-up (&optional arg)
7661 "Move the current subtree up past ARG headlines of the same level."
7662 (interactive "p")
7663 (org-move-subtree-down (- (prefix-numeric-value arg))))
7665 (defun org-move-subtree-down (&optional arg)
7666 "Move the current subtree down past ARG headlines of the same level."
7667 (interactive "p")
7668 (setq arg (prefix-numeric-value arg))
7669 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7670 'org-get-last-sibling))
7671 (ins-point (make-marker))
7672 (cnt (abs arg))
7673 (col (current-column))
7674 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7675 ;; Select the tree
7676 (org-back-to-heading)
7677 (setq beg0 (point))
7678 (save-excursion
7679 (setq ne-beg (org-back-over-empty-lines))
7680 (setq beg (point)))
7681 (save-match-data
7682 (save-excursion (outline-end-of-heading)
7683 (setq folded (outline-invisible-p)))
7684 (outline-end-of-subtree))
7685 (outline-next-heading)
7686 (setq ne-end (org-back-over-empty-lines))
7687 (setq end (point))
7688 (goto-char beg0)
7689 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7690 ;; include less whitespace
7691 (save-excursion
7692 (goto-char beg)
7693 (forward-line (- ne-beg ne-end))
7694 (setq beg (point))))
7695 ;; Find insertion point, with error handling
7696 (while (> cnt 0)
7697 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7698 (progn (goto-char beg0)
7699 (error "Cannot move past superior level or buffer limit")))
7700 (setq cnt (1- cnt)))
7701 (if (> arg 0)
7702 ;; Moving forward - still need to move over subtree
7703 (progn (org-end-of-subtree t t)
7704 (save-excursion
7705 (org-back-over-empty-lines)
7706 (or (bolp) (newline)))))
7707 (setq ne-ins (org-back-over-empty-lines))
7708 (move-marker ins-point (point))
7709 (setq txt (buffer-substring beg end))
7710 (org-save-markers-in-region beg end)
7711 (delete-region beg end)
7712 (org-remove-empty-overlays-at beg)
7713 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7714 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7715 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7716 (let ((bbb (point)))
7717 (insert-before-markers txt)
7718 (org-reinstall-markers-in-region bbb)
7719 (move-marker ins-point bbb))
7720 (or (bolp) (insert "\n"))
7721 (setq ins-end (point))
7722 (goto-char ins-point)
7723 (org-skip-whitespace)
7724 (when (and (< arg 0)
7725 (org-first-sibling-p)
7726 (> ne-ins ne-beg))
7727 ;; Move whitespace back to beginning
7728 (save-excursion
7729 (goto-char ins-end)
7730 (let ((kill-whole-line t))
7731 (kill-line (- ne-ins ne-beg)) (point)))
7732 (insert (make-string (- ne-ins ne-beg) ?\n)))
7733 (move-marker ins-point nil)
7734 (if folded
7735 (hide-subtree)
7736 (org-show-entry)
7737 (show-children)
7738 (org-cycle-hide-drawers 'children))
7739 (org-clean-visibility-after-subtree-move)
7740 ;; move back to the initial column we were at
7741 (move-to-column col)))
7743 (defvar org-subtree-clip ""
7744 "Clipboard for cut and paste of subtrees.
7745 This is actually only a copy of the kill, because we use the normal kill
7746 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7748 (defvar org-subtree-clip-folded nil
7749 "Was the last copied subtree folded?
7750 This is used to fold the tree back after pasting.")
7752 (defun org-cut-subtree (&optional n)
7753 "Cut the current subtree into the clipboard.
7754 With prefix arg N, cut this many sequential subtrees.
7755 This is a short-hand for marking the subtree and then cutting it."
7756 (interactive "p")
7757 (org-copy-subtree n 'cut))
7759 (defun org-copy-subtree (&optional n cut force-store-markers)
7760 "Cut the current subtree into the clipboard.
7761 With prefix arg N, cut this many sequential subtrees.
7762 This is a short-hand for marking the subtree and then copying it.
7763 If CUT is non-nil, actually cut the subtree.
7764 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7765 of some markers in the region, even if CUT is non-nil. This is
7766 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7767 (interactive "p")
7768 (let (beg end folded (beg0 (point)))
7769 (if (org-called-interactively-p 'any)
7770 (org-back-to-heading nil) ; take what looks like a subtree
7771 (org-back-to-heading t)) ; take what is really there
7772 (org-back-over-empty-lines)
7773 (setq beg (point))
7774 (skip-chars-forward " \t\r\n")
7775 (save-match-data
7776 (save-excursion (outline-end-of-heading)
7777 (setq folded (outline-invisible-p)))
7778 (condition-case nil
7779 (org-forward-same-level (1- n) t)
7780 (error nil))
7781 (org-end-of-subtree t t))
7782 (org-back-over-empty-lines)
7783 (setq end (point))
7784 (goto-char beg0)
7785 (when (> end beg)
7786 (setq org-subtree-clip-folded folded)
7787 (when (or cut force-store-markers)
7788 (org-save-markers-in-region beg end))
7789 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7790 (setq org-subtree-clip (current-kill 0))
7791 (message "%s: Subtree(s) with %d characters"
7792 (if cut "Cut" "Copied")
7793 (length org-subtree-clip)))))
7795 (defun org-paste-subtree (&optional level tree for-yank)
7796 "Paste the clipboard as a subtree, with modification of headline level.
7797 The entire subtree is promoted or demoted in order to match a new headline
7798 level.
7800 If the cursor is at the beginning of a headline, the same level as
7801 that headline is used to paste the tree
7803 If not, the new level is derived from the *visible* headings
7804 before and after the insertion point, and taken to be the inferior headline
7805 level of the two. So if the previous visible heading is level 3 and the
7806 next is level 4 (or vice versa), level 4 will be used for insertion.
7807 This makes sure that the subtree remains an independent subtree and does
7808 not swallow low level entries.
7810 You can also force a different level, either by using a numeric prefix
7811 argument, or by inserting the heading marker by hand. For example, if the
7812 cursor is after \"*****\", then the tree will be shifted to level 5.
7814 If optional TREE is given, use this text instead of the kill ring.
7816 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7817 move back over whitespace before inserting, and move point to the end of
7818 the inserted text when done."
7819 (interactive "P")
7820 (setq tree (or tree (and kill-ring (current-kill 0))))
7821 (unless (org-kill-is-subtree-p tree)
7822 (error "%s"
7823 (substitute-command-keys
7824 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7825 (org-with-limited-levels
7826 (let* ((visp (not (outline-invisible-p)))
7827 (txt tree)
7828 (^re_ "\\(\\*+\\)[ \t]*")
7829 (old-level (if (string-match org-outline-regexp-bol txt)
7830 (- (match-end 0) (match-beginning 0) 1)
7831 -1))
7832 (force-level (cond (level (prefix-numeric-value level))
7833 ((and (looking-at "[ \t]*$")
7834 (string-match
7835 "^\\*+$" (buffer-substring
7836 (point-at-bol) (point))))
7837 (- (match-end 1) (match-beginning 1)))
7838 ((and (bolp)
7839 (looking-at org-outline-regexp))
7840 (- (match-end 0) (point) 1))
7841 (t nil)))
7842 (previous-level (save-excursion
7843 (condition-case nil
7844 (progn
7845 (outline-previous-visible-heading 1)
7846 (if (looking-at ^re_)
7847 (- (match-end 0) (match-beginning 0) 1)
7849 (error 1))))
7850 (next-level (save-excursion
7851 (condition-case nil
7852 (progn
7853 (or (looking-at org-outline-regexp)
7854 (outline-next-visible-heading 1))
7855 (if (looking-at ^re_)
7856 (- (match-end 0) (match-beginning 0) 1)
7858 (error 1))))
7859 (new-level (or force-level (max previous-level next-level)))
7860 (shift (if (or (= old-level -1)
7861 (= new-level -1)
7862 (= old-level new-level))
7864 (- new-level old-level)))
7865 (delta (if (> shift 0) -1 1))
7866 (func (if (> shift 0) 'org-demote 'org-promote))
7867 (org-odd-levels-only nil)
7868 beg end newend)
7869 ;; Remove the forced level indicator
7870 (if force-level
7871 (delete-region (point-at-bol) (point)))
7872 ;; Paste
7873 (beginning-of-line (if (bolp) 1 2))
7874 (unless for-yank (org-back-over-empty-lines))
7875 (setq beg (point))
7876 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7877 (insert-before-markers txt)
7878 (unless (string-match "\n\\'" txt) (insert "\n"))
7879 (setq newend (point))
7880 (org-reinstall-markers-in-region beg)
7881 (setq end (point))
7882 (goto-char beg)
7883 (skip-chars-forward " \t\n\r")
7884 (setq beg (point))
7885 (if (and (outline-invisible-p) visp)
7886 (save-excursion (outline-show-heading)))
7887 ;; Shift if necessary
7888 (unless (= shift 0)
7889 (save-restriction
7890 (narrow-to-region beg end)
7891 (while (not (= shift 0))
7892 (org-map-region func (point-min) (point-max))
7893 (setq shift (+ delta shift)))
7894 (goto-char (point-min))
7895 (setq newend (point-max))))
7896 (when (or (org-called-interactively-p 'interactive) for-yank)
7897 (message "Clipboard pasted as level %d subtree" new-level))
7898 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7899 kill-ring
7900 (eq org-subtree-clip (current-kill 0))
7901 org-subtree-clip-folded)
7902 ;; The tree was folded before it was killed/copied
7903 (hide-subtree))
7904 (and for-yank (goto-char newend)))))
7906 (defun org-kill-is-subtree-p (&optional txt)
7907 "Check if the current kill is an outline subtree, or a set of trees.
7908 Returns nil if kill does not start with a headline, or if the first
7909 headline level is not the largest headline level in the tree.
7910 So this will actually accept several entries of equal levels as well,
7911 which is OK for `org-paste-subtree'.
7912 If optional TXT is given, check this string instead of the current kill."
7913 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7914 (re (org-get-limited-outline-regexp))
7915 (^re (concat "^" re))
7916 (start-level (and kill
7917 (string-match
7918 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7919 kill)
7920 (- (match-end 2) (match-beginning 2) 1)))
7921 (start (1+ (or (match-beginning 2) -1))))
7922 (if (not start-level)
7923 (progn
7924 nil) ;; does not even start with a heading
7925 (catch 'exit
7926 (while (setq start (string-match ^re kill (1+ start)))
7927 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7928 (throw 'exit nil)))
7929 t))))
7931 (defvar org-markers-to-move nil
7932 "Markers that should be moved with a cut-and-paste operation.
7933 Those markers are stored together with their positions relative to
7934 the start of the region.")
7936 (defun org-save-markers-in-region (beg end)
7937 "Check markers in region.
7938 If these markers are between BEG and END, record their position relative
7939 to BEG, so that after moving the block of text, we can put the markers back
7940 into place.
7941 This function gets called just before an entry or tree gets cut from the
7942 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7943 called immediately, to move the markers with the entries."
7944 (setq org-markers-to-move nil)
7945 (when (featurep 'org-clock)
7946 (org-clock-save-markers-for-cut-and-paste beg end))
7947 (when (featurep 'org-agenda)
7948 (org-agenda-save-markers-for-cut-and-paste beg end)))
7950 (defun org-check-and-save-marker (marker beg end)
7951 "Check if MARKER is between BEG and END.
7952 If yes, remember the marker and the distance to BEG."
7953 (when (and (marker-buffer marker)
7954 (equal (marker-buffer marker) (current-buffer)))
7955 (if (and (>= marker beg) (< marker end))
7956 (push (cons marker (- marker beg)) org-markers-to-move))))
7958 (defun org-reinstall-markers-in-region (beg)
7959 "Move all remembered markers to their position relative to BEG."
7960 (mapc (lambda (x)
7961 (move-marker (car x) (+ beg (cdr x))))
7962 org-markers-to-move)
7963 (setq org-markers-to-move nil))
7965 (defun org-narrow-to-subtree ()
7966 "Narrow buffer to the current subtree."
7967 (interactive)
7968 (save-excursion
7969 (save-match-data
7970 (org-with-limited-levels
7971 (narrow-to-region
7972 (progn (org-back-to-heading t) (point))
7973 (progn (org-end-of-subtree t t)
7974 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7975 (point)))))))
7977 (defun org-narrow-to-block ()
7978 "Narrow buffer to the current block."
7979 (interactive)
7980 (let* ((case-fold-search t)
7981 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7982 "^[ \t]*#\\+end_.*")))
7983 (if blockp
7984 (narrow-to-region (car blockp) (cdr blockp))
7985 (error "Not in a block"))))
7987 (eval-when-compile
7988 (defvar org-property-drawer-re))
7990 (defvar org-property-start-re) ;; defined below
7991 (defun org-clone-subtree-with-time-shift (n &optional shift)
7992 "Clone the task (subtree) at point N times.
7993 The clones will be inserted as siblings.
7995 In interactive use, the user will be prompted for the number of
7996 clones to be produced, and for a time SHIFT, which may be a
7997 repeater as used in time stamps, for example `+3d'.
7999 When a valid repeater is given and the entry contains any time
8000 stamps, the clones will become a sequence in time, with time
8001 stamps in the subtree shifted for each clone produced. If SHIFT
8002 is nil or the empty string, time stamps will be left alone. The
8003 ID property of the original subtree is removed.
8005 If the original subtree did contain time stamps with a repeater,
8006 the following will happen:
8007 - the repeater will be removed in each clone
8008 - an additional clone will be produced, with the current, unshifted
8009 date(s) in the entry.
8010 - the original entry will be placed *after* all the clones, with
8011 repeater intact.
8012 - the start days in the repeater in the original entry will be shifted
8013 to past the last clone.
8014 In this way you can spell out a number of instances of a repeating task,
8015 and still retain the repeater to cover future instances of the task."
8016 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8017 (let (beg end template task idprop
8018 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8019 (drawer-re org-drawer-regexp))
8020 (if (not (and (integerp n) (> n 0)))
8021 (error "Invalid number of replications %s" n))
8022 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8023 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8024 shift)))
8025 (error "Invalid shift specification %s" shift))
8026 (when doshift
8027 (setq shift-n (string-to-number (match-string 1 shift))
8028 shift-what (cdr (assoc (match-string 2 shift)
8029 '(("d" . day) ("w" . week)
8030 ("m" . month) ("y" . year))))))
8031 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8032 (setq nmin 1 nmax n)
8033 (org-back-to-heading t)
8034 (setq beg (point))
8035 (setq idprop (org-entry-get nil "ID"))
8036 (org-end-of-subtree t t)
8037 (or (bolp) (insert "\n"))
8038 (setq end (point))
8039 (setq template (buffer-substring beg end))
8040 (when (and doshift
8041 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8042 (delete-region beg end)
8043 (setq end beg)
8044 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8045 (goto-char end)
8046 (loop for n from nmin to nmax do
8047 ;; prepare clone
8048 (with-temp-buffer
8049 (insert template)
8050 (org-mode)
8051 (goto-char (point-min))
8052 (org-show-subtree)
8053 (and idprop (if org-clone-delete-id
8054 (org-entry-delete nil "ID")
8055 (org-id-get-create t)))
8056 (unless (= n 0)
8057 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8058 (kill-whole-line))
8059 (goto-char (point-min))
8060 (while (re-search-forward drawer-re nil t)
8061 (mapc (lambda (d)
8062 (org-remove-empty-drawer-at d (point))) org-drawers)))
8063 (goto-char (point-min))
8064 (when doshift
8065 (while (re-search-forward org-ts-regexp-both nil t)
8066 (org-timestamp-change (* n shift-n) shift-what))
8067 (unless (= n n-no-remove)
8068 (goto-char (point-min))
8069 (while (re-search-forward org-ts-regexp nil t)
8070 (save-excursion
8071 (goto-char (match-beginning 0))
8072 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8073 (delete-region (match-beginning 1) (match-end 1)))))))
8074 (setq task (buffer-string)))
8075 (insert task))
8076 (goto-char beg)))
8078 ;;; Outline Sorting
8080 (defun org-sort (with-case)
8081 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8082 Optional argument WITH-CASE means sort case-sensitively."
8083 (interactive "P")
8084 (cond
8085 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8086 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8088 (org-call-with-arg 'org-sort-entries with-case))))
8090 (defun org-sort-remove-invisible (s)
8091 (remove-text-properties 0 (length s) org-rm-props s)
8092 (while (string-match org-bracket-link-regexp s)
8093 (setq s (replace-match (if (match-end 2)
8094 (match-string 3 s)
8095 (match-string 1 s)) t t s)))
8098 (defvar org-priority-regexp) ; defined later in the file
8100 (defvar org-after-sorting-entries-or-items-hook nil
8101 "Hook that is run after a bunch of entries or items have been sorted.
8102 When children are sorted, the cursor is in the parent line when this
8103 hook gets called. When a region or a plain list is sorted, the cursor
8104 will be in the first entry of the sorted region/list.")
8106 (defun org-sort-entries
8107 (&optional with-case sorting-type getkey-func compare-func property)
8108 "Sort entries on a certain level of an outline tree.
8109 If there is an active region, the entries in the region are sorted.
8110 Else, if the cursor is before the first entry, sort the top-level items.
8111 Else, the children of the entry at point are sorted.
8113 Sorting can be alphabetically, numerically, by date/time as given by
8114 a time stamp, by a property or by priority.
8116 The command prompts for the sorting type unless it has been given to the
8117 function through the SORTING-TYPE argument, which needs to be a character,
8118 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8119 precise meaning of each character:
8121 n Numerically, by converting the beginning of the entry/item to a number.
8122 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8123 t By date/time, either the first active time stamp in the entry, or, if
8124 none exist, by the first inactive one.
8125 s By the scheduled date/time.
8126 d By deadline date/time.
8127 c By creation time, which is assumed to be the first inactive time stamp
8128 at the beginning of a line.
8129 p By priority according to the cookie.
8130 r By the value of a property.
8132 Capital letters will reverse the sort order.
8134 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8135 called with point at the beginning of the record. It must return either
8136 a string or a number that should serve as the sorting key for that record.
8138 Comparing entries ignores case by default. However, with an optional argument
8139 WITH-CASE, the sorting considers case as well."
8140 (interactive "P")
8141 (let ((case-func (if with-case 'identity 'downcase))
8142 start beg end stars re re2
8143 txt what tmp)
8144 ;; Find beginning and end of region to sort
8145 (cond
8146 ((org-region-active-p)
8147 ;; we will sort the region
8148 (setq end (region-end)
8149 what "region")
8150 (goto-char (region-beginning))
8151 (if (not (org-at-heading-p)) (outline-next-heading))
8152 (setq start (point)))
8153 ((or (org-at-heading-p)
8154 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8155 ;; we will sort the children of the current headline
8156 (org-back-to-heading)
8157 (setq start (point)
8158 end (progn (org-end-of-subtree t t)
8159 (or (bolp) (insert "\n"))
8160 (org-back-over-empty-lines)
8161 (point))
8162 what "children")
8163 (goto-char start)
8164 (show-subtree)
8165 (outline-next-heading))
8167 ;; we will sort the top-level entries in this file
8168 (goto-char (point-min))
8169 (or (org-at-heading-p) (outline-next-heading))
8170 (setq start (point))
8171 (goto-char (point-max))
8172 (beginning-of-line 1)
8173 (when (looking-at ".*?\\S-")
8174 ;; File ends in a non-white line
8175 (end-of-line 1)
8176 (insert "\n"))
8177 (setq end (point-max))
8178 (setq what "top-level")
8179 (goto-char start)
8180 (show-all)))
8182 (setq beg (point))
8183 (if (>= beg end) (error "Nothing to sort"))
8185 (looking-at "\\(\\*+\\)")
8186 (setq stars (match-string 1)
8187 re (concat "^" (regexp-quote stars) " +")
8188 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8189 txt (buffer-substring beg end))
8190 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8191 (if (and (not (equal stars "*")) (string-match re2 txt))
8192 (error "Region to sort contains a level above the first entry"))
8194 (unless sorting-type
8195 (message
8196 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8197 [t]ime [s]cheduled [d]eadline [c]reated
8198 A/N/T/S/D/C/P/O/F means reversed:"
8199 what)
8200 (setq sorting-type (read-char-exclusive))
8202 (and (= (downcase sorting-type) ?f)
8203 (setq getkey-func
8204 (org-icompleting-read "Sort using function: "
8205 obarray 'fboundp t nil nil))
8206 (setq getkey-func (intern getkey-func)))
8208 (and (= (downcase sorting-type) ?r)
8209 (setq property
8210 (org-icompleting-read "Property: "
8211 (mapcar 'list (org-buffer-property-keys t))
8212 nil t))))
8214 (message "Sorting entries...")
8216 (save-restriction
8217 (narrow-to-region start end)
8218 (let ((dcst (downcase sorting-type))
8219 (case-fold-search nil)
8220 (now (current-time)))
8221 (sort-subr
8222 (/= dcst sorting-type)
8223 ;; This function moves to the beginning character of the "record" to
8224 ;; be sorted.
8225 (lambda nil
8226 (if (re-search-forward re nil t)
8227 (goto-char (match-beginning 0))
8228 (goto-char (point-max))))
8229 ;; This function moves to the last character of the "record" being
8230 ;; sorted.
8231 (lambda nil
8232 (save-match-data
8233 (condition-case nil
8234 (outline-forward-same-level 1)
8235 (error
8236 (goto-char (point-max))))))
8237 ;; This function returns the value that gets sorted against.
8238 (lambda nil
8239 (cond
8240 ((= dcst ?n)
8241 (if (looking-at org-complex-heading-regexp)
8242 (string-to-number (match-string 4))
8243 nil))
8244 ((= dcst ?a)
8245 (if (looking-at org-complex-heading-regexp)
8246 (funcall case-func (match-string 4))
8247 nil))
8248 ((= dcst ?t)
8249 (let ((end (save-excursion (outline-next-heading) (point))))
8250 (if (or (re-search-forward org-ts-regexp end t)
8251 (re-search-forward org-ts-regexp-both end t))
8252 (org-time-string-to-seconds (match-string 0))
8253 (org-float-time now))))
8254 ((= dcst ?c)
8255 (let ((end (save-excursion (outline-next-heading) (point))))
8256 (if (re-search-forward
8257 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8258 end t)
8259 (org-time-string-to-seconds (match-string 0))
8260 (org-float-time now))))
8261 ((= dcst ?s)
8262 (let ((end (save-excursion (outline-next-heading) (point))))
8263 (if (re-search-forward org-scheduled-time-regexp end t)
8264 (org-time-string-to-seconds (match-string 1))
8265 (org-float-time now))))
8266 ((= dcst ?d)
8267 (let ((end (save-excursion (outline-next-heading) (point))))
8268 (if (re-search-forward org-deadline-time-regexp end t)
8269 (org-time-string-to-seconds (match-string 1))
8270 (org-float-time now))))
8271 ((= dcst ?p)
8272 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8273 (string-to-char (match-string 2))
8274 org-default-priority))
8275 ((= dcst ?r)
8276 (or (org-entry-get nil property) ""))
8277 ((= dcst ?o)
8278 (if (looking-at org-complex-heading-regexp)
8279 (- 9999 (length (member (match-string 2)
8280 org-todo-keywords-1)))))
8281 ((= dcst ?f)
8282 (if getkey-func
8283 (progn
8284 (setq tmp (funcall getkey-func))
8285 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8286 tmp)
8287 (error "Invalid key function `%s'" getkey-func)))
8288 (t (error "Invalid sorting type `%c'" sorting-type))))
8290 (cond
8291 ((= dcst ?a) 'string<)
8292 ((= dcst ?f) compare-func)
8293 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8294 (t nil)))))
8295 (run-hooks 'org-after-sorting-entries-or-items-hook)
8296 (message "Sorting entries...done")))
8298 (defun org-do-sort (table what &optional with-case sorting-type)
8299 "Sort TABLE of WHAT according to SORTING-TYPE.
8300 The user will be prompted for the SORTING-TYPE if the call to this
8301 function does not specify it. WHAT is only for the prompt, to indicate
8302 what is being sorted. The sorting key will be extracted from
8303 the car of the elements of the table.
8304 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8305 (unless sorting-type
8306 (message
8307 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8308 what)
8309 (setq sorting-type (read-char-exclusive)))
8310 (let ((dcst (downcase sorting-type))
8311 extractfun comparefun)
8312 ;; Define the appropriate functions
8313 (cond
8314 ((= dcst ?n)
8315 (setq extractfun 'string-to-number
8316 comparefun (if (= dcst sorting-type) '< '>)))
8317 ((= dcst ?a)
8318 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8319 (lambda(x) (downcase (org-sort-remove-invisible x))))
8320 comparefun (if (= dcst sorting-type)
8321 'string<
8322 (lambda (a b) (and (not (string< a b))
8323 (not (string= a b)))))))
8324 ((= dcst ?t)
8325 (setq extractfun
8326 (lambda (x)
8327 (if (or (string-match org-ts-regexp x)
8328 (string-match org-ts-regexp-both x))
8329 (org-float-time
8330 (org-time-string-to-time (match-string 0 x)))
8332 comparefun (if (= dcst sorting-type) '< '>)))
8333 (t (error "Invalid sorting type `%c'" sorting-type)))
8335 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8336 table)
8337 (lambda (a b) (funcall comparefun (car a) (car b))))))
8340 ;;; The orgstruct minor mode
8342 ;; Define a minor mode which can be used in other modes in order to
8343 ;; integrate the org-mode structure editing commands.
8345 ;; This is really a hack, because the org-mode structure commands use
8346 ;; keys which normally belong to the major mode. Here is how it
8347 ;; works: The minor mode defines all the keys necessary to operate the
8348 ;; structure commands, but wraps the commands into a function which
8349 ;; tests if the cursor is currently at a headline or a plain list
8350 ;; item. If that is the case, the structure command is used,
8351 ;; temporarily setting many Org-mode variables like regular
8352 ;; expressions for filling etc. However, when any of those keys is
8353 ;; used at a different location, function uses `key-binding' to look
8354 ;; up if the key has an associated command in another currently active
8355 ;; keymap (minor modes, major mode, global), and executes that
8356 ;; command. There might be problems if any of the keys is otherwise
8357 ;; used as a prefix key.
8359 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8360 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8361 ;; addresses this by checking explicitly for both bindings.
8363 (defvar orgstruct-mode-map (make-sparse-keymap)
8364 "Keymap for the minor `orgstruct-mode'.")
8366 (defvar org-local-vars nil
8367 "List of local variables, for use by `orgstruct-mode'.")
8369 ;;;###autoload
8370 (define-minor-mode orgstruct-mode
8371 "Toggle the minor mode `orgstruct-mode'.
8372 This mode is for using Org-mode structure commands in other
8373 modes. The following keys behave as if Org-mode were active, if
8374 the cursor is on a headline, or on a plain list item (both as
8375 defined by Org-mode).
8377 M-up Move entry/item up
8378 M-down Move entry/item down
8379 M-left Promote
8380 M-right Demote
8381 M-S-up Move entry/item up
8382 M-S-down Move entry/item down
8383 M-S-left Promote subtree
8384 M-S-right Demote subtree
8385 M-q Fill paragraph and items like in Org-mode
8386 C-c ^ Sort entries
8387 C-c - Cycle list bullet
8388 TAB Cycle item visibility
8389 M-RET Insert new heading/item
8390 S-M-RET Insert new TODO heading / Checkbox item
8391 C-c C-c Set tags / toggle checkbox"
8392 nil " OrgStruct" nil
8393 (org-load-modules-maybe)
8394 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8396 ;;;###autoload
8397 (defun turn-on-orgstruct ()
8398 "Unconditionally turn on `orgstruct-mode'."
8399 (orgstruct-mode 1))
8401 (defvar org-fb-vars nil)
8402 (make-variable-buffer-local 'org-fb-vars)
8403 (defun orgstruct++-mode (&optional arg)
8404 "Toggle `orgstruct-mode', the enhanced version of it.
8405 In addition to setting orgstruct-mode, this also exports all
8406 indentation and autofilling variables from org-mode into the
8407 buffer. It will also recognize item context in multiline items."
8408 (interactive "P")
8409 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8410 (if (< arg 1)
8411 (progn (orgstruct-mode -1)
8412 (mapc (lambda(v)
8413 (org-set-local (car v)
8414 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8415 org-fb-vars))
8416 (orgstruct-mode 1)
8417 (setq org-fb-vars nil)
8418 (let (var val)
8419 (mapc
8420 (lambda (x)
8421 (when (string-match
8422 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8423 (symbol-name (car x)))
8424 (setq var (car x) val (nth 1 x))
8425 (push (list var `(quote ,(eval var))) org-fb-vars)
8426 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8427 org-local-vars)
8428 (org-set-local 'orgstruct-is-++ t))))
8430 (defvar orgstruct-is-++ nil
8431 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8432 (make-variable-buffer-local 'orgstruct-is-++)
8434 ;;;###autoload
8435 (defun turn-on-orgstruct++ ()
8436 "Unconditionally turn on `orgstruct++-mode'."
8437 (orgstruct++-mode 1))
8439 (defun orgstruct-error ()
8440 "Error when there is no default binding for a structure key."
8441 (interactive)
8442 (error "This key has no function outside structure elements"))
8444 (defun orgstruct-setup ()
8445 "Setup orgstruct keymaps."
8446 (let ((nfunc 0)
8447 (bindings
8448 (list
8449 '([(meta up)] org-metaup)
8450 '([(meta down)] org-metadown)
8451 '([(meta left)] org-metaleft)
8452 '([(meta right)] org-metaright)
8453 '([(meta shift up)] org-shiftmetaup)
8454 '([(meta shift down)] org-shiftmetadown)
8455 '([(meta shift left)] org-shiftmetaleft)
8456 '([(meta shift right)] org-shiftmetaright)
8457 '([?\e (up)] org-metaup)
8458 '([?\e (down)] org-metadown)
8459 '([?\e (left)] org-metaleft)
8460 '([?\e (right)] org-metaright)
8461 '([?\e (shift up)] org-shiftmetaup)
8462 '([?\e (shift down)] org-shiftmetadown)
8463 '([?\e (shift left)] org-shiftmetaleft)
8464 '([?\e (shift right)] org-shiftmetaright)
8465 '([(shift up)] org-shiftup)
8466 '([(shift down)] org-shiftdown)
8467 '([(shift left)] org-shiftleft)
8468 '([(shift right)] org-shiftright)
8469 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8470 '("\M-q" fill-paragraph)
8471 '("\C-c^" org-sort)
8472 '("\C-c-" org-cycle-list-bullet)))
8473 elt key fun cmd)
8474 (while (setq elt (pop bindings))
8475 (setq nfunc (1+ nfunc))
8476 (setq key (org-key (car elt))
8477 fun (nth 1 elt)
8478 cmd (orgstruct-make-binding fun nfunc key))
8479 (org-defkey orgstruct-mode-map key cmd))
8481 ;; Special treatment needed for TAB and RET
8482 (org-defkey orgstruct-mode-map [(tab)]
8483 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8484 (org-defkey orgstruct-mode-map "\C-i"
8485 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8487 (org-defkey orgstruct-mode-map "\M-\C-m"
8488 (orgstruct-make-binding 'org-insert-heading 105
8489 "\M-\C-m" [(meta return)]))
8490 (org-defkey orgstruct-mode-map [(meta return)]
8491 (orgstruct-make-binding 'org-insert-heading 106
8492 [(meta return)] "\M-\C-m"))
8494 (org-defkey orgstruct-mode-map [(shift meta return)]
8495 (orgstruct-make-binding 'org-insert-todo-heading 107
8496 [(meta return)] "\M-\C-m"))
8498 (org-defkey orgstruct-mode-map "\e\C-m"
8499 (orgstruct-make-binding 'org-insert-heading 108
8500 "\e\C-m" [?\e (return)]))
8501 (org-defkey orgstruct-mode-map [?\e (return)]
8502 (orgstruct-make-binding 'org-insert-heading 109
8503 [?\e (return)] "\e\C-m"))
8504 (org-defkey orgstruct-mode-map [?\e (shift return)]
8505 (orgstruct-make-binding 'org-insert-todo-heading 110
8506 [?\e (return)] "\e\C-m"))
8508 (unless org-local-vars
8509 (setq org-local-vars (org-get-local-variables)))
8513 (defun orgstruct-make-binding (fun n &rest keys)
8514 "Create a function for binding in the structure minor mode.
8515 FUN is the command to call inside a table. N is used to create a unique
8516 command name. KEYS are keys that should be checked in for a command
8517 to execute outside of tables."
8518 (eval
8519 (list 'defun
8520 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8521 '(arg)
8522 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8523 "Outside of structure, run the binding of `"
8524 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8525 "'.")
8526 '(interactive "p")
8527 (list 'if
8528 `(org-context-p 'headline 'item
8529 (and orgstruct-is-++
8530 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8531 'item-body))
8532 (list 'org-run-like-in-org-mode (list 'quote fun))
8533 (list 'let '(orgstruct-mode)
8534 (list 'call-interactively
8535 (append '(or)
8536 (mapcar (lambda (k)
8537 (list 'key-binding k))
8538 keys)
8539 '('orgstruct-error))))))))
8541 (defun org-context-p (&rest contexts)
8542 "Check if local context is any of CONTEXTS.
8543 Possible values in the list of contexts are `table', `headline', and `item'."
8544 (let ((pos (point)))
8545 (goto-char (point-at-bol))
8546 (prog1 (or (and (memq 'table contexts)
8547 (looking-at "[ \t]*|"))
8548 (and (memq 'headline contexts)
8549 (looking-at org-outline-regexp))
8550 (and (memq 'item contexts)
8551 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8552 (and (memq 'item-body contexts)
8553 (org-in-item-p)))
8554 (goto-char pos))))
8556 (defun org-get-local-variables ()
8557 "Return a list of all local variables in an org-mode buffer."
8558 (let (varlist)
8559 (with-current-buffer (get-buffer-create "*Org tmp*")
8560 (erase-buffer)
8561 (org-mode)
8562 (setq varlist (buffer-local-variables)))
8563 (kill-buffer "*Org tmp*")
8564 (delq nil
8565 (mapcar
8566 (lambda (x)
8567 (setq x
8568 (if (symbolp x)
8569 (list x)
8570 (list (car x) (list 'quote (cdr x)))))
8571 (if (string-match
8572 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8573 (symbol-name (car x)))
8574 x nil))
8575 varlist))))
8577 (defun org-clone-local-variables (from-buffer &optional regexp)
8578 "Clone local variables from FROM-BUFFER.
8579 Optional argument REGEXP selects variables to clone."
8580 (mapc
8581 (lambda (pair)
8582 (and (symbolp (car pair))
8583 (or (null regexp)
8584 (string-match regexp (symbol-name (car pair))))
8585 (set (make-local-variable (car pair))
8586 (cdr pair))))
8587 (buffer-local-variables from-buffer)))
8589 ;;;###autoload
8590 (defun org-run-like-in-org-mode (cmd)
8591 "Run a command, pretending that the current buffer is in Org-mode.
8592 This will temporarily bind local variables that are typically bound in
8593 Org-mode to the values they have in Org-mode, and then interactively
8594 call CMD."
8595 (org-load-modules-maybe)
8596 (unless org-local-vars
8597 (setq org-local-vars (org-get-local-variables)))
8598 (eval (list 'let org-local-vars
8599 (list 'call-interactively (list 'quote cmd)))))
8601 ;;;; Archiving
8603 (defun org-get-category (&optional pos force-refresh)
8604 "Get the category applying to position POS."
8605 (save-match-data
8606 (if force-refresh (org-refresh-category-properties))
8607 (let ((pos (or pos (point))))
8608 (or (get-text-property pos 'org-category)
8609 (progn (org-refresh-category-properties)
8610 (get-text-property pos 'org-category))))))
8612 (defun org-refresh-category-properties ()
8613 "Refresh category text properties in the buffer."
8614 (let ((inhibit-read-only t)
8615 (def-cat (cond
8616 ((null org-category)
8617 (if buffer-file-name
8618 (file-name-sans-extension
8619 (file-name-nondirectory buffer-file-name))
8620 "???"))
8621 ((symbolp org-category) (symbol-name org-category))
8622 (t org-category)))
8623 beg end cat pos optionp)
8624 (org-unmodified
8625 (save-excursion
8626 (save-restriction
8627 (widen)
8628 (goto-char (point-min))
8629 (put-text-property (point) (point-max) 'org-category def-cat)
8630 (while (re-search-forward
8631 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8632 (setq pos (match-end 0)
8633 optionp (equal (char-after (match-beginning 0)) ?#)
8634 cat (org-trim (match-string 2)))
8635 (if optionp
8636 (setq beg (point-at-bol) end (point-max))
8637 (org-back-to-heading t)
8638 (setq beg (point) end (org-end-of-subtree t t)))
8639 (put-text-property beg end 'org-category cat)
8640 (put-text-property beg end 'org-category-position beg)
8641 (goto-char pos)))))))
8644 ;;;; Link Stuff
8646 ;;; Link abbreviations
8648 (defun org-link-expand-abbrev (link)
8649 "Apply replacements as defined in `org-link-abbrev-alist'."
8650 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8651 (let* ((key (match-string 1 link))
8652 (as (or (assoc key org-link-abbrev-alist-local)
8653 (assoc key org-link-abbrev-alist)))
8654 (tag (and (match-end 2) (match-string 3 link)))
8655 rpl)
8656 (if (not as)
8657 link
8658 (setq rpl (cdr as))
8659 (cond
8660 ((symbolp rpl) (funcall rpl tag))
8661 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8662 ((string-match "%h" rpl)
8663 (replace-match (url-hexify-string (or tag "")) t t rpl))
8664 (t (concat rpl tag)))))
8665 link))
8667 ;;; Storing and inserting links
8669 (defvar org-insert-link-history nil
8670 "Minibuffer history for links inserted with `org-insert-link'.")
8672 (defvar org-stored-links nil
8673 "Contains the links stored with `org-store-link'.")
8675 (defvar org-store-link-plist nil
8676 "Plist with info about the most recently link created with `org-store-link'.")
8678 (defvar org-link-protocols nil
8679 "Link protocols added to Org-mode using `org-add-link-type'.")
8681 (defvar org-store-link-functions nil
8682 "List of functions that are called to create and store a link.
8683 Each function will be called in turn until one returns a non-nil
8684 value. Each function should check if it is responsible for creating
8685 this link (for example by looking at the major mode).
8686 If not, it must exit and return nil.
8687 If yes, it should return a non-nil value after a calling
8688 `org-store-link-props' with a list of properties and values.
8689 Special properties are:
8691 :type The link prefix, like \"http\". This must be given.
8692 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8693 This is obligatory as well.
8694 :description Optional default description for the second pair
8695 of brackets in an Org-mode link. The user can still change
8696 this when inserting this link into an Org-mode buffer.
8698 In addition to these, any additional properties can be specified
8699 and then used in remember templates.")
8701 (defun org-add-link-type (type &optional follow export)
8702 "Add TYPE to the list of `org-link-types'.
8703 Re-compute all regular expressions depending on `org-link-types'
8705 FOLLOW and EXPORT are two functions.
8707 FOLLOW should take the link path as the single argument and do whatever
8708 is necessary to follow the link, for example find a file or display
8709 a mail message.
8711 EXPORT should format the link path for export to one of the export formats.
8712 It should be a function accepting three arguments:
8714 path the path of the link, the text after the prefix (like \"http:\")
8715 desc the description of the link, if any, or a description added by
8716 org-export-normalize-links if there is none
8717 format the export format, a symbol like `html' or `latex' or `ascii'..
8719 The function may use the FORMAT information to return different values
8720 depending on the format. The return value will be put literally into
8721 the exported file. If the return value is nil, this means Org should
8722 do what it normally does with links which do not have EXPORT defined.
8724 Org-mode has a built-in default for exporting links. If you are happy with
8725 this default, there is no need to define an export function for the link
8726 type. For a simple example of an export function, see `org-bbdb.el'."
8727 (add-to-list 'org-link-types type t)
8728 (org-make-link-regexps)
8729 (if (assoc type org-link-protocols)
8730 (setcdr (assoc type org-link-protocols) (list follow export))
8731 (push (list type follow export) org-link-protocols)))
8733 (defvar org-agenda-buffer-name)
8735 ;;;###autoload
8736 (defun org-store-link (arg)
8737 "\\<org-mode-map>Store an org-link to the current location.
8738 This link is added to `org-stored-links' and can later be inserted
8739 into an org-buffer with \\[org-insert-link].
8741 For some link types, a prefix arg is interpreted:
8742 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8743 For file links, arg negates `org-context-in-file-links'."
8744 (interactive "P")
8745 (org-load-modules-maybe)
8746 (setq org-store-link-plist nil) ; reset
8747 (org-with-limited-levels
8748 (let (link cpltxt desc description search txt custom-id agenda-link)
8749 (cond
8751 ((run-hook-with-args-until-success 'org-store-link-functions)
8752 (setq link (plist-get org-store-link-plist :link)
8753 desc (or (plist-get org-store-link-plist :description) link)))
8755 ((org-src-edit-buffer-p)
8756 (let (label gc)
8757 (while (or (not label)
8758 (save-excursion
8759 (save-restriction
8760 (widen)
8761 (goto-char (point-min))
8762 (re-search-forward
8763 (regexp-quote (format org-coderef-label-format label))
8764 nil t))))
8765 (when label (message "Label exists already") (sit-for 2))
8766 (setq label (read-string "Code line label: " label)))
8767 (end-of-line 1)
8768 (setq link (format org-coderef-label-format label))
8769 (setq gc (- 79 (length link)))
8770 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8771 (insert link)
8772 (setq link (concat "(" label ")") desc nil)))
8774 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8775 ;; We are in the agenda, link to referenced location
8776 (let ((m (or (get-text-property (point) 'org-hd-marker)
8777 (get-text-property (point) 'org-marker))))
8778 (when m
8779 (org-with-point-at m
8780 (setq agenda-link
8781 (if (org-called-interactively-p 'any)
8782 (call-interactively 'org-store-link)
8783 (org-store-link nil)))))))
8785 ((eq major-mode 'calendar-mode)
8786 (let ((cd (calendar-cursor-to-date)))
8787 (setq link
8788 (format-time-string
8789 (car org-time-stamp-formats)
8790 (apply 'encode-time
8791 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8792 nil nil nil))))
8793 (org-store-link-props :type "calendar" :date cd)))
8795 ((eq major-mode 'w3-mode)
8796 (setq cpltxt (if (and (buffer-name)
8797 (not (string-match "Untitled" (buffer-name))))
8798 (buffer-name)
8799 (url-view-url t))
8800 link (org-make-link (url-view-url t)))
8801 (org-store-link-props :type "w3" :url (url-view-url t)))
8803 ((eq major-mode 'w3m-mode)
8804 (setq cpltxt (or w3m-current-title w3m-current-url)
8805 link (org-make-link w3m-current-url))
8806 (org-store-link-props :type "w3m" :url (url-view-url t)))
8808 ((setq search (run-hook-with-args-until-success
8809 'org-create-file-search-functions))
8810 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8811 "::" search))
8812 (setq cpltxt (or description link)))
8814 ((eq major-mode 'image-mode)
8815 (setq cpltxt (concat "file:"
8816 (abbreviate-file-name buffer-file-name))
8817 link (org-make-link cpltxt))
8818 (org-store-link-props :type "image" :file buffer-file-name))
8820 ((eq major-mode 'dired-mode)
8821 ;; link to the file in the current line
8822 (let ((file (dired-get-filename nil t)))
8823 (setq file (if file
8824 (abbreviate-file-name
8825 (expand-file-name (dired-get-filename nil t)))
8826 ;; otherwise, no file so use current directory.
8827 default-directory))
8828 (setq cpltxt (concat "file:" file)
8829 link (org-make-link cpltxt))))
8831 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8832 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8833 (cond
8834 ((org-in-regexp "<<\\(.*?\\)>>")
8835 (setq cpltxt
8836 (concat "file:"
8837 (abbreviate-file-name
8838 (buffer-file-name (buffer-base-buffer)))
8839 "::" (match-string 1))
8840 link (org-make-link cpltxt)))
8841 ((and (featurep 'org-id)
8842 (or (eq org-link-to-org-use-id t)
8843 (and (eq org-link-to-org-use-id 'create-if-interactive)
8844 (org-called-interactively-p 'any))
8845 (and (eq org-link-to-org-use-id
8846 'create-if-interactive-and-no-custom-id)
8847 (org-called-interactively-p 'any)
8848 (not custom-id))
8849 (and org-link-to-org-use-id
8850 (org-entry-get nil "ID"))))
8851 ;; We can make a link using the ID.
8852 (setq link (condition-case nil
8853 (prog1 (org-id-store-link)
8854 (setq desc (plist-get org-store-link-plist
8855 :description)))
8856 (error
8857 ;; probably before first headline, link to file only
8858 (concat "file:"
8859 (abbreviate-file-name
8860 (buffer-file-name (buffer-base-buffer))))))))
8862 ;; Just link to current headline
8863 (setq cpltxt (concat "file:"
8864 (abbreviate-file-name
8865 (buffer-file-name (buffer-base-buffer)))))
8866 ;; Add a context search string
8867 (when (org-xor org-context-in-file-links arg)
8868 (setq txt (cond
8869 ((org-at-heading-p) nil)
8870 ((org-region-active-p)
8871 (buffer-substring (region-beginning) (region-end)))
8872 (t nil)))
8873 (when (or (null txt) (string-match "\\S-" txt))
8874 (setq cpltxt
8875 (concat cpltxt "::"
8876 (condition-case nil
8877 (org-make-org-heading-search-string txt)
8878 (error "")))
8879 desc (or (nth 4 (ignore-errors
8880 (org-heading-components))) "NONE"))))
8881 (if (string-match "::\\'" cpltxt)
8882 (setq cpltxt (substring cpltxt 0 -2)))
8883 (setq link (org-make-link cpltxt)))))
8885 ((buffer-file-name (buffer-base-buffer))
8886 ;; Just link to this file here.
8887 (setq cpltxt (concat "file:"
8888 (abbreviate-file-name
8889 (buffer-file-name (buffer-base-buffer)))))
8890 ;; Add a context string
8891 (when (org-xor org-context-in-file-links arg)
8892 (setq txt (if (org-region-active-p)
8893 (buffer-substring (region-beginning) (region-end))
8894 (buffer-substring (point-at-bol) (point-at-eol))))
8895 ;; Only use search option if there is some text.
8896 (when (string-match "\\S-" txt)
8897 (setq cpltxt
8898 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8899 desc "NONE")))
8900 (setq link (org-make-link cpltxt)))
8902 ((org-called-interactively-p 'interactive)
8903 (error "Cannot link to a buffer which is not visiting a file"))
8905 (t (setq link nil)))
8907 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8908 (setq link (or link cpltxt)
8909 desc (or desc cpltxt))
8910 (if (equal desc "NONE") (setq desc nil))
8912 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8913 (progn
8914 (setq org-stored-links
8915 (cons (list link desc) org-stored-links))
8916 (message "Stored: %s" (or desc link))
8917 (when custom-id
8918 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8919 "::#" custom-id))
8920 (setq org-stored-links
8921 (cons (list link desc) org-stored-links))))
8922 (or agenda-link (and link (org-make-link-string link desc)))))))
8924 (defun org-store-link-props (&rest plist)
8925 "Store link properties, extract names and addresses."
8926 (let (x adr)
8927 (when (setq x (plist-get plist :from))
8928 (setq adr (mail-extract-address-components x))
8929 (setq plist (plist-put plist :fromname (car adr)))
8930 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8931 (when (setq x (plist-get plist :to))
8932 (setq adr (mail-extract-address-components x))
8933 (setq plist (plist-put plist :toname (car adr)))
8934 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8935 (let ((from (plist-get plist :from))
8936 (to (plist-get plist :to)))
8937 (when (and from to org-from-is-user-regexp)
8938 (setq plist
8939 (plist-put plist :fromto
8940 (if (string-match org-from-is-user-regexp from)
8941 (concat "to %t")
8942 (concat "from %f"))))))
8943 (setq org-store-link-plist plist))
8945 (defun org-add-link-props (&rest plist)
8946 "Add these properties to the link property list."
8947 (let (key value)
8948 (while plist
8949 (setq key (pop plist) value (pop plist))
8950 (setq org-store-link-plist
8951 (plist-put org-store-link-plist key value)))))
8953 (defun org-email-link-description (&optional fmt)
8954 "Return the description part of an email link.
8955 This takes information from `org-store-link-plist' and formats it
8956 according to FMT (default from `org-email-link-description-format')."
8957 (setq fmt (or fmt org-email-link-description-format))
8958 (let* ((p org-store-link-plist)
8959 (to (plist-get p :toaddress))
8960 (from (plist-get p :fromaddress))
8961 (table
8962 (list
8963 (cons "%c" (plist-get p :fromto))
8964 (cons "%F" (plist-get p :from))
8965 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8966 (cons "%T" (plist-get p :to))
8967 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8968 (cons "%s" (plist-get p :subject))
8969 (cons "%d" (plist-get p :date))
8970 (cons "%m" (plist-get p :message-id)))))
8971 (when (string-match "%c" fmt)
8972 ;; Check if the user wrote this message
8973 (if (and org-from-is-user-regexp from to
8974 (save-match-data (string-match org-from-is-user-regexp from)))
8975 (setq fmt (replace-match "to %t" t t fmt))
8976 (setq fmt (replace-match "from %f" t t fmt))))
8977 (org-replace-escapes fmt table)))
8979 (defun org-make-org-heading-search-string (&optional string heading)
8980 "Make search string for STRING or current headline."
8981 (interactive)
8982 (let ((s (or string (org-get-heading)))
8983 (lines org-context-in-file-links))
8984 (unless (and string (not heading))
8985 ;; We are using a headline, clean up garbage in there.
8986 (if (string-match org-todo-regexp s)
8987 (setq s (replace-match "" t t s)))
8988 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8989 (setq s (replace-match "" t t s)))
8990 (setq s (org-trim s))
8991 (if (string-match (concat "^\\(" org-quote-string "\\|"
8992 org-comment-string "\\)") s)
8993 (setq s (replace-match "" t t s)))
8994 (while (string-match org-ts-regexp s)
8995 (setq s (replace-match "" t t s))))
8996 (or string (setq s (concat "*" s))) ; Add * for headlines
8997 (when (and string (integerp lines) (> lines 0))
8998 (let ((slines (org-split-string s "\n")))
8999 (when (< lines (length slines))
9000 (setq s (mapconcat
9001 'identity
9002 (reverse (nthcdr (- (length slines) lines)
9003 (reverse slines))) "\n")))))
9004 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9006 (defun org-make-link (&rest strings)
9007 "Concatenate STRINGS."
9008 (apply 'concat strings))
9010 (defun org-make-link-string (link &optional description)
9011 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9012 (unless (string-match "\\S-" link)
9013 (error "Empty link"))
9014 (when (and description
9015 (stringp description)
9016 (not (string-match "\\S-" description)))
9017 (setq description nil))
9018 (when (stringp description)
9019 ;; Remove brackets from the description, they are fatal.
9020 (while (string-match "\\[" description)
9021 (setq description (replace-match "{" t t description)))
9022 (while (string-match "\\]" description)
9023 (setq description (replace-match "}" t t description))))
9024 (when (equal link description)
9025 ;; No description needed, it is identical
9026 (setq description nil))
9027 (when (and (not description)
9028 (not (string-match (org-image-file-name-regexp) link))
9029 (not (equal link (org-link-escape link))))
9030 (setq description (org-extract-attributes link)))
9031 (setq link
9032 (cond ((string-match (org-image-file-name-regexp) link) link)
9033 ((string-match org-link-types-re link)
9034 (concat (match-string 1 link)
9035 (org-link-escape (substring link (match-end 1)))))
9036 (t (org-link-escape link))))
9037 (concat "[[" link "]"
9038 (if description (concat "[" description "]") "")
9039 "]"))
9041 (defconst org-link-escape-chars
9042 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9043 "List of characters that should be escaped in link.
9044 This is the list that is used for internal purposes.")
9046 (defvar org-url-encoding-use-url-hexify nil)
9048 (defconst org-link-escape-chars-browser
9049 '(?\ )
9050 "List of escapes for characters that are problematic in links.
9051 This is the list that is used before handing over to the browser.")
9053 (defun org-link-escape (text &optional table merge)
9054 "Return percent escaped representation of TEXT.
9055 TEXT is a string with the text to escape.
9056 Optional argument TABLE is a list with characters that should be
9057 escaped. When nil, `org-link-escape-chars' is used.
9058 If optional argument MERGE is set, merge TABLE into
9059 `org-link-escape-chars'."
9060 (if (and org-url-encoding-use-url-hexify (not table))
9061 (url-hexify-string text)
9062 (cond
9063 ((and table merge)
9064 (mapc (lambda (defchr)
9065 (unless (member defchr table)
9066 (setq table (cons defchr table)))) org-link-escape-chars))
9067 ((null table)
9068 (setq table org-link-escape-chars)))
9069 (mapconcat
9070 (lambda (char)
9071 (if (or (member char table)
9072 (< char 32) (= char 37) (> char 126))
9073 (mapconcat (lambda (sequence-element)
9074 (format "%%%.2X" sequence-element))
9075 (or (encode-coding-char char 'utf-8)
9076 (error "Unable to percent escape character: %s"
9077 (char-to-string char))) "")
9078 (char-to-string char))) text "")))
9080 (defun org-link-unescape (str)
9081 "Unhex hexified Unicode strings as returned from the JavaScript function
9082 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9083 (unless (and (null str) (string= "" str))
9084 (let ((pos 0) (case-fold-search t) unhexed)
9085 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9086 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9087 (setq str (replace-match unhexed t t str))
9088 (setq pos (+ pos (length unhexed))))))
9089 str)
9091 (defun org-link-unescape-compound (hex)
9092 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9093 Note: this function also decodes single byte encodings like
9094 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9095 (save-match-data
9096 (let* ((bytes (cdr (split-string hex "%")))
9097 (ret "")
9098 (eat 0)
9099 (sum 0))
9100 (while bytes
9101 (let* ((val (string-to-number (pop bytes) 16))
9102 (shift-xor
9103 (if (= 0 eat)
9104 (cond
9105 ((>= val 252) (cons 6 252))
9106 ((>= val 248) (cons 5 248))
9107 ((>= val 240) (cons 4 240))
9108 ((>= val 224) (cons 3 224))
9109 ((>= val 192) (cons 2 192))
9110 (t (cons 0 0)))
9111 (cons 6 128))))
9112 (if (>= val 192) (setq eat (car shift-xor)))
9113 (setq val (logxor val (cdr shift-xor)))
9114 (setq sum (+ (lsh sum (car shift-xor)) val))
9115 (if (> eat 0) (setq eat (- eat 1)))
9116 (cond
9117 ((= 0 eat) ;multi byte
9118 (setq ret (concat ret (org-char-to-string sum)))
9119 (setq sum 0))
9120 ((not bytes) ; single byte(s)
9121 (setq ret (org-link-unescape-single-byte-sequence hex))))
9122 )) ;; end (while bytes
9123 ret )))
9125 (defun org-link-unescape-single-byte-sequence (hex)
9126 "Unhexify hex-encoded single byte character sequences."
9127 (mapconcat (lambda (byte)
9128 (char-to-string (string-to-number byte 16)))
9129 (cdr (split-string hex "%")) ""))
9131 (defun org-xor (a b)
9132 "Exclusive or."
9133 (if a (not b) b))
9135 (defun org-fixup-message-id-for-http (s)
9136 "Replace special characters in a message id, so it can be used in an http query."
9137 (when (string-match "%" s)
9138 (setq s (mapconcat (lambda (c)
9139 (if (eq c ?%)
9140 "%25"
9141 (char-to-string c)))
9142 s "")))
9143 (while (string-match "<" s)
9144 (setq s (replace-match "%3C" t t s)))
9145 (while (string-match ">" s)
9146 (setq s (replace-match "%3E" t t s)))
9147 (while (string-match "@" s)
9148 (setq s (replace-match "%40" t t s)))
9151 (defun org-link-prettify (link)
9152 "Return a human-readable representation of LINK.
9153 The car of LINK must be a raw link the cdr of LINK must be either
9154 a link description or nil."
9155 (let ((desc (or (cadr link) "<no description>")))
9156 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9157 "[[" (car link) "]]")))
9159 ;;;###autoload
9160 (defun org-insert-link-global ()
9161 "Insert a link like Org-mode does.
9162 This command can be called in any mode to insert a link in Org-mode syntax."
9163 (interactive)
9164 (org-load-modules-maybe)
9165 (org-run-like-in-org-mode 'org-insert-link))
9167 (defun org-insert-link (&optional complete-file link-location default-description)
9168 "Insert a link. At the prompt, enter the link.
9170 Completion can be used to insert any of the link protocol prefixes like
9171 http or ftp in use.
9173 The history can be used to select a link previously stored with
9174 `org-store-link'. When the empty string is entered (i.e. if you just
9175 press RET at the prompt), the link defaults to the most recently
9176 stored link. As SPC triggers completion in the minibuffer, you need to
9177 use M-SPC or C-q SPC to force the insertion of a space character.
9179 You will also be prompted for a description, and if one is given, it will
9180 be displayed in the buffer instead of the link.
9182 If there is already a link at point, this command will allow you to edit link
9183 and description parts.
9185 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9186 be selected using completion. The path to the file will be relative to the
9187 current directory if the file is in the current directory or a subdirectory.
9188 Otherwise, the link will be the absolute path as completed in the minibuffer
9189 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9190 option `org-link-file-path-type'.
9192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9193 the current directory or below.
9195 With three \\[universal-argument] prefixes, negate the meaning of
9196 `org-keep-stored-link-after-insertion'.
9198 If `org-make-link-description-function' is non-nil, this function will be
9199 called with the link target, and the result will be the default
9200 link description.
9202 If the LINK-LOCATION parameter is non-nil, this value will be
9203 used as the link location instead of reading one interactively.
9205 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9206 be used as the default description."
9207 (interactive "P")
9208 (let* ((wcf (current-window-configuration))
9209 (region (if (org-region-active-p)
9210 (buffer-substring (region-beginning) (region-end))))
9211 (remove (and region (list (region-beginning) (region-end))))
9212 (desc region)
9213 tmphist ; byte-compile incorrectly complains about this
9214 (link link-location)
9215 entry file all-prefixes)
9216 (cond
9217 (link-location) ; specified by arg, just use it.
9218 ((org-in-regexp org-bracket-link-regexp 1)
9219 ;; We do have a link at point, and we are going to edit it.
9220 (setq remove (list (match-beginning 0) (match-end 0)))
9221 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9222 (setq link (read-string "Link: "
9223 (org-link-unescape
9224 (org-match-string-no-properties 1)))))
9225 ((or (org-in-regexp org-angle-link-re)
9226 (org-in-regexp org-plain-link-re))
9227 ;; Convert to bracket link
9228 (setq remove (list (match-beginning 0) (match-end 0))
9229 link (read-string "Link: "
9230 (org-remove-angle-brackets (match-string 0)))))
9231 ((member complete-file '((4) (16)))
9232 ;; Completing read for file names.
9233 (setq link (org-file-complete-link complete-file)))
9235 ;; Read link, with completion for stored links.
9236 (with-output-to-temp-buffer "*Org Links*"
9237 (princ "Insert a link.
9238 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9239 (when org-stored-links
9240 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9241 (princ (mapconcat 'org-link-prettify
9242 (reverse org-stored-links) "\n"))))
9243 (let ((cw (selected-window)))
9244 (select-window (get-buffer-window "*Org Links*" 'visible))
9245 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9246 (unless (pos-visible-in-window-p (point-max))
9247 (org-fit-window-to-buffer))
9248 (and (window-live-p cw) (select-window cw)))
9249 ;; Fake a link history, containing the stored links.
9250 (setq tmphist (append (mapcar 'car org-stored-links)
9251 org-insert-link-history))
9252 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9253 (mapcar 'car org-link-abbrev-alist)
9254 org-link-types))
9255 (unwind-protect
9256 (progn
9257 (setq link
9258 (let ((org-completion-use-ido nil)
9259 (org-completion-use-iswitchb nil))
9260 (org-completing-read
9261 "Link: "
9262 (append
9263 (mapcar (lambda (x) (list (concat x ":")))
9264 all-prefixes)
9265 (mapcar 'car org-stored-links))
9266 nil nil nil
9267 'tmphist
9268 (car (car org-stored-links)))))
9269 (if (not (string-match "\\S-" link))
9270 (error "No link selected"))
9271 (if (or (member link all-prefixes)
9272 (and (equal ":" (substring link -1))
9273 (member (substring link 0 -1) all-prefixes)
9274 (setq link (substring link 0 -1))))
9275 (setq link (org-link-try-special-completion link))))
9276 (set-window-configuration wcf)
9277 (kill-buffer "*Org Links*"))
9278 (setq entry (assoc link org-stored-links))
9279 (or entry (push link org-insert-link-history))
9280 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9281 (not org-keep-stored-link-after-insertion))
9282 (setq org-stored-links (delq (assoc link org-stored-links)
9283 org-stored-links)))
9284 (setq desc (or desc (nth 1 entry)))))
9286 (if (string-match org-plain-link-re link)
9287 ;; URL-like link, normalize the use of angular brackets.
9288 (setq link (org-make-link (org-remove-angle-brackets link))))
9290 ;; Check if we are linking to the current file with a search option
9291 ;; If yes, simplify the link by using only the search option.
9292 (when (and buffer-file-name
9293 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9294 (let* ((path (match-string 1 link))
9295 (case-fold-search nil)
9296 (search (match-string 2 link)))
9297 (save-match-data
9298 (if (equal (file-truename buffer-file-name) (file-truename path))
9299 ;; We are linking to this same file, with a search option
9300 (setq link search)))))
9302 ;; Check if we can/should use a relative path. If yes, simplify the link
9303 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9304 (let* ((type (match-string 1 link))
9305 (path (match-string 2 link))
9306 (origpath path)
9307 (case-fold-search nil))
9308 (cond
9309 ((or (eq org-link-file-path-type 'absolute)
9310 (equal complete-file '(16)))
9311 (setq path (abbreviate-file-name (expand-file-name path))))
9312 ((eq org-link-file-path-type 'noabbrev)
9313 (setq path (expand-file-name path)))
9314 ((eq org-link-file-path-type 'relative)
9315 (setq path (file-relative-name path)))
9317 (save-match-data
9318 (if (string-match (concat "^" (regexp-quote
9319 (expand-file-name
9320 (file-name-as-directory
9321 default-directory))))
9322 (expand-file-name path))
9323 ;; We are linking a file with relative path name.
9324 (setq path (substring (expand-file-name path)
9325 (match-end 0)))
9326 (setq path (abbreviate-file-name (expand-file-name path)))))))
9327 (setq link (concat type path))
9328 (if (equal desc origpath)
9329 (setq desc path))))
9331 (if org-make-link-description-function
9332 (setq desc (funcall org-make-link-description-function link desc))
9333 (if default-description (setq desc default-description)))
9335 (setq desc (read-string "Description: " desc))
9336 (unless (string-match "\\S-" desc) (setq desc nil))
9337 (if remove (apply 'delete-region remove))
9338 (insert (org-make-link-string link desc))))
9340 (defun org-link-try-special-completion (type)
9341 "If there is completion support for link type TYPE, offer it."
9342 (let ((fun (intern (concat "org-" type "-complete-link"))))
9343 (if (functionp fun)
9344 (funcall fun)
9345 (read-string "Link (no completion support): " (concat type ":")))))
9347 (defun org-file-complete-link (&optional arg)
9348 "Create a file link using completion."
9349 (let (file link)
9350 (setq file (read-file-name "File: "))
9351 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9352 (pwd1 (file-name-as-directory (abbreviate-file-name
9353 (expand-file-name ".")))))
9354 (cond
9355 ((equal arg '(16))
9356 (setq link (org-make-link
9357 "file:"
9358 (abbreviate-file-name (expand-file-name file)))))
9359 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9360 (setq link (org-make-link "file:" (match-string 1 file))))
9361 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9362 (expand-file-name file))
9363 (setq link (org-make-link
9364 "file:" (match-string 1 (expand-file-name file)))))
9365 (t (setq link (org-make-link "file:" file)))))
9366 link))
9368 (defun org-completing-read (&rest args)
9369 "Completing-read with SPACE being a normal character."
9370 (let ((enable-recursive-minibuffers t)
9371 (minibuffer-local-completion-map
9372 (copy-keymap minibuffer-local-completion-map)))
9373 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9374 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9375 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9376 (apply 'org-icompleting-read args)))
9378 (defun org-completing-read-no-i (&rest args)
9379 (let (org-completion-use-ido org-completion-use-iswitchb)
9380 (apply 'org-completing-read args)))
9382 (defun org-iswitchb-completing-read (prompt choices &rest args)
9383 "Use iswitch as a completing-read replacement to choose from choices.
9384 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9385 from."
9386 (let* ((iswitchb-use-virtual-buffers nil)
9387 (iswitchb-make-buflist-hook
9388 (lambda ()
9389 (setq iswitchb-temp-buflist choices))))
9390 (iswitchb-read-buffer prompt)))
9392 (defun org-icompleting-read (&rest args)
9393 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9394 (org-without-partial-completion
9395 (if (and org-completion-use-ido
9396 (fboundp 'ido-completing-read)
9397 (boundp 'ido-mode) ido-mode
9398 (listp (second args)))
9399 (let ((ido-enter-matching-directory nil))
9400 (apply 'ido-completing-read (concat (car args))
9401 (if (consp (car (nth 1 args)))
9402 (mapcar 'car (nth 1 args))
9403 (nth 1 args))
9404 (cddr args)))
9405 (if (and org-completion-use-iswitchb
9406 (boundp 'iswitchb-mode) iswitchb-mode
9407 (listp (second args)))
9408 (apply 'org-iswitchb-completing-read (concat (car args))
9409 (if (consp (car (nth 1 args)))
9410 (mapcar 'car (nth 1 args))
9411 (nth 1 args))
9412 (cddr args))
9413 (apply 'completing-read args)))))
9415 (defun org-extract-attributes (s)
9416 "Extract the attributes cookie from a string and set as text property."
9417 (let (a attr (start 0) key value)
9418 (save-match-data
9419 (when (string-match "{{\\([^}]+\\)}}$" s)
9420 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9421 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9422 (setq key (match-string 1 a) value (match-string 2 a)
9423 start (match-end 0)
9424 attr (plist-put attr (intern key) value))))
9425 (org-add-props s nil 'org-attr attr))
9428 (defun org-extract-attributes-from-string (tag)
9429 (let (key value attr)
9430 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9431 (setq key (match-string 1 tag) value (match-string 2 tag)
9432 tag (replace-match "" t t tag)
9433 attr (plist-put attr (intern key) value)))
9434 (cons tag attr)))
9436 (defun org-attributes-to-string (plist)
9437 "Format a property list into an HTML attribute list."
9438 (let ((s "") key value)
9439 (while plist
9440 (setq key (pop plist) value (pop plist))
9441 (and value
9442 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9445 ;;; Opening/following a link
9447 (defvar org-link-search-failed nil)
9449 (defvar org-open-link-functions nil
9450 "Hook for functions finding a plain text link.
9451 These functions must take a single argument, the link content.
9452 They will be called for links that look like [[link text][description]]
9453 when LINK TEXT does not have a protocol like \"http:\" and does not look
9454 like a filename (e.g. \"./blue.png\").
9456 These functions will be called *before* Org attempts to resolve the
9457 link by doing text searches in the current buffer - so if you want a
9458 link \"[[target]]\" to still find \"<<target>>\", your function should
9459 handle this as a special case.
9461 When the function does handle the link, it must return a non-nil value.
9462 If it decides that it is not responsible for this link, it must return
9463 nil to indicate that that Org-mode can continue with other options
9464 like exact and fuzzy text search.")
9466 (defun org-next-link ()
9467 "Move forward to the next link.
9468 If the link is in hidden text, expose it."
9469 (interactive)
9470 (when (and org-link-search-failed (eq this-command last-command))
9471 (goto-char (point-min))
9472 (message "Link search wrapped back to beginning of buffer"))
9473 (setq org-link-search-failed nil)
9474 (let* ((pos (point))
9475 (ct (org-context))
9476 (a (assoc :link ct)))
9477 (if a (goto-char (nth 2 a)))
9478 (if (re-search-forward org-any-link-re nil t)
9479 (progn
9480 (goto-char (match-beginning 0))
9481 (if (outline-invisible-p) (org-show-context)))
9482 (goto-char pos)
9483 (setq org-link-search-failed t)
9484 (error "No further link found"))))
9486 (defun org-previous-link ()
9487 "Move backward to the previous link.
9488 If the link is in hidden text, expose it."
9489 (interactive)
9490 (when (and org-link-search-failed (eq this-command last-command))
9491 (goto-char (point-max))
9492 (message "Link search wrapped back to end of buffer"))
9493 (setq org-link-search-failed nil)
9494 (let* ((pos (point))
9495 (ct (org-context))
9496 (a (assoc :link ct)))
9497 (if a (goto-char (nth 1 a)))
9498 (if (re-search-backward org-any-link-re nil t)
9499 (progn
9500 (goto-char (match-beginning 0))
9501 (if (outline-invisible-p) (org-show-context)))
9502 (goto-char pos)
9503 (setq org-link-search-failed t)
9504 (error "No further link found"))))
9506 (defun org-translate-link (s)
9507 "Translate a link string if a translation function has been defined."
9508 (if (and org-link-translation-function
9509 (fboundp org-link-translation-function)
9510 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9511 (progn
9512 (setq s (funcall org-link-translation-function
9513 (match-string 1 s) (match-string 2 s)))
9514 (concat (car s) ":" (cdr s)))
9517 (defun org-translate-link-from-planner (type path)
9518 "Translate a link from Emacs Planner syntax so that Org can follow it.
9519 This is still an experimental function, your mileage may vary."
9520 (cond
9521 ((member type '("http" "https" "news" "ftp"))
9522 ;; standard Internet links are the same.
9523 nil)
9524 ((and (equal type "irc") (string-match "^//" path))
9525 ;; Planner has two / at the beginning of an irc link, we have 1.
9526 ;; We should have zero, actually....
9527 (setq path (substring path 1)))
9528 ((and (equal type "lisp") (string-match "^/" path))
9529 ;; Planner has a slash, we do not.
9530 (setq type "elisp" path (substring path 1)))
9531 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9532 ;; A typical message link. Planner has the id after the final slash,
9533 ;; we separate it with a hash mark
9534 (setq path (concat (match-string 1 path) "#"
9535 (org-remove-angle-brackets (match-string 2 path)))))
9537 (cons type path))
9539 (defun org-find-file-at-mouse (ev)
9540 "Open file link or URL at mouse."
9541 (interactive "e")
9542 (mouse-set-point ev)
9543 (org-open-at-point 'in-emacs))
9545 (defun org-open-at-mouse (ev)
9546 "Open file link or URL at mouse.
9547 See the docstring of `org-open-file' for details."
9548 (interactive "e")
9549 (mouse-set-point ev)
9550 (if (eq major-mode 'org-agenda-mode)
9551 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9552 (org-open-at-point))
9554 (defvar org-window-config-before-follow-link nil
9555 "The window configuration before following a link.
9556 This is saved in case the need arises to restore it.")
9558 (defvar org-open-link-marker (make-marker)
9559 "Marker pointing to the location where `org-open-at-point; was called.")
9561 ;;;###autoload
9562 (defun org-open-at-point-global ()
9563 "Follow a link like Org-mode does.
9564 This command can be called in any mode to follow a link that has
9565 Org-mode syntax."
9566 (interactive)
9567 (org-run-like-in-org-mode 'org-open-at-point))
9569 ;;;###autoload
9570 (defun org-open-link-from-string (s &optional arg reference-buffer)
9571 "Open a link in the string S, as if it was in Org-mode."
9572 (interactive "sLink: \nP")
9573 (let ((reference-buffer (or reference-buffer (current-buffer))))
9574 (with-temp-buffer
9575 (let ((org-inhibit-startup (not reference-buffer)))
9576 (org-mode)
9577 (insert s)
9578 (goto-char (point-min))
9579 (when reference-buffer
9580 (setq org-link-abbrev-alist-local
9581 (with-current-buffer reference-buffer
9582 org-link-abbrev-alist-local)))
9583 (org-open-at-point arg reference-buffer)))))
9585 (defvar org-open-at-point-functions nil
9586 "Hook that is run when following a link at point.
9588 Functions in this hook must return t if they identify and follow
9589 a link at point. If they don't find anything interesting at point,
9590 they must return nil.")
9592 (defun org-open-at-point (&optional arg reference-buffer)
9593 "Open link at or after point.
9594 If there is no link at point, this function will search forward up to
9595 the end of the current line.
9596 Normally, files will be opened by an appropriate application. If the
9597 optional prefix argument ARG is non-nil, Emacs will visit the file.
9598 With a double prefix argument, try to open outside of Emacs, in the
9599 application the system uses for this file type."
9600 (interactive "P")
9601 ;; if in a code block, then open the block's results
9602 (unless (call-interactively #'org-babel-open-src-block-result)
9603 (org-load-modules-maybe)
9604 (move-marker org-open-link-marker (point))
9605 (setq org-window-config-before-follow-link (current-window-configuration))
9606 (org-remove-occur-highlights nil nil t)
9607 (cond
9608 ((and (org-at-heading-p)
9609 (not (org-at-timestamp-p t))
9610 (not (org-in-regexp
9611 (concat org-plain-link-re "\\|"
9612 org-bracket-link-regexp "\\|"
9613 org-angle-link-re "\\|"
9614 "[ \t]:[^ \t\n]+:[ \t]*$")))
9615 (not (get-text-property (point) 'org-linked-text)))
9616 (or (org-offer-links-in-entry arg)
9617 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9618 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9619 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9620 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9621 (not (org-in-regexp org-bracket-link-regexp)))
9622 (org-footnote-action))
9624 (let (type path link line search (pos (point)))
9625 (catch 'match
9626 (save-excursion
9627 (skip-chars-forward "^]\n\r")
9628 (when (org-in-regexp org-bracket-link-regexp 1)
9629 (setq link (org-extract-attributes
9630 (org-link-unescape (org-match-string-no-properties 1))))
9631 (while (string-match " *\n *" link)
9632 (setq link (replace-match " " t t link)))
9633 (setq link (org-link-expand-abbrev link))
9634 (cond
9635 ((or (file-name-absolute-p link)
9636 (string-match "^\\.\\.?/" link))
9637 (setq type "file" path link))
9638 ((string-match org-link-re-with-space3 link)
9639 (setq type (match-string 1 link) path (match-string 2 link)))
9640 (t (setq type "thisfile" path link)))
9641 (throw 'match t)))
9643 (when (get-text-property (point) 'org-linked-text)
9644 (setq type "thisfile"
9645 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9646 (1+ (point)) (point))
9647 path (buffer-substring
9648 (or (previous-single-property-change pos 'org-linked-text)
9649 (point-min))
9650 (or (next-single-property-change pos 'org-linked-text)
9651 (point-max))))
9652 (throw 'match t))
9654 (save-excursion
9655 (when (or (org-in-regexp org-angle-link-re)
9656 (org-in-regexp org-plain-link-re))
9657 (setq type (match-string 1)
9658 path (org-link-unescape (match-string 2)))
9659 (throw 'match t)))
9660 (save-excursion
9661 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9662 (setq type "tags"
9663 path (match-string 1))
9664 (while (string-match ":" path)
9665 (setq path (replace-match "+" t t path)))
9666 (throw 'match t)))
9667 (when (org-in-regexp "<\\([^><\n]+\\)>")
9668 (setq type "tree-match"
9669 path (match-string 1))
9670 (throw 'match t)))
9671 (unless path
9672 (error "No link found"))
9674 ;; switch back to reference buffer
9675 ;; needed when if called in a temporary buffer through
9676 ;; org-open-link-from-string
9677 (with-current-buffer (or reference-buffer (current-buffer))
9679 ;; Remove any trailing spaces in path
9680 (if (string-match " +\\'" path)
9681 (setq path (replace-match "" t t path)))
9682 (if (and org-link-translation-function
9683 (fboundp org-link-translation-function))
9684 ;; Check if we need to translate the link
9685 (let ((tmp (funcall org-link-translation-function type path)))
9686 (setq type (car tmp) path (cdr tmp))))
9688 (cond
9690 ((assoc type org-link-protocols)
9691 (funcall (nth 1 (assoc type org-link-protocols)) path))
9693 ((equal type "mailto")
9694 (let ((cmd (car org-link-mailto-program))
9695 (args (cdr org-link-mailto-program)) args1
9696 (address path) (subject "") a)
9697 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9698 (setq address (match-string 1 path)
9699 subject (org-link-escape (match-string 2 path))))
9700 (while args
9701 (cond
9702 ((not (stringp (car args))) (push (pop args) args1))
9703 (t (setq a (pop args))
9704 (if (string-match "%a" a)
9705 (setq a (replace-match address t t a)))
9706 (if (string-match "%s" a)
9707 (setq a (replace-match subject t t a)))
9708 (push a args1))))
9709 (apply cmd (nreverse args1))))
9711 ((member type '("http" "https" "ftp" "news"))
9712 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9713 (org-link-escape
9714 path org-link-escape-chars-browser)
9715 path))))
9717 ((string= type "doi")
9718 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9719 (org-link-escape
9720 path org-link-escape-chars-browser)
9721 path))))
9723 ((member type '("message"))
9724 (browse-url (concat type ":" path)))
9726 ((string= type "tags")
9727 (org-tags-view arg path))
9729 ((string= type "tree-match")
9730 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9732 ((string= type "file")
9733 (if (string-match "::\\([0-9]+\\)\\'" path)
9734 (setq line (string-to-number (match-string 1 path))
9735 path (substring path 0 (match-beginning 0)))
9736 (if (string-match "::\\(.+\\)\\'" path)
9737 (setq search (match-string 1 path)
9738 path (substring path 0 (match-beginning 0)))))
9739 (if (string-match "[*?{]" (file-name-nondirectory path))
9740 (dired path)
9741 (org-open-file path arg line search)))
9743 ((string= type "shell")
9744 (let ((cmd path))
9745 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9746 (string-match org-confirm-shell-link-not-regexp cmd))
9747 (not org-confirm-shell-link-function)
9748 (funcall org-confirm-shell-link-function
9749 (format "Execute \"%s\" in shell? "
9750 (org-add-props cmd nil
9751 'face 'org-warning))))
9752 (progn
9753 (message "Executing %s" cmd)
9754 (shell-command cmd))
9755 (error "Abort"))))
9757 ((string= type "elisp")
9758 (let ((cmd path))
9759 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9760 (string-match org-confirm-elisp-link-not-regexp cmd))
9761 (not org-confirm-elisp-link-function)
9762 (funcall org-confirm-elisp-link-function
9763 (format "Execute \"%s\" as elisp? "
9764 (org-add-props cmd nil
9765 'face 'org-warning))))
9766 (message "%s => %s" cmd
9767 (if (equal (string-to-char cmd) ?\()
9768 (eval (read cmd))
9769 (call-interactively (read cmd))))
9770 (error "Abort"))))
9772 ((and (string= type "thisfile")
9773 (run-hook-with-args-until-success
9774 'org-open-link-functions path)))
9776 ((string= type "thisfile")
9777 (if arg
9778 (switch-to-buffer-other-window
9779 (org-get-buffer-for-internal-link (current-buffer)))
9780 (org-mark-ring-push))
9781 (let ((cmd `(org-link-search
9782 ,path
9783 ,(cond ((equal arg '(4)) ''occur)
9784 ((equal arg '(16)) ''org-occur)
9785 (t nil))
9786 ,pos)))
9787 (condition-case nil (let ((org-link-search-inhibit-query t))
9788 (eval cmd))
9789 (error (progn (widen) (eval cmd))))))
9792 (browse-url-at-point)))))))
9793 (move-marker org-open-link-marker nil)
9794 (run-hook-with-args 'org-follow-link-hook)))
9796 (defun org-offer-links-in-entry (&optional nth zero)
9797 "Offer links in the current entry and follow the selected link.
9798 If there is only one link, follow it immediately as well.
9799 If NTH is an integer, immediately pick the NTH link found.
9800 If ZERO is a string, check also this string for a link, and if
9801 there is one, offer it as link number zero."
9802 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9803 "\\(" org-angle-link-re "\\)\\|"
9804 "\\(" org-plain-link-re "\\)"))
9805 (cnt ?0)
9806 (in-emacs (if (integerp nth) nil nth))
9807 have-zero end links link c)
9808 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9809 (push (match-string 0 zero) links)
9810 (setq cnt (1- cnt) have-zero t))
9811 (save-excursion
9812 (org-back-to-heading t)
9813 (setq end (save-excursion (outline-next-heading) (point)))
9814 (while (re-search-forward re end t)
9815 (push (match-string 0) links))
9816 (setq links (org-uniquify (reverse links))))
9818 (cond
9819 ((null links)
9820 (message "No links"))
9821 ((equal (length links) 1)
9822 (setq link (list (car links))))
9823 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9824 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9825 (t ; we have to select a link
9826 (save-excursion
9827 (save-window-excursion
9828 (delete-other-windows)
9829 (with-output-to-temp-buffer "*Select Link*"
9830 (mapc (lambda (l)
9831 (if (not (string-match org-bracket-link-regexp l))
9832 (princ (format "[%c] %s\n" (incf cnt)
9833 (org-remove-angle-brackets l)))
9834 (if (match-end 3)
9835 (princ (format "[%c] %s (%s)\n" (incf cnt)
9836 (match-string 3 l) (match-string 1 l)))
9837 (princ (format "[%c] %s\n" (incf cnt)
9838 (match-string 1 l))))))
9839 links))
9840 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9841 (message "Select link to open, RET to open all:")
9842 (setq c (read-char-exclusive))
9843 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9844 (when (equal c ?q) (error "Abort"))
9845 (if (equal c ?\C-m)
9846 (setq link links)
9847 (setq nth (- c ?0))
9848 (if have-zero (setq nth (1+ nth)))
9849 (unless (and (integerp nth) (>= (length links) nth))
9850 (error "Invalid link selection"))
9851 (setq link (list (nth (1- nth) links))))))
9852 (if link
9853 (let ((buf (current-buffer)))
9854 (dolist (l link)
9855 (org-open-link-from-string l in-emacs buf))
9857 nil)))
9859 ;; Add special file links that specify the way of opening
9861 (org-add-link-type "file+sys" 'org-open-file-with-system)
9862 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9863 (defun org-open-file-with-system (path)
9864 "Open file at PATH using the system way of opening it."
9865 (org-open-file path 'system))
9866 (defun org-open-file-with-emacs (path)
9867 "Open file at PATH in Emacs."
9868 (org-open-file path 'emacs))
9869 (defun org-remove-file-link-modifiers ()
9870 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9871 (goto-char (point-min))
9872 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9873 (org-if-unprotected
9874 (replace-match "file:" t t))))
9875 (eval-after-load "org-exp"
9876 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9877 'org-remove-file-link-modifiers))
9879 ;;;; Time estimates
9881 (defun org-get-effort (&optional pom)
9882 "Get the effort estimate for the current entry."
9883 (org-entry-get pom org-effort-property))
9885 ;;; File search
9887 (defvar org-create-file-search-functions nil
9888 "List of functions to construct the right search string for a file link.
9889 These functions are called in turn with point at the location to
9890 which the link should point.
9892 A function in the hook should first test if it would like to
9893 handle this file type, for example by checking the `major-mode'
9894 or the file extension. If it decides not to handle this file, it
9895 should just return nil to give other functions a chance. If it
9896 does handle the file, it must return the search string to be used
9897 when following the link. The search string will be part of the
9898 file link, given after a double colon, and `org-open-at-point'
9899 will automatically search for it. If special measures must be
9900 taken to make the search successful, another function should be
9901 added to the companion hook `org-execute-file-search-functions',
9902 which see.
9904 A function in this hook may also use `setq' to set the variable
9905 `description' to provide a suggestion for the descriptive text to
9906 be used for this link when it gets inserted into an Org-mode
9907 buffer with \\[org-insert-link].")
9909 (defvar org-execute-file-search-functions nil
9910 "List of functions to execute a file search triggered by a link.
9912 Functions added to this hook must accept a single argument, the
9913 search string that was part of the file link, the part after the
9914 double colon. The function must first check if it would like to
9915 handle this search, for example by checking the `major-mode' or
9916 the file extension. If it decides not to handle this search, it
9917 should just return nil to give other functions a chance. If it
9918 does handle the search, it must return a non-nil value to keep
9919 other functions from trying.
9921 Each function can access the current prefix argument through the
9922 variable `current-prefix-argument'. Note that a single prefix is
9923 used to force opening a link in Emacs, so it may be good to only
9924 use a numeric or double prefix to guide the search function.
9926 In case this is needed, a function in this hook can also restore
9927 the window configuration before `org-open-at-point' was called using:
9929 (set-window-configuration org-window-config-before-follow-link)")
9931 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9932 (defun org-link-search (s &optional type avoid-pos stealth)
9933 "Search for a link search option.
9934 If S is surrounded by forward slashes, it is interpreted as a
9935 regular expression. In org-mode files, this will create an `org-occur'
9936 sparse tree. In ordinary files, `occur' will be used to list matches.
9937 If the current buffer is in `dired-mode', grep will be used to search
9938 in all files. If AVOID-POS is given, ignore matches near that position.
9940 When optional argument STEALTH is non-nil, do not modify
9941 visibility around point, thus ignoring
9942 `org-show-hierarchy-above', `org-show-following-heading' and
9943 `org-show-siblings' variables."
9944 (let ((case-fold-search t)
9945 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9946 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9947 (append '(("") (" ") ("\t") ("\n"))
9948 org-emphasis-alist)
9949 "\\|") "\\)"))
9950 (pos (point))
9951 (pre nil) (post nil)
9952 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9953 (cond
9954 ;; First check if there are any special search functions
9955 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9956 ;; Now try the builtin stuff
9957 ((and (equal (string-to-char s0) ?#)
9958 (> (length s0) 1)
9959 (save-excursion
9960 (goto-char (point-min))
9961 (and
9962 (re-search-forward
9963 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9964 (setq type 'dedicated
9965 pos (match-beginning 0))))
9966 ;; There is an exact target for this
9967 (goto-char pos)
9968 (org-back-to-heading t)))
9969 ((save-excursion
9970 (goto-char (point-min))
9971 (and
9972 (re-search-forward
9973 (concat "<<" (regexp-quote s0) ">>") nil t)
9974 (setq type 'dedicated
9975 pos (match-beginning 0))))
9976 ;; There is an exact target for this
9977 (goto-char pos))
9978 ((save-excursion
9979 (goto-char (point-min))
9980 (and
9981 (re-search-forward
9982 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9983 (setq type 'dedicated pos (match-beginning 0))))
9984 ;; Found an invisible target.
9985 (goto-char pos))
9986 ((save-excursion
9987 (goto-char (point-min))
9988 (and
9989 (re-search-forward
9990 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9991 (setq type 'dedicated pos (match-beginning 0))))
9992 ;; Found an element with a matching #+name affiliated keyword.
9993 (goto-char pos))
9994 ((and (string-match "^(\\(.*\\))$" s0)
9995 (save-excursion
9996 (goto-char (point-min))
9997 (and
9998 (re-search-forward
9999 (concat "[^[]" (regexp-quote
10000 (format org-coderef-label-format
10001 (match-string 1 s0))))
10002 nil t)
10003 (setq type 'dedicated
10004 pos (1+ (match-beginning 0))))))
10005 ;; There is a coderef target for this
10006 (goto-char pos))
10007 ((string-match "^/\\(.*\\)/$" s)
10008 ;; A regular expression
10009 (cond
10010 ((derived-mode-p 'org-mode)
10011 (org-occur (match-string 1 s)))
10012 ;;((eq major-mode 'dired-mode)
10013 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10014 (t (org-do-occur (match-string 1 s)))))
10015 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10016 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10017 (goto-char (point-min))
10018 (cond
10019 ((let (case-fold-search)
10020 (re-search-forward (format org-complex-heading-regexp-format
10021 (regexp-quote s))
10022 nil t))
10023 ;; OK, found a match
10024 (setq type 'dedicated)
10025 (goto-char (match-beginning 0)))
10026 ((and (not org-link-search-inhibit-query)
10027 (eq org-link-search-must-match-exact-headline 'query-to-create)
10028 (y-or-n-p "No match - create this as a new heading? "))
10029 (goto-char (point-max))
10030 (or (bolp) (newline))
10031 (insert "* " s "\n")
10032 (beginning-of-line 0))
10034 (goto-char pos)
10035 (error "No match"))))
10037 ;; A normal search string
10038 (when (equal (string-to-char s) ?*)
10039 ;; Anchor on headlines, post may include tags.
10040 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10041 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10042 s (substring s 1)))
10043 (remove-text-properties
10044 0 (length s)
10045 '(face nil mouse-face nil keymap nil fontified nil) s)
10046 ;; Make a series of regular expressions to find a match
10047 (setq words (org-split-string s "[ \n\r\t]+")
10049 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10050 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10051 "\\)" markers)
10052 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10053 re2a (concat "[ \t\r\n]" re2a_)
10054 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10055 re4 (concat "[^a-zA-Z_]" re4_)
10057 re1 (concat pre re2 post)
10058 re3 (concat pre (if pre re4_ re4) post)
10059 re5 (concat pre ".*" re4)
10060 re2 (concat pre re2)
10061 re2a (concat pre (if pre re2a_ re2a))
10062 re4 (concat pre (if pre re4_ re4))
10063 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10064 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10065 re5 "\\)"
10067 (cond
10068 ((eq type 'org-occur) (org-occur reall))
10069 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10070 (t (goto-char (point-min))
10071 (setq type 'fuzzy)
10072 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10073 (org-search-not-self 1 re1 nil t)
10074 (org-search-not-self 1 re2 nil t)
10075 (org-search-not-self 1 re2a nil t)
10076 (org-search-not-self 1 re3 nil t)
10077 (org-search-not-self 1 re4 nil t)
10078 (org-search-not-self 1 re5 nil t)
10080 (goto-char (match-beginning 1))
10081 (goto-char pos)
10082 (error "No match"))))))
10083 (and (derived-mode-p 'org-mode)
10084 (not stealth)
10085 (org-show-context 'link-search))
10086 type))
10088 (defun org-search-not-self (group &rest args)
10089 "Execute `re-search-forward', but only accept matches that do not
10090 enclose the position of `org-open-link-marker'."
10091 (let ((m org-open-link-marker))
10092 (catch 'exit
10093 (while (apply 're-search-forward args)
10094 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10095 (goto-char (match-end group))
10096 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10097 (> (match-beginning 0) (marker-position m))
10098 (< (match-end 0) (marker-position m)))
10099 (save-match-data
10100 (or (not (org-in-regexp
10101 org-bracket-link-analytic-regexp 1))
10102 (not (match-end 4)) ; no description
10103 (and (<= (match-beginning 4) (point))
10104 (>= (match-end 4) (point))))))
10105 (throw 'exit (point))))))))
10107 (defun org-get-buffer-for-internal-link (buffer)
10108 "Return a buffer to be used for displaying the link target of internal links."
10109 (cond
10110 ((not org-display-internal-link-with-indirect-buffer)
10111 buffer)
10112 ((string-match "(Clone)$" (buffer-name buffer))
10113 (message "Buffer is already a clone, not making another one")
10114 ;; we also do not modify visibility in this case
10115 buffer)
10116 (t ; make a new indirect buffer for displaying the link
10117 (let* ((bn (buffer-name buffer))
10118 (ibn (concat bn "(Clone)"))
10119 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10120 (with-current-buffer ib (org-overview))
10121 ib))))
10123 (defun org-do-occur (regexp &optional cleanup)
10124 "Call the Emacs command `occur'.
10125 If CLEANUP is non-nil, remove the printout of the regular expression
10126 in the *Occur* buffer. This is useful if the regex is long and not useful
10127 to read."
10128 (occur regexp)
10129 (when cleanup
10130 (let ((cwin (selected-window)) win beg end)
10131 (when (setq win (get-buffer-window "*Occur*"))
10132 (select-window win))
10133 (goto-char (point-min))
10134 (when (re-search-forward "match[a-z]+" nil t)
10135 (setq beg (match-end 0))
10136 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10137 (setq end (1- (match-beginning 0)))))
10138 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10139 (goto-char (point-min))
10140 (select-window cwin))))
10142 ;;; The mark ring for links jumps
10144 (defvar org-mark-ring nil
10145 "Mark ring for positions before jumps in Org-mode.")
10146 (defvar org-mark-ring-last-goto nil
10147 "Last position in the mark ring used to go back.")
10148 ;; Fill and close the ring
10149 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10150 (loop for i from 1 to org-mark-ring-length do
10151 (push (make-marker) org-mark-ring))
10152 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10153 org-mark-ring)
10155 (defun org-mark-ring-push (&optional pos buffer)
10156 "Put the current position or POS into the mark ring and rotate it."
10157 (interactive)
10158 (setq pos (or pos (point)))
10159 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10160 (move-marker (car org-mark-ring)
10161 (or pos (point))
10162 (or buffer (current-buffer)))
10163 (message "%s"
10164 (substitute-command-keys
10165 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10167 (defun org-mark-ring-goto (&optional n)
10168 "Jump to the previous position in the mark ring.
10169 With prefix arg N, jump back that many stored positions. When
10170 called several times in succession, walk through the entire ring.
10171 Org-mode commands jumping to a different position in the current file,
10172 or to another Org-mode file, automatically push the old position
10173 onto the ring."
10174 (interactive "p")
10175 (let (p m)
10176 (if (eq last-command this-command)
10177 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10178 (setq p org-mark-ring))
10179 (setq org-mark-ring-last-goto p)
10180 (setq m (car p))
10181 (org-pop-to-buffer-same-window (marker-buffer m))
10182 (goto-char m)
10183 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10185 (defun org-remove-angle-brackets (s)
10186 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10187 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10189 (defun org-add-angle-brackets (s)
10190 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10191 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10193 (defun org-remove-double-quotes (s)
10194 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10195 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10198 ;;; Following specific links
10200 (defun org-follow-timestamp-link ()
10201 (cond
10202 ((org-at-date-range-p t)
10203 (let ((org-agenda-start-on-weekday)
10204 (t1 (match-string 1))
10205 (t2 (match-string 2)))
10206 (setq t1 (time-to-days (org-time-string-to-time t1))
10207 t2 (time-to-days (org-time-string-to-time t2)))
10208 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10209 ((org-at-timestamp-p t)
10210 (org-agenda-list nil (time-to-days (org-time-string-to-time
10211 (substring (match-string 1) 0 10)))
10213 (t (error "This should not happen"))))
10216 ;;; Following file links
10217 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10218 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10219 (declare-function mailcap-mime-info
10220 "mailcap" (string &optional request no-decode))
10221 (defvar org-wait nil)
10222 (defun org-open-file (path &optional in-emacs line search)
10223 "Open the file at PATH.
10224 First, this expands any special file name abbreviations. Then the
10225 configuration variable `org-file-apps' is checked if it contains an
10226 entry for this file type, and if yes, the corresponding command is launched.
10228 If no application is found, Emacs simply visits the file.
10230 With optional prefix argument IN-EMACS, Emacs will visit the file.
10231 With a double \\[universal-argument] \\[universal-argument] \
10232 prefix arg, Org tries to avoid opening in Emacs
10233 and to use an external application to visit the file.
10235 Optional LINE specifies a line to go to, optional SEARCH a string
10236 to search for. If LINE or SEARCH is given, the file will be
10237 opened in Emacs, unless an entry from org-file-apps that makes
10238 use of groups in a regexp matches.
10240 If you want to change the way frames are used when following a
10241 link, please customize `org-link-frame-setup'.
10243 If the file does not exist, an error is thrown."
10244 (let* ((file (if (equal path "")
10245 buffer-file-name
10246 (substitute-in-file-name (expand-file-name path))))
10247 (file-apps (append org-file-apps (org-default-apps)))
10248 (apps (org-remove-if
10249 'org-file-apps-entry-match-against-dlink-p file-apps))
10250 (apps-dlink (org-remove-if-not
10251 'org-file-apps-entry-match-against-dlink-p file-apps))
10252 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10253 (dirp (if remp nil (file-directory-p file)))
10254 (file (if (and dirp org-open-directory-means-index-dot-org)
10255 (concat (file-name-as-directory file) "index.org")
10256 file))
10257 (a-m-a-p (assq 'auto-mode apps))
10258 (dfile (downcase file))
10259 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10260 (link (cond ((and (eq line nil)
10261 (eq search nil))
10262 file)
10263 (line
10264 (concat file "::" (number-to-string line)))
10265 (search
10266 (concat file "::" search))))
10267 (dlink (downcase link))
10268 (old-buffer (current-buffer))
10269 (old-pos (point))
10270 (old-mode major-mode)
10271 ext cmd link-match-data)
10272 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10273 (setq ext (match-string 1 dfile))
10274 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10275 (setq ext (match-string 1 dfile))))
10276 (cond
10277 ((member in-emacs '((16) system))
10278 (setq cmd (cdr (assoc 'system apps))))
10279 (in-emacs (setq cmd 'emacs))
10281 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10282 (and dirp (cdr (assoc 'directory apps)))
10283 ; first, try matching against apps-dlink
10284 ; if we get a match here, store the match data for later
10285 (let ((match (assoc-default dlink apps-dlink
10286 'string-match)))
10287 (if match
10288 (progn (setq link-match-data (match-data))
10289 match)
10290 (progn (setq in-emacs (or in-emacs line search))
10291 nil))) ; if we have no match in apps-dlink,
10292 ; always open the file in emacs if line or search
10293 ; is given (for backwards compatibility)
10294 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10295 'string-match)
10296 (cdr (assoc ext apps))
10297 (cdr (assoc t apps))))))
10298 (when (eq cmd 'system)
10299 (setq cmd (cdr (assoc 'system apps))))
10300 (when (eq cmd 'default)
10301 (setq cmd (cdr (assoc t apps))))
10302 (when (eq cmd 'mailcap)
10303 (require 'mailcap)
10304 (mailcap-parse-mailcaps)
10305 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10306 (command (mailcap-mime-info mime-type)))
10307 (if (stringp command)
10308 (setq cmd command)
10309 (setq cmd 'emacs))))
10310 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10311 (not (file-exists-p file))
10312 (not org-open-non-existing-files))
10313 (error "No such file: %s" file))
10314 (cond
10315 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10316 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10317 (while (string-match "['\"]%s['\"]" cmd)
10318 (setq cmd (replace-match "%s" t t cmd)))
10319 (while (string-match "%s" cmd)
10320 (setq cmd (replace-match
10321 (save-match-data
10322 (shell-quote-argument
10323 (convert-standard-filename file)))
10324 t t cmd)))
10326 ;; Replace "%1", "%2" etc. in command with group matches from regex
10327 (save-match-data
10328 (let ((match-index 1)
10329 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10330 (set-match-data link-match-data)
10331 (while (<= match-index number-of-groups)
10332 (let ((regex (concat "%" (number-to-string match-index)))
10333 (replace-with (match-string match-index dlink)))
10334 (while (string-match regex cmd)
10335 (setq cmd (replace-match replace-with t t cmd))))
10336 (setq match-index (+ match-index 1)))))
10338 (save-window-excursion
10339 (start-process-shell-command cmd nil cmd)
10340 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10342 ((or (stringp cmd)
10343 (eq cmd 'emacs))
10344 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10345 (widen)
10346 (if line (org-goto-line line)
10347 (if search (org-link-search search))))
10348 ((consp cmd)
10349 (let ((file (convert-standard-filename file)))
10350 (save-match-data
10351 (set-match-data link-match-data)
10352 (eval cmd))))
10353 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10354 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10355 (or (not (equal old-buffer (current-buffer)))
10356 (not (equal old-pos (point))))
10357 (org-mark-ring-push old-pos old-buffer))))
10359 (defun org-file-apps-entry-match-against-dlink-p (entry)
10360 "This function returns non-nil if `entry' uses a regular
10361 expression which should be matched against the whole link by
10362 org-open-file.
10364 It assumes that is the case when the entry uses a regular
10365 expression which has at least one grouping construct and the
10366 action is either a lisp form or a command string containing
10367 '%1', i.e. using at least one subexpression match as a
10368 parameter."
10369 (let ((selector (car entry))
10370 (action (cdr entry)))
10371 (if (stringp selector)
10372 (and (> (regexp-opt-depth selector) 0)
10373 (or (and (stringp action)
10374 (string-match "%[0-9]" action))
10375 (consp action)))
10376 nil)))
10378 (defun org-default-apps ()
10379 "Return the default applications for this operating system."
10380 (cond
10381 ((eq system-type 'darwin)
10382 org-file-apps-defaults-macosx)
10383 ((eq system-type 'windows-nt)
10384 org-file-apps-defaults-windowsnt)
10385 (t org-file-apps-defaults-gnu)))
10387 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10388 "Convert extensions to regular expressions in the cars of LIST.
10389 Also, weed out any non-string entries, because the return value is used
10390 only for regexp matching.
10391 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10392 point to the symbol `emacs', indicating that the file should
10393 be opened in Emacs."
10394 (append
10395 (delq nil
10396 (mapcar (lambda (x)
10397 (if (not (stringp (car x)))
10399 (if (string-match "\\W" (car x))
10401 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10402 list))
10403 (if add-auto-mode
10404 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10406 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10407 (defun org-file-remote-p (file)
10408 "Test whether FILE specifies a location on a remote system.
10409 Return non-nil if the location is indeed remote.
10411 For example, the filename \"/user@host:/foo\" specifies a location
10412 on the system \"/user@host:\"."
10413 (cond ((fboundp 'file-remote-p)
10414 (file-remote-p file))
10415 ((fboundp 'tramp-handle-file-remote-p)
10416 (tramp-handle-file-remote-p file))
10417 ((and (boundp 'ange-ftp-name-format)
10418 (string-match (car ange-ftp-name-format) file))
10420 (t nil)))
10423 ;;;; Refiling
10425 (defun org-get-org-file ()
10426 "Read a filename, with default directory `org-directory'."
10427 (let ((default (or org-default-notes-file remember-data-file)))
10428 (read-file-name (format "File name [%s]: " default)
10429 (file-name-as-directory org-directory)
10430 default)))
10432 (defun org-notes-order-reversed-p ()
10433 "Check if the current file should receive notes in reversed order."
10434 (cond
10435 ((not org-reverse-note-order) nil)
10436 ((eq t org-reverse-note-order) t)
10437 ((not (listp org-reverse-note-order)) nil)
10438 (t (catch 'exit
10439 (let ((all org-reverse-note-order)
10440 entry)
10441 (while (setq entry (pop all))
10442 (if (string-match (car entry) buffer-file-name)
10443 (throw 'exit (cdr entry))))
10444 nil)))))
10446 (defvar org-refile-target-table nil
10447 "The list of refile targets, created by `org-refile'.")
10449 (defvar org-agenda-new-buffers nil
10450 "Buffers created to visit agenda files.")
10452 (defvar org-refile-cache nil
10453 "Cache for refile targets.")
10455 (defvar org-refile-markers nil
10456 "All the markers used for caching refile locations.")
10458 (defun org-refile-marker (pos)
10459 "Get a new refile marker, but only if caching is in use."
10460 (if (not org-refile-use-cache)
10462 (let ((m (make-marker)))
10463 (move-marker m pos)
10464 (push m org-refile-markers)
10465 m)))
10467 (defun org-refile-cache-clear ()
10468 "Clear the refile cache and disable all the markers."
10469 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10470 (setq org-refile-markers nil)
10471 (setq org-refile-cache nil)
10472 (message "Refile cache has been cleared"))
10474 (defun org-refile-cache-check-set (set)
10475 "Check if all the markers in the cache still have live buffers."
10476 (let (marker)
10477 (catch 'exit
10478 (while (and set (setq marker (nth 3 (pop set))))
10479 ;; if org-refile-use-outline-path is 'file, marker may be nil
10480 (when (and marker (null (marker-buffer marker)))
10481 (message "not found") (sit-for 3)
10482 (throw 'exit nil)))
10483 t)))
10485 (defun org-refile-cache-put (set &rest identifiers)
10486 "Push the refile targets SET into the cache, under IDENTIFIERS."
10487 (let* ((key (sha1 (prin1-to-string identifiers)))
10488 (entry (assoc key org-refile-cache)))
10489 (if entry
10490 (setcdr entry set)
10491 (push (cons key set) org-refile-cache))))
10493 (defun org-refile-cache-get (&rest identifiers)
10494 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10495 (cond
10496 ((not org-refile-cache) nil)
10497 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10499 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10500 org-refile-cache))))
10501 (and set (org-refile-cache-check-set set) set)))))
10503 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10504 "Produce a table with refile targets."
10505 (let ((case-fold-search nil)
10506 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10507 (entries (or org-refile-targets '((nil . (:level . 1)))))
10508 targets tgs txt re files f desc descre fast-path-p level pos0)
10509 (message "Getting targets...")
10510 (with-current-buffer (or default-buffer (current-buffer))
10511 (while (setq entry (pop entries))
10512 (setq files (car entry) desc (cdr entry))
10513 (setq fast-path-p nil)
10514 (cond
10515 ((null files) (setq files (list (current-buffer))))
10516 ((eq files 'org-agenda-files)
10517 (setq files (org-agenda-files 'unrestricted)))
10518 ((and (symbolp files) (fboundp files))
10519 (setq files (funcall files)))
10520 ((and (symbolp files) (boundp files))
10521 (setq files (symbol-value files))))
10522 (if (stringp files) (setq files (list files)))
10523 (cond
10524 ((eq (car desc) :tag)
10525 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10526 ((eq (car desc) :todo)
10527 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10528 ((eq (car desc) :regexp)
10529 (setq descre (cdr desc)))
10530 ((eq (car desc) :level)
10531 (setq descre (concat "^\\*\\{" (number-to-string
10532 (if org-odd-levels-only
10533 (1- (* 2 (cdr desc)))
10534 (cdr desc)))
10535 "\\}[ \t]")))
10536 ((eq (car desc) :maxlevel)
10537 (setq fast-path-p t)
10538 (setq descre (concat "^\\*\\{1," (number-to-string
10539 (if org-odd-levels-only
10540 (1- (* 2 (cdr desc)))
10541 (cdr desc)))
10542 "\\}[ \t]")))
10543 (t (error "Bad refiling target description %s" desc)))
10544 (while (setq f (pop files))
10545 (with-current-buffer
10546 (if (bufferp f) f (org-get-agenda-file-buffer f))
10548 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10549 (progn
10550 (if (bufferp f) (setq f (buffer-file-name
10551 (buffer-base-buffer f))))
10552 (setq f (and f (expand-file-name f)))
10553 (if (eq org-refile-use-outline-path 'file)
10554 (push (list (file-name-nondirectory f) f nil nil) tgs))
10555 (save-excursion
10556 (save-restriction
10557 (widen)
10558 (goto-char (point-min))
10559 (while (re-search-forward descre nil t)
10560 (goto-char (setq pos0 (point-at-bol)))
10561 (catch 'next
10562 (when org-refile-target-verify-function
10563 (save-match-data
10564 (or (funcall org-refile-target-verify-function)
10565 (throw 'next t))))
10566 (when (and (looking-at org-complex-heading-regexp)
10567 (not (member (match-string 4) excluded-entries))
10568 (match-string 4))
10569 (setq level (org-reduced-level
10570 (- (match-end 1) (match-beginning 1)))
10571 txt (org-link-display-format (match-string 4))
10572 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10573 re (format org-complex-heading-regexp-format
10574 (regexp-quote (match-string 4))))
10575 (when org-refile-use-outline-path
10576 (setq txt (mapconcat
10577 'org-protect-slash
10578 (append
10579 (if (eq org-refile-use-outline-path
10580 'file)
10581 (list (file-name-nondirectory
10582 (buffer-file-name
10583 (buffer-base-buffer))))
10584 (if (eq org-refile-use-outline-path
10585 'full-file-path)
10586 (list (buffer-file-name
10587 (buffer-base-buffer)))))
10588 (org-get-outline-path fast-path-p
10589 level txt)
10590 (list txt))
10591 "/")))
10592 (push (list txt f re (org-refile-marker (point)))
10593 tgs)))
10594 (when (= (point) pos0)
10595 ;; verification function has not moved point
10596 (goto-char (point-at-eol))))))))
10597 (when org-refile-use-cache
10598 (org-refile-cache-put tgs (buffer-file-name) descre))
10599 (setq targets (append tgs targets))
10600 ))))
10601 (message "Getting targets...done")
10602 (nreverse targets)))
10604 (defun org-protect-slash (s)
10605 (while (string-match "/" s)
10606 (setq s (replace-match "\\" t t s)))
10609 (defvar org-olpa (make-vector 20 nil))
10611 (defun org-get-outline-path (&optional fastp level heading)
10612 "Return the outline path to the current entry, as a list.
10614 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10615 routine which makes outline path derivations for an entire file,
10616 avoiding backtracing. Refile target collection makes use of that."
10617 (if fastp
10618 (progn
10619 (if (> level 19)
10620 (error "Outline path failure, more than 19 levels"))
10621 (loop for i from level upto 19 do
10622 (aset org-olpa i nil))
10623 (prog1
10624 (delq nil (append org-olpa nil))
10625 (aset org-olpa level heading)))
10626 (let (rtn case-fold-search)
10627 (save-excursion
10628 (save-restriction
10629 (widen)
10630 (while (org-up-heading-safe)
10631 (when (looking-at org-complex-heading-regexp)
10632 (push (org-match-string-no-properties 4) rtn)))
10633 rtn)))))
10635 (defun org-format-outline-path (path &optional width prefix)
10636 "Format the outline path PATH for display.
10637 Width is the maximum number of characters that is available.
10638 Prefix is a prefix to be included in the returned string,
10639 such as the file name."
10640 (setq width (or width 79))
10641 (if prefix (setq width (- width (length prefix))))
10642 (if (not path)
10643 (or prefix "")
10644 (let* ((nsteps (length path))
10645 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10646 (maxwidth (if (<= total-width width)
10647 10000 ;; everything fits
10648 ;; we need to shorten the level headings
10649 (/ (- width nsteps) nsteps)))
10650 (org-odd-levels-only nil)
10651 (n 0)
10652 (total (1+ (length prefix))))
10653 (setq maxwidth (max maxwidth 10))
10654 (concat prefix
10655 (mapconcat
10656 (lambda (h)
10657 (setq n (1+ n))
10658 (if (and (= n nsteps) (< maxwidth 10000))
10659 (setq maxwidth (- total-width total)))
10660 (if (< (length h) maxwidth)
10661 (progn (setq total (+ total (length h) 1)) h)
10662 (setq h (substring h 0 (- maxwidth 2))
10663 total (+ total maxwidth 1))
10664 (if (string-match "[ \t]+\\'" h)
10665 (setq h (substring h 0 (match-beginning 0))))
10666 (setq h (concat h "..")))
10667 (org-add-props h nil 'face
10668 (nth (% (1- n) org-n-level-faces)
10669 org-level-faces))
10671 path "/")))))
10673 (defun org-display-outline-path (&optional file current)
10674 "Display the current outline path in the echo area."
10675 (interactive "P")
10676 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10677 (case-fold-search nil)
10678 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10679 (if current (setq path (append path
10680 (save-excursion
10681 (org-back-to-heading t)
10682 (if (looking-at org-complex-heading-regexp)
10683 (list (match-string 4)))))))
10684 (message "%s"
10685 (org-format-outline-path
10686 path
10687 (1- (frame-width))
10688 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10690 (defvar org-refile-history nil
10691 "History for refiling operations.")
10693 (defvar org-after-refile-insert-hook nil
10694 "Hook run after `org-refile' has inserted its stuff at the new location.
10695 Note that this is still *before* the stuff will be removed from
10696 the *old* location.")
10698 (defvar org-capture-last-stored-marker)
10699 (defun org-refile (&optional goto default-buffer rfloc)
10700 "Move the entry or entries at point to another heading.
10701 The list of target headings is compiled using the information in
10702 `org-refile-targets', which see.
10704 At the target location, the entry is filed as a subitem of the target
10705 heading. Depending on `org-reverse-note-order', the new subitem will
10706 either be the first or the last subitem.
10708 If there is an active region, all entries in that region will be moved.
10709 However, the region must fulfill the requirement that the first heading
10710 is the first one sets the top-level of the moved text - at most siblings
10711 below it are allowed.
10713 With prefix arg GOTO, the command will only visit the target location
10714 and not actually move anything.
10716 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10717 go to the location where the last refiling operation has put the subtree.
10718 With a prefix argument of `2', refile to the running clock.
10720 RFLOC can be a refile location obtained in a different way.
10722 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10724 If you are using target caching (see `org-refile-use-cache'),
10725 you have to clear the target cache in order to find new targets.
10726 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10727 prefix argument (`C-u C-u C-u C-c C-w')."
10729 (interactive "P")
10730 (if (member goto '(0 (64)))
10731 (org-refile-cache-clear)
10732 (let* ((cbuf (current-buffer))
10733 (regionp (org-region-active-p))
10734 (region-start (and regionp (region-beginning)))
10735 (region-end (and regionp (region-end)))
10736 (region-length (and regionp (- region-end region-start)))
10737 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10738 pos it nbuf file re level reversed)
10739 (setq last-command nil)
10740 (when regionp
10741 (goto-char region-start)
10742 (or (bolp) (goto-char (point-at-bol)))
10743 (setq region-start (point))
10744 (unless (or (org-kill-is-subtree-p
10745 (buffer-substring region-start region-end))
10746 (prog1 org-refile-active-region-within-subtree
10747 (org-toggle-heading)))
10748 (error "The region is not a (sequence of) subtree(s)")))
10749 (if (equal goto '(16))
10750 (org-refile-goto-last-stored)
10751 (when (or
10752 (and (equal goto 2)
10753 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10754 (prog1
10755 (setq it (list (or org-clock-heading "running clock")
10756 (buffer-file-name
10757 (marker-buffer org-clock-hd-marker))
10759 (marker-position org-clock-hd-marker)))
10760 (setq goto nil)))
10761 (setq it (or rfloc
10762 (let (heading-text)
10763 (save-excursion
10764 (unless goto
10765 (org-back-to-heading t)
10766 (setq heading-text
10767 (nth 4 (org-heading-components))))
10768 (org-refile-get-location
10769 (cond (goto "Goto")
10770 (regionp "Refile region to")
10771 (t (concat "Refile subtree \""
10772 heading-text "\" to")))
10773 default-buffer
10774 (and (not (equal '(4) goto))
10775 org-refile-allow-creating-parent-nodes)
10776 goto))))))
10777 (setq file (nth 1 it)
10778 re (nth 2 it)
10779 pos (nth 3 it))
10780 (if (and (not goto)
10782 (equal (buffer-file-name) file)
10783 (if regionp
10784 (and (>= pos region-start)
10785 (<= pos region-end))
10786 (and (>= pos (point))
10787 (< pos (save-excursion
10788 (org-end-of-subtree t t))))))
10789 (error "Cannot refile to position inside the tree or region"))
10791 (setq nbuf (or (find-buffer-visiting file)
10792 (find-file-noselect file)))
10793 (if goto
10794 (progn
10795 (org-pop-to-buffer-same-window nbuf)
10796 (goto-char pos)
10797 (org-show-context 'org-goto))
10798 (if regionp
10799 (progn
10800 (org-kill-new (buffer-substring region-start region-end))
10801 (org-save-markers-in-region region-start region-end))
10802 (org-copy-subtree 1 nil t))
10803 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10804 (find-file-noselect file)))
10805 (setq reversed (org-notes-order-reversed-p))
10806 (save-excursion
10807 (save-restriction
10808 (widen)
10809 (if pos
10810 (progn
10811 (goto-char pos)
10812 (looking-at org-outline-regexp)
10813 (setq level (org-get-valid-level (funcall outline-level) 1))
10814 (goto-char
10815 (if reversed
10816 (or (outline-next-heading) (point-max))
10817 (or (save-excursion (org-get-next-sibling))
10818 (org-end-of-subtree t t)
10819 (point-max)))))
10820 (setq level 1)
10821 (if (not reversed)
10822 (goto-char (point-max))
10823 (goto-char (point-min))
10824 (or (outline-next-heading) (goto-char (point-max)))))
10825 (if (not (bolp)) (newline))
10826 (org-paste-subtree level)
10827 (when org-log-refile
10828 (org-add-log-setup 'refile nil nil 'findpos
10829 org-log-refile)
10830 (unless (eq org-log-refile 'note)
10831 (save-excursion (org-add-log-note))))
10832 (and org-auto-align-tags (org-set-tags nil t))
10833 (bookmark-set "org-refile-last-stored")
10834 ;; If we are refiling for capture, make sure that the
10835 ;; last-capture pointers point here
10836 (when (org-bound-and-true-p org-refile-for-capture)
10837 (bookmark-set "org-capture-last-stored-marker")
10838 (move-marker org-capture-last-stored-marker (point)))
10839 (if (fboundp 'deactivate-mark) (deactivate-mark))
10840 (run-hooks 'org-after-refile-insert-hook))))
10841 (if regionp
10842 (delete-region (point) (+ (point) region-length))
10843 (org-cut-subtree))
10844 (when (featurep 'org-inlinetask)
10845 (org-inlinetask-remove-END-maybe))
10846 (setq org-markers-to-move nil)
10847 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10849 (defun org-refile-goto-last-stored ()
10850 "Go to the location where the last refile was stored."
10851 (interactive)
10852 (bookmark-jump "org-refile-last-stored")
10853 (message "This is the location of the last refile"))
10855 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10856 no-exclude)
10857 "Prompt the user for a refile location, using PROMPT.
10858 PROMPT should not be suffixed with a colon and a space, because
10859 this function appends the default value from
10860 `org-refile-history' automatically, if that is not empty.
10861 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10862 this is used for the GOTO interface."
10863 (let ((org-refile-targets org-refile-targets)
10864 (org-refile-use-outline-path org-refile-use-outline-path)
10865 excluded-entries)
10866 (when (and (derived-mode-p 'org-mode)
10867 (not org-refile-use-cache)
10868 (not no-exclude))
10869 (org-map-tree
10870 (lambda()
10871 (setq excluded-entries
10872 (append excluded-entries (list (org-get-heading t t)))))))
10873 (setq org-refile-target-table
10874 (org-refile-get-targets default-buffer excluded-entries)))
10875 (unless org-refile-target-table
10876 (error "No refile targets"))
10877 (let* ((prompt (concat prompt
10878 (and (car org-refile-history)
10879 (concat " (default " (car org-refile-history) ")"))
10880 ": "))
10881 (cbuf (current-buffer))
10882 (partial-completion-mode nil)
10883 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10884 (cfunc (if (and org-refile-use-outline-path
10885 org-outline-path-complete-in-steps)
10886 'org-olpath-completing-read
10887 'org-icompleting-read))
10888 (extra (if org-refile-use-outline-path "/" ""))
10889 (filename (and cfn (expand-file-name cfn)))
10890 (tbl (mapcar
10891 (lambda (x)
10892 (if (and (not (member org-refile-use-outline-path
10893 '(file full-file-path)))
10894 (not (equal filename (nth 1 x))))
10895 (cons (concat (car x) extra " ("
10896 (file-name-nondirectory (nth 1 x)) ")")
10897 (cdr x))
10898 (cons (concat (car x) extra) (cdr x))))
10899 org-refile-target-table))
10900 (completion-ignore-case t)
10901 pa answ parent-target child parent old-hist)
10902 (setq old-hist org-refile-history)
10903 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10904 nil 'org-refile-history (car org-refile-history)))
10905 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10906 (org-refile-check-position pa)
10907 (if pa
10908 (progn
10909 (when (or (not org-refile-history)
10910 (not (eq old-hist org-refile-history))
10911 (not (equal (car pa) (car org-refile-history))))
10912 (setq org-refile-history
10913 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10914 org-refile-history
10915 (cdr org-refile-history))))
10916 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10917 (pop org-refile-history)))
10919 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10920 (progn
10921 (setq parent (match-string 1 answ)
10922 child (match-string 2 answ))
10923 (setq parent-target (or (assoc parent tbl)
10924 (assoc (concat parent "/") tbl)))
10925 (when (and parent-target
10926 (or (eq new-nodes t)
10927 (and (eq new-nodes 'confirm)
10928 (y-or-n-p (format "Create new node \"%s\"? "
10929 child)))))
10930 (org-refile-new-child parent-target child)))
10931 (error "Invalid target location")))))
10933 (declare-function org-string-nw-p "org-macs.el" (s))
10934 (defun org-refile-check-position (refile-pointer)
10935 "Check if the refile pointer matches the readline to which it points."
10936 (let* ((file (nth 1 refile-pointer))
10937 (re (nth 2 refile-pointer))
10938 (pos (nth 3 refile-pointer))
10939 buffer)
10940 (when (org-string-nw-p re)
10941 (setq buffer (if (markerp pos)
10942 (marker-buffer pos)
10943 (or (find-buffer-visiting file)
10944 (find-file-noselect file))))
10945 (with-current-buffer buffer
10946 (save-excursion
10947 (save-restriction
10948 (widen)
10949 (goto-char pos)
10950 (beginning-of-line 1)
10951 (unless (org-looking-at-p re)
10952 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10954 (defun org-refile-new-child (parent-target child)
10955 "Use refile target PARENT-TARGET to add new CHILD below it."
10956 (unless parent-target
10957 (error "Cannot find parent for new node"))
10958 (let ((file (nth 1 parent-target))
10959 (pos (nth 3 parent-target))
10960 level)
10961 (with-current-buffer (or (find-buffer-visiting file)
10962 (find-file-noselect file))
10963 (save-excursion
10964 (save-restriction
10965 (widen)
10966 (if pos
10967 (goto-char pos)
10968 (goto-char (point-max))
10969 (if (not (bolp)) (newline)))
10970 (when (looking-at org-outline-regexp)
10971 (setq level (funcall outline-level))
10972 (org-end-of-subtree t t))
10973 (org-back-over-empty-lines)
10974 (insert "\n" (make-string
10975 (if pos (org-get-valid-level level 1) 1) ?*)
10976 " " child "\n")
10977 (beginning-of-line 0)
10978 (list (concat (car parent-target) "/" child) file "" (point)))))))
10980 (defun org-olpath-completing-read (prompt collection &rest args)
10981 "Read an outline path like a file name."
10982 (let ((thetable collection)
10983 (org-completion-use-ido nil) ; does not work with ido.
10984 (org-completion-use-iswitchb nil)) ; or iswitchb
10985 (apply
10986 'org-icompleting-read prompt
10987 (lambda (string predicate &optional flag)
10988 (let (rtn r f (l (length string)))
10989 (cond
10990 ((eq flag nil)
10991 ;; try completion
10992 (try-completion string thetable))
10993 ((eq flag t)
10994 ;; all-completions
10995 (setq rtn (all-completions string thetable predicate))
10996 (mapcar
10997 (lambda (x)
10998 (setq r (substring x l))
10999 (if (string-match " ([^)]*)$" x)
11000 (setq f (match-string 0 x))
11001 (setq f ""))
11002 (if (string-match "/" r)
11003 (concat string (substring r 0 (match-end 0)) f)
11005 rtn))
11006 ((eq flag 'lambda)
11007 ;; exact match?
11008 (assoc string thetable)))))
11009 args)))
11011 ;;;; Dynamic blocks
11013 (defun org-find-dblock (name)
11014 "Find the first dynamic block with name NAME in the buffer.
11015 If not found, stay at current position and return nil."
11016 (let (pos)
11017 (save-excursion
11018 (goto-char (point-min))
11019 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11020 nil t)
11021 (match-beginning 0))))
11022 (if pos (goto-char pos))
11023 pos))
11025 (defconst org-dblock-start-re
11026 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11027 "Matches the start line of a dynamic block, with parameters.")
11029 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11030 "Matches the end of a dynamic block.")
11032 (defun org-create-dblock (plist)
11033 "Create a dynamic block section, with parameters taken from PLIST.
11034 PLIST must contain a :name entry which is used as name of the block."
11035 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11036 (end-of-line 1)
11037 (newline))
11038 (let ((col (current-column))
11039 (name (plist-get plist :name)))
11040 (insert "#+BEGIN: " name)
11041 (while plist
11042 (if (eq (car plist) :name)
11043 (setq plist (cddr plist))
11044 (insert " " (prin1-to-string (pop plist)))))
11045 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11046 (beginning-of-line -2)))
11048 (defun org-prepare-dblock ()
11049 "Prepare dynamic block for refresh.
11050 This empties the block, puts the cursor at the insert position and returns
11051 the property list including an extra property :name with the block name."
11052 (unless (looking-at org-dblock-start-re)
11053 (error "Not at a dynamic block"))
11054 (let* ((begdel (1+ (match-end 0)))
11055 (name (org-no-properties (match-string 1)))
11056 (params (append (list :name name)
11057 (read (concat "(" (match-string 3) ")")))))
11058 (save-excursion
11059 (beginning-of-line 1)
11060 (skip-chars-forward " \t")
11061 (setq params (plist-put params :indentation-column (current-column))))
11062 (unless (re-search-forward org-dblock-end-re nil t)
11063 (error "Dynamic block not terminated"))
11064 (setq params
11065 (append params
11066 (list :content (buffer-substring
11067 begdel (match-beginning 0)))))
11068 (delete-region begdel (match-beginning 0))
11069 (goto-char begdel)
11070 (open-line 1)
11071 params))
11073 (defun org-map-dblocks (&optional command)
11074 "Apply COMMAND to all dynamic blocks in the current buffer.
11075 If COMMAND is not given, use `org-update-dblock'."
11076 (let ((cmd (or command 'org-update-dblock)))
11077 (save-excursion
11078 (goto-char (point-min))
11079 (while (re-search-forward org-dblock-start-re nil t)
11080 (goto-char (match-beginning 0))
11081 (save-excursion
11082 (condition-case nil
11083 (funcall cmd)
11084 (error (message "Error during update of dynamic block"))))
11085 (unless (re-search-forward org-dblock-end-re nil t)
11086 (error "Dynamic block not terminated"))))))
11088 (defun org-dblock-update (&optional arg)
11089 "User command for updating dynamic blocks.
11090 Update the dynamic block at point. With prefix ARG, update all dynamic
11091 blocks in the buffer."
11092 (interactive "P")
11093 (if arg
11094 (org-update-all-dblocks)
11095 (or (looking-at org-dblock-start-re)
11096 (org-beginning-of-dblock))
11097 (org-update-dblock)))
11099 (defun org-update-dblock ()
11100 "Update the dynamic block at point.
11101 This means to empty the block, parse for parameters and then call
11102 the correct writing function."
11103 (interactive)
11104 (save-window-excursion
11105 (let* ((pos (point))
11106 (line (org-current-line))
11107 (params (org-prepare-dblock))
11108 (name (plist-get params :name))
11109 (indent (plist-get params :indentation-column))
11110 (cmd (intern (concat "org-dblock-write:" name))))
11111 (message "Updating dynamic block `%s' at line %d..." name line)
11112 (funcall cmd params)
11113 (message "Updating dynamic block `%s' at line %d...done" name line)
11114 (goto-char pos)
11115 (when (and indent (> indent 0))
11116 (setq indent (make-string indent ?\ ))
11117 (save-excursion
11118 (org-beginning-of-dblock)
11119 (forward-line 1)
11120 (while (not (looking-at org-dblock-end-re))
11121 (insert indent)
11122 (beginning-of-line 2))
11123 (when (looking-at org-dblock-end-re)
11124 (and (looking-at "[ \t]+")
11125 (replace-match ""))
11126 (insert indent)))))))
11128 (defun org-beginning-of-dblock ()
11129 "Find the beginning of the dynamic block at point.
11130 Error if there is no such block at point."
11131 (let ((pos (point))
11132 beg)
11133 (end-of-line 1)
11134 (if (and (re-search-backward org-dblock-start-re nil t)
11135 (setq beg (match-beginning 0))
11136 (re-search-forward org-dblock-end-re nil t)
11137 (> (match-end 0) pos))
11138 (goto-char beg)
11139 (goto-char pos)
11140 (error "Not in a dynamic block"))))
11142 ;;;###autoload
11143 (defun org-update-all-dblocks ()
11144 "Update all dynamic blocks in the buffer.
11145 This function can be used in a hook."
11146 (interactive)
11147 (when (derived-mode-p 'org-mode)
11148 (org-map-dblocks 'org-update-dblock)))
11151 ;;;; Completion
11153 (defconst org-additional-option-like-keywords
11154 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11155 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11156 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11157 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11158 "BEGIN:" "END:"
11159 "ORGTBL" "TBLFM:" "TBLNAME:"
11160 "BEGIN_EXAMPLE" "END_EXAMPLE"
11161 "BEGIN_QUOTE" "END_QUOTE"
11162 "BEGIN_VERSE" "END_VERSE"
11163 "BEGIN_CENTER" "END_CENTER"
11164 "BEGIN_SRC" "END_SRC"
11165 "BEGIN_RESULT" "END_RESULT"
11166 "NAME:" "RESULTS:"
11167 "HEADER:" "HEADERS:"
11168 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11169 "CAPTION:" "LABEL:"
11170 "SETUPFILE:"
11171 "INCLUDE:"
11172 "BIND:"
11173 "MACRO:"))
11175 (defcustom org-structure-template-alist
11177 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11178 "<src lang=\"?\">\n\n</src>")
11179 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11180 "<example>\n?\n</example>")
11181 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11182 "<quote>\n?\n</quote>")
11183 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11184 "<verse>\n?\n</verse>")
11185 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11186 "<center>\n?\n</center>")
11187 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11188 "<literal style=\"latex\">\n?\n</literal>")
11189 ("L" "#+LaTeX: "
11190 "<literal style=\"latex\">?</literal>")
11191 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11192 "<literal style=\"html\">\n?\n</literal>")
11193 ("H" "#+HTML: "
11194 "<literal style=\"html\">?</literal>")
11195 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11196 ("A" "#+ASCII: ")
11197 ("i" "#+INDEX: ?"
11198 "#+INDEX: ?")
11199 ("I" "#+INCLUDE %file ?"
11200 "<include file=%file markup=\"?\">")
11202 "Structure completion elements.
11203 This is a list of abbreviation keys and values. The value gets inserted
11204 if you type `<' followed by the key and then press the completion key,
11205 usually `M-TAB'. %file will be replaced by a file name after prompting
11206 for the file using completion. The cursor will be placed at the position
11207 of the `?` in the template.
11208 There are two templates for each key, the first uses the original Org syntax,
11209 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11210 the default when the /org-mtags.el/ module has been loaded. See also the
11211 variable `org-mtags-prefer-muse-templates'."
11212 :group 'org-completion
11213 :type '(repeat
11214 (string :tag "Key")
11215 (string :tag "Template")
11216 (string :tag "Muse Template")))
11218 (defun org-try-structure-completion ()
11219 "Try to complete a structure template before point.
11220 This looks for strings like \"<e\" on an otherwise empty line and
11221 expands them."
11222 (let ((l (buffer-substring (point-at-bol) (point)))
11224 (when (and (looking-at "[ \t]*$")
11225 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11226 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11227 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11228 (match-beginning 1)) a)
11229 t)))
11231 (defun org-complete-expand-structure-template (start cell)
11232 "Expand a structure template."
11233 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11234 (rpl (nth (if musep 2 1) cell))
11235 (ind ""))
11236 (delete-region start (point))
11237 (when (string-match "\\`#\\+" rpl)
11238 (cond
11239 ((bolp))
11240 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11241 (setq ind (buffer-substring (point-at-bol) (point))))
11242 (t (newline))))
11243 (setq start (point))
11244 (if (string-match "%file" rpl)
11245 (setq rpl (replace-match
11246 (concat
11247 "\""
11248 (save-match-data
11249 (abbreviate-file-name (read-file-name "Include file: ")))
11250 "\"")
11251 t t rpl)))
11252 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11253 (concat "\n" ind)))
11254 (insert rpl)
11255 (if (re-search-backward "\\?" start t) (delete-char 1))))
11257 ;;;; TODO, DEADLINE, Comments
11259 (defun org-toggle-comment ()
11260 "Change the COMMENT state of an entry."
11261 (interactive)
11262 (save-excursion
11263 (org-back-to-heading)
11264 (let (case-fold-search)
11265 (cond
11266 ((looking-at (format org-heading-keyword-regexp-format
11267 org-comment-string))
11268 (goto-char (match-end 1))
11269 (looking-at (concat " +" org-comment-string))
11270 (replace-match "" t t)
11271 (when (eolp) (insert " ")))
11272 ((looking-at org-outline-regexp)
11273 (goto-char (match-end 0))
11274 (insert org-comment-string " "))))))
11276 (defvar org-last-todo-state-is-todo nil
11277 "This is non-nil when the last TODO state change led to a TODO state.
11278 If the last change removed the TODO tag or switched to DONE, then
11279 this is nil.")
11281 (defvar org-setting-tags nil) ; dynamically skipped
11283 (defvar org-todo-setup-filter-hook nil
11284 "Hook for functions that pre-filter todo specs.
11285 Each function takes a todo spec and returns either nil or the spec
11286 transformed into canonical form." )
11288 (defvar org-todo-get-default-hook nil
11289 "Hook for functions that get a default item for todo.
11290 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11291 nil or a string to be used for the todo mark." )
11293 (defvar org-agenda-headline-snapshot-before-repeat)
11295 (defun org-current-effective-time ()
11296 "Return current time adjusted for `org-extend-today-until' variable"
11297 (let* ((ct (org-current-time))
11298 (dct (decode-time ct))
11299 (ct1
11300 (if (and org-use-effective-time
11301 (< (nth 2 dct) org-extend-today-until))
11302 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11303 ct)))
11304 ct1))
11306 (defun org-todo-yesterday (&optional arg)
11307 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11308 (interactive "P")
11309 (if (eq major-mode 'org-agenda-mode)
11310 (apply 'org-agenda-todo-yesterday arg)
11311 (let* ((hour (third (decode-time
11312 (org-current-time))))
11313 (org-extend-today-until (1+ hour)))
11314 (org-todo arg))))
11316 (defun org-todo (&optional arg)
11317 "Change the TODO state of an item.
11318 The state of an item is given by a keyword at the start of the heading,
11319 like
11320 *** TODO Write paper
11321 *** DONE Call mom
11323 The different keywords are specified in the variable `org-todo-keywords'.
11324 By default the available states are \"TODO\" and \"DONE\".
11325 So for this example: when the item starts with TODO, it is changed to DONE.
11326 When it starts with DONE, the DONE is removed. And when neither TODO nor
11327 DONE are present, add TODO at the beginning of the heading.
11329 With \\[universal-argument] prefix arg, use completion to determine the new \
11330 state.
11331 With numeric prefix arg, switch to that state.
11332 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11333 keywords (nextset).
11334 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11335 With a numeric prefix arg of 0, inhibit note taking for the change.
11337 For calling through lisp, arg is also interpreted in the following way:
11338 'none -> empty state
11339 \"\"(empty string) -> switch to empty state
11340 'done -> switch to DONE
11341 'nextset -> switch to the next set of keywords
11342 'previousset -> switch to the previous set of keywords
11343 \"WAITING\" -> switch to the specified keyword, but only if it
11344 really is a member of `org-todo-keywords'."
11345 (interactive "P")
11346 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11347 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11348 'region-start-level 'region))
11349 org-loop-over-headlines-in-active-region)
11350 (org-map-entries
11351 `(org-todo ,arg)
11352 org-loop-over-headlines-in-active-region
11353 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11354 (if (equal arg '(16)) (setq arg 'nextset))
11355 (let ((org-blocker-hook org-blocker-hook)
11356 (case-fold-search nil))
11357 (when (equal arg '(64))
11358 (setq arg nil org-blocker-hook nil))
11359 (when (and org-blocker-hook
11360 (or org-inhibit-blocking
11361 (org-entry-get nil "NOBLOCKING")))
11362 (setq org-blocker-hook nil))
11363 (save-excursion
11364 (catch 'exit
11365 (org-back-to-heading t)
11366 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11367 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11368 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11369 (let* ((match-data (match-data))
11370 (startpos (point-at-bol))
11371 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11372 (org-log-done org-log-done)
11373 (org-log-repeat org-log-repeat)
11374 (org-todo-log-states org-todo-log-states)
11375 (org-inhibit-logging
11376 (if (equal arg 0)
11377 (progn (setq arg nil) 'note) org-inhibit-logging))
11378 (this (match-string 1))
11379 (hl-pos (match-beginning 0))
11380 (head (org-get-todo-sequence-head this))
11381 (ass (assoc head org-todo-kwd-alist))
11382 (interpret (nth 1 ass))
11383 (done-word (nth 3 ass))
11384 (final-done-word (nth 4 ass))
11385 (org-last-state (or this ""))
11386 (completion-ignore-case t)
11387 (member (member this org-todo-keywords-1))
11388 (tail (cdr member))
11389 (org-state (cond
11390 ((and org-todo-key-trigger
11391 (or (and (equal arg '(4))
11392 (eq org-use-fast-todo-selection 'prefix))
11393 (and (not arg) org-use-fast-todo-selection
11394 (not (eq org-use-fast-todo-selection
11395 'prefix)))))
11396 ;; Use fast selection
11397 (org-fast-todo-selection))
11398 ((and (equal arg '(4))
11399 (or (not org-use-fast-todo-selection)
11400 (not org-todo-key-trigger)))
11401 ;; Read a state with completion
11402 (org-icompleting-read
11403 "State: " (mapcar (lambda(x) (list x))
11404 org-todo-keywords-1)
11405 nil t))
11406 ((eq arg 'right)
11407 (if this
11408 (if tail (car tail) nil)
11409 (car org-todo-keywords-1)))
11410 ((eq arg 'left)
11411 (if (equal member org-todo-keywords-1)
11413 (if this
11414 (nth (- (length org-todo-keywords-1)
11415 (length tail) 2)
11416 org-todo-keywords-1)
11417 (org-last org-todo-keywords-1))))
11418 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11419 (setq arg nil))) ; hack to fall back to cycling
11420 (arg
11421 ;; user or caller requests a specific state
11422 (cond
11423 ((equal arg "") nil)
11424 ((eq arg 'none) nil)
11425 ((eq arg 'done) (or done-word (car org-done-keywords)))
11426 ((eq arg 'nextset)
11427 (or (car (cdr (member head org-todo-heads)))
11428 (car org-todo-heads)))
11429 ((eq arg 'previousset)
11430 (let ((org-todo-heads (reverse org-todo-heads)))
11431 (or (car (cdr (member head org-todo-heads)))
11432 (car org-todo-heads))))
11433 ((car (member arg org-todo-keywords-1)))
11434 ((stringp arg)
11435 (error "State `%s' not valid in this file" arg))
11436 ((nth (1- (prefix-numeric-value arg))
11437 org-todo-keywords-1))))
11438 ((null member) (or head (car org-todo-keywords-1)))
11439 ((equal this final-done-word) nil) ;; -> make empty
11440 ((null tail) nil) ;; -> first entry
11441 ((memq interpret '(type priority))
11442 (if (eq this-command last-command)
11443 (car tail)
11444 (if (> (length tail) 0)
11445 (or done-word (car org-done-keywords))
11446 nil)))
11448 (car tail))))
11449 (org-state (or
11450 (run-hook-with-args-until-success
11451 'org-todo-get-default-hook org-state org-last-state)
11452 org-state))
11453 (next (if org-state (concat " " org-state " ") " "))
11454 (change-plist (list :type 'todo-state-change :from this :to org-state
11455 :position startpos))
11456 dolog now-done-p)
11457 (when org-blocker-hook
11458 (setq org-last-todo-state-is-todo
11459 (not (member this org-done-keywords)))
11460 (unless (save-excursion
11461 (save-match-data
11462 (org-with-wide-buffer
11463 (run-hook-with-args-until-failure
11464 'org-blocker-hook change-plist))))
11465 (if (org-called-interactively-p 'interactive)
11466 (error "TODO state change from %s to %s blocked" this org-state)
11467 ;; fail silently
11468 (message "TODO state change from %s to %s blocked" this org-state)
11469 (throw 'exit nil))))
11470 (store-match-data match-data)
11471 (replace-match next t t)
11472 (unless (pos-visible-in-window-p hl-pos)
11473 (message "TODO state changed to %s" (org-trim next)))
11474 (unless head
11475 (setq head (org-get-todo-sequence-head org-state)
11476 ass (assoc head org-todo-kwd-alist)
11477 interpret (nth 1 ass)
11478 done-word (nth 3 ass)
11479 final-done-word (nth 4 ass)))
11480 (when (memq arg '(nextset previousset))
11481 (message "Keyword-Set %d/%d: %s"
11482 (- (length org-todo-sets) -1
11483 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11484 (length org-todo-sets)
11485 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11486 (setq org-last-todo-state-is-todo
11487 (not (member org-state org-done-keywords)))
11488 (setq now-done-p (and (member org-state org-done-keywords)
11489 (not (member this org-done-keywords))))
11490 (and logging (org-local-logging logging))
11491 (when (and (or org-todo-log-states org-log-done)
11492 (not (eq org-inhibit-logging t))
11493 (not (memq arg '(nextset previousset))))
11494 ;; we need to look at recording a time and note
11495 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11496 (nth 2 (assoc this org-todo-log-states))))
11497 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11498 (setq dolog 'time))
11499 (when (and org-state
11500 (member org-state org-not-done-keywords)
11501 (not (member this org-not-done-keywords)))
11502 ;; This is now a todo state and was not one before
11503 ;; If there was a CLOSED time stamp, get rid of it.
11504 (org-add-planning-info nil nil 'closed))
11505 (when (and now-done-p org-log-done)
11506 ;; It is now done, and it was not done before
11507 (org-add-planning-info 'closed (org-current-effective-time))
11508 (if (and (not dolog) (eq 'note org-log-done))
11509 (org-add-log-setup 'done org-state this 'findpos 'note)))
11510 (when (and org-state dolog)
11511 ;; This is a non-nil state, and we need to log it
11512 (org-add-log-setup 'state org-state this 'findpos dolog)))
11513 ;; Fixup tag positioning
11514 (org-todo-trigger-tag-changes org-state)
11515 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11516 (when org-provide-todo-statistics
11517 (org-update-parent-todo-statistics))
11518 (run-hooks 'org-after-todo-state-change-hook)
11519 (if (and arg (not (member org-state org-done-keywords)))
11520 (setq head (org-get-todo-sequence-head org-state)))
11521 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11522 ;; Do we need to trigger a repeat?
11523 (when now-done-p
11524 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11525 ;; This is for the agenda, take a snapshot of the headline.
11526 (save-match-data
11527 (setq org-agenda-headline-snapshot-before-repeat
11528 (org-get-heading))))
11529 (org-auto-repeat-maybe org-state))
11530 ;; Fixup cursor location if close to the keyword
11531 (if (and (outline-on-heading-p)
11532 (not (bolp))
11533 (save-excursion (beginning-of-line 1)
11534 (looking-at org-todo-line-regexp))
11535 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11536 (progn
11537 (goto-char (or (match-end 2) (match-end 1)))
11538 (and (looking-at " ") (just-one-space))))
11539 (when org-trigger-hook
11540 (save-excursion
11541 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11543 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11544 "Block turning an entry into a TODO, using the hierarchy.
11545 This checks whether the current task should be blocked from state
11546 changes. Such blocking occurs when:
11548 1. The task has children which are not all in a completed state.
11550 2. A task has a parent with the property :ORDERED:, and there
11551 are siblings prior to the current task with incomplete
11552 status.
11554 3. The parent of the task is blocked because it has siblings that should
11555 be done first, or is child of a block grandparent TODO entry."
11557 (if (not org-enforce-todo-dependencies)
11558 t ; if locally turned off don't block
11559 (catch 'dont-block
11560 ;; If this is not a todo state change, or if this entry is already DONE,
11561 ;; do not block
11562 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11563 (member (plist-get change-plist :from)
11564 (cons 'done org-done-keywords))
11565 (member (plist-get change-plist :to)
11566 (cons 'todo org-not-done-keywords))
11567 (not (plist-get change-plist :to)))
11568 (throw 'dont-block t))
11569 ;; If this task has children, and any are undone, it's blocked
11570 (save-excursion
11571 (org-back-to-heading t)
11572 (let ((this-level (funcall outline-level)))
11573 (outline-next-heading)
11574 (let ((child-level (funcall outline-level)))
11575 (while (and (not (eobp))
11576 (> child-level this-level))
11577 ;; this todo has children, check whether they are all
11578 ;; completed
11579 (if (and (not (org-entry-is-done-p))
11580 (org-entry-is-todo-p))
11581 (throw 'dont-block nil))
11582 (outline-next-heading)
11583 (setq child-level (funcall outline-level))))))
11584 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11585 ;; any previous siblings are undone, it's blocked
11586 (save-excursion
11587 (org-back-to-heading t)
11588 (let* ((pos (point))
11589 (parent-pos (and (org-up-heading-safe) (point))))
11590 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11591 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11592 (forward-line 1)
11593 (re-search-forward org-not-done-heading-regexp pos t))
11594 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11595 ;; Search further up the hierarchy, to see if an ancestor is blocked
11596 (while t
11597 (goto-char parent-pos)
11598 (if (not (looking-at org-not-done-heading-regexp))
11599 (throw 'dont-block t)) ; do not block, parent is not a TODO
11600 (setq pos (point))
11601 (setq parent-pos (and (org-up-heading-safe) (point)))
11602 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11603 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11604 (forward-line 1)
11605 (re-search-forward org-not-done-heading-regexp pos t))
11606 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11608 (defcustom org-track-ordered-property-with-tag nil
11609 "Should the ORDERED property also be shown as a tag?
11610 The ORDERED property decides if an entry should require subtasks to be
11611 completed in sequence. Since a property is not very visible, setting
11612 this option means that toggling the ORDERED property with the command
11613 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11614 not relevant for the behavior, but it makes things more visible.
11616 Note that toggling the tag with tags commands will not change the property
11617 and therefore not influence behavior!
11619 This can be t, meaning the tag ORDERED should be used, It can also be a
11620 string to select a different tag for this task."
11621 :group 'org-todo
11622 :type '(choice
11623 (const :tag "No tracking" nil)
11624 (const :tag "Track with ORDERED tag" t)
11625 (string :tag "Use other tag")))
11627 (defun org-toggle-ordered-property ()
11628 "Toggle the ORDERED property of the current entry.
11629 For better visibility, you can track the value of this property with a tag.
11630 See variable `org-track-ordered-property-with-tag'."
11631 (interactive)
11632 (let* ((t1 org-track-ordered-property-with-tag)
11633 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11634 (save-excursion
11635 (org-back-to-heading)
11636 (if (org-entry-get nil "ORDERED")
11637 (progn
11638 (org-delete-property "ORDERED")
11639 (and tag (org-toggle-tag tag 'off))
11640 (message "Subtasks can be completed in arbitrary order"))
11641 (org-entry-put nil "ORDERED" "t")
11642 (and tag (org-toggle-tag tag 'on))
11643 (message "Subtasks must be completed in sequence")))))
11645 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11646 (defun org-block-todo-from-checkboxes (change-plist)
11647 "Block turning an entry into a TODO, using checkboxes.
11648 This checks whether the current task should be blocked from state
11649 changes because there are unchecked boxes in this entry."
11650 (if (not org-enforce-todo-checkbox-dependencies)
11651 t ; if locally turned off don't block
11652 (catch 'dont-block
11653 ;; If this is not a todo state change, or if this entry is already DONE,
11654 ;; do not block
11655 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11656 (member (plist-get change-plist :from)
11657 (cons 'done org-done-keywords))
11658 (member (plist-get change-plist :to)
11659 (cons 'todo org-not-done-keywords))
11660 (not (plist-get change-plist :to)))
11661 (throw 'dont-block t))
11662 ;; If this task has checkboxes that are not checked, it's blocked
11663 (save-excursion
11664 (org-back-to-heading t)
11665 (let ((beg (point)) end)
11666 (outline-next-heading)
11667 (setq end (point))
11668 (goto-char beg)
11669 (if (org-list-search-forward
11670 (concat (org-item-beginning-re)
11671 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11672 "\\[[- ]\\]")
11673 end t)
11674 (progn
11675 (if (boundp 'org-blocked-by-checkboxes)
11676 (setq org-blocked-by-checkboxes t))
11677 (throw 'dont-block nil)))))
11678 t))) ; do not block
11680 (defun org-entry-blocked-p ()
11681 "Is the current entry blocked?"
11682 (if (org-entry-get nil "NOBLOCKING")
11683 nil ;; Never block this entry
11684 (not
11685 (run-hook-with-args-until-failure
11686 'org-blocker-hook
11687 (list :type 'todo-state-change
11688 :position (point)
11689 :from 'todo
11690 :to 'done)))))
11692 (defun org-update-statistics-cookies (all)
11693 "Update the statistics cookie, either from TODO or from checkboxes.
11694 This should be called with the cursor in a line with a statistics cookie."
11695 (interactive "P")
11696 (if all
11697 (progn
11698 (org-update-checkbox-count 'all)
11699 (org-map-entries 'org-update-parent-todo-statistics))
11700 (if (not (org-at-heading-p))
11701 (org-update-checkbox-count)
11702 (let ((pos (move-marker (make-marker) (point)))
11703 end l1 l2)
11704 (ignore-errors (org-back-to-heading t))
11705 (if (not (org-at-heading-p))
11706 (org-update-checkbox-count)
11707 (setq l1 (org-outline-level))
11708 (setq end (save-excursion
11709 (outline-next-heading)
11710 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11711 (point)))
11712 (if (and (save-excursion
11713 (re-search-forward
11714 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11715 (not (save-excursion (re-search-forward
11716 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11717 (org-update-checkbox-count)
11718 (if (and l2 (> l2 l1))
11719 (progn
11720 (goto-char end)
11721 (org-update-parent-todo-statistics))
11722 (goto-char pos)
11723 (beginning-of-line 1)
11724 (while (re-search-forward
11725 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11726 (point-at-eol) t)
11727 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11728 (goto-char pos)
11729 (move-marker pos nil)))))
11731 (defvar org-entry-property-inherited-from) ;; defined below
11732 (defun org-update-parent-todo-statistics ()
11733 "Update any statistics cookie in the parent of the current headline.
11734 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11735 the entire subtree and this will travel up the hierarchy and update
11736 statistics everywhere."
11737 (let* ((prop (save-excursion (org-up-heading-safe)
11738 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11739 (recursive (or (not org-hierarchical-todo-statistics)
11740 (and prop (string-match "\\<recursive\\>" prop))))
11741 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11743 (first t)
11744 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11745 level ltoggle l1 new ndel
11746 (cnt-all 0) (cnt-done 0) is-percent kwd
11747 checkbox-beg ov ovs ove cookie-present)
11748 (catch 'exit
11749 (save-excursion
11750 (beginning-of-line 1)
11751 (setq ltoggle (funcall outline-level))
11752 ;; Three situations are to consider:
11754 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11755 ;; to the top-level ancestor on the headline;
11757 ;; 2. If parent has "recursive" property, repeat up to the
11758 ;; headline setting that property, taking inheritance into
11759 ;; account;
11761 ;; 3. Else, move up to direct parent and proceed only once.
11762 (while (and (setq level (org-up-heading-safe))
11763 (or recursive first)
11764 (>= (point) lim))
11765 (setq first nil cookie-present nil)
11766 (unless (and level
11767 (not (string-match
11768 "\\<checkbox\\>"
11769 (downcase (or (org-entry-get nil "COOKIE_DATA")
11770 "")))))
11771 (throw 'exit nil))
11772 (while (re-search-forward box-re (point-at-eol) t)
11773 (setq cnt-all 0 cnt-done 0 cookie-present t)
11774 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11775 (save-match-data
11776 (unless (outline-next-heading) (throw 'exit nil))
11777 (while (and (looking-at org-complex-heading-regexp)
11778 (> (setq l1 (length (match-string 1))) level))
11779 (setq kwd (and (or recursive (= l1 ltoggle))
11780 (match-string 2)))
11781 (if (or (eq org-provide-todo-statistics 'all-headlines)
11782 (and (listp org-provide-todo-statistics)
11783 (or (member kwd org-provide-todo-statistics)
11784 (member kwd org-done-keywords))))
11785 (setq cnt-all (1+ cnt-all))
11786 (if (eq org-provide-todo-statistics t)
11787 (and kwd (setq cnt-all (1+ cnt-all)))))
11788 (and (member kwd org-done-keywords)
11789 (setq cnt-done (1+ cnt-done)))
11790 (outline-next-heading)))
11791 (setq new
11792 (if is-percent
11793 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11794 (format "[%d/%d]" cnt-done cnt-all))
11795 ndel (- (match-end 0) checkbox-beg))
11796 ;; handle overlays when updating cookie from column view
11797 (when (setq ov (car (overlays-at checkbox-beg)))
11798 (setq ovs (overlay-start ov) ove (overlay-end ov))
11799 (delete-overlay ov))
11800 (goto-char checkbox-beg)
11801 (insert new)
11802 (delete-region (point) (+ (point) ndel))
11803 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11804 (when ov (move-overlay ov ovs ove)))
11805 (when cookie-present
11806 (run-hook-with-args 'org-after-todo-statistics-hook
11807 cnt-done (- cnt-all cnt-done))))))
11808 (run-hooks 'org-todo-statistics-hook)))
11810 (defvar org-after-todo-statistics-hook nil
11811 "Hook that is called after a TODO statistics cookie has been updated.
11812 Each function is called with two arguments: the number of not-done entries
11813 and the number of done entries.
11815 For example, the following function, when added to this hook, will switch
11816 an entry to DONE when all children are done, and back to TODO when new
11817 entries are set to a TODO status. Note that this hook is only called
11818 when there is a statistics cookie in the headline!
11820 (defun org-summary-todo (n-done n-not-done)
11821 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11822 (let (org-log-done org-log-states) ; turn off logging
11823 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11826 (defvar org-todo-statistics-hook nil
11827 "Hook that is run whenever Org thinks TODO statistics should be updated.
11828 This hook runs even if there is no statistics cookie present, in which case
11829 `org-after-todo-statistics-hook' would not run.")
11831 (defun org-todo-trigger-tag-changes (state)
11832 "Apply the changes defined in `org-todo-state-tags-triggers'."
11833 (let ((l org-todo-state-tags-triggers)
11834 changes)
11835 (when (or (not state) (equal state ""))
11836 (setq changes (append changes (cdr (assoc "" l)))))
11837 (when (and (stringp state) (> (length state) 0))
11838 (setq changes (append changes (cdr (assoc state l)))))
11839 (when (member state org-not-done-keywords)
11840 (setq changes (append changes (cdr (assoc 'todo l)))))
11841 (when (member state org-done-keywords)
11842 (setq changes (append changes (cdr (assoc 'done l)))))
11843 (dolist (c changes)
11844 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11846 (defun org-local-logging (value)
11847 "Get logging settings from a property VALUE."
11848 (let* (words w a)
11849 ;; directly set the variables, they are already local.
11850 (setq org-log-done nil
11851 org-log-repeat nil
11852 org-todo-log-states nil)
11853 (setq words (org-split-string value))
11854 (while (setq w (pop words))
11855 (cond
11856 ((setq a (assoc w org-startup-options))
11857 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11858 (set (nth 1 a) (nth 2 a))))
11859 ((setq a (org-extract-log-state-settings w))
11860 (and (member (car a) org-todo-keywords-1)
11861 (push a org-todo-log-states)))))))
11863 (defun org-get-todo-sequence-head (kwd)
11864 "Return the head of the TODO sequence to which KWD belongs.
11865 If KWD is not set, check if there is a text property remembering the
11866 right sequence."
11867 (let (p)
11868 (cond
11869 ((not kwd)
11870 (or (get-text-property (point-at-bol) 'org-todo-head)
11871 (progn
11872 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11873 nil (point-at-eol)))
11874 (get-text-property p 'org-todo-head))))
11875 ((not (member kwd org-todo-keywords-1))
11876 (car org-todo-keywords-1))
11877 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11879 (defun org-fast-todo-selection ()
11880 "Fast TODO keyword selection with single keys.
11881 Returns the new TODO keyword, or nil if no state change should occur."
11882 (let* ((fulltable org-todo-key-alist)
11883 (done-keywords org-done-keywords) ;; needed for the faces.
11884 (maxlen (apply 'max (mapcar
11885 (lambda (x)
11886 (if (stringp (car x)) (string-width (car x)) 0))
11887 fulltable)))
11888 (expert nil)
11889 (fwidth (+ maxlen 3 1 3))
11890 (ncol (/ (- (window-width) 4) fwidth))
11891 tg cnt e c tbl
11892 groups ingroup)
11893 (save-excursion
11894 (save-window-excursion
11895 (if expert
11896 (set-buffer (get-buffer-create " *Org todo*"))
11897 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11898 (erase-buffer)
11899 (org-set-local 'org-done-keywords done-keywords)
11900 (setq tbl fulltable cnt 0)
11901 (while (setq e (pop tbl))
11902 (cond
11903 ((equal e '(:startgroup))
11904 (push '() groups) (setq ingroup t)
11905 (when (not (= cnt 0))
11906 (setq cnt 0)
11907 (insert "\n"))
11908 (insert "{ "))
11909 ((equal e '(:endgroup))
11910 (setq ingroup nil cnt 0)
11911 (insert "}\n"))
11912 ((equal e '(:newline))
11913 (when (not (= cnt 0))
11914 (setq cnt 0)
11915 (insert "\n")
11916 (setq e (car tbl))
11917 (while (equal (car tbl) '(:newline))
11918 (insert "\n")
11919 (setq tbl (cdr tbl)))))
11921 (setq tg (car e) c (cdr e))
11922 (if ingroup (push tg (car groups)))
11923 (setq tg (org-add-props tg nil 'face
11924 (org-get-todo-face tg)))
11925 (if (and (= cnt 0) (not ingroup)) (insert " "))
11926 (insert "[" c "] " tg (make-string
11927 (- fwidth 4 (length tg)) ?\ ))
11928 (when (= (setq cnt (1+ cnt)) ncol)
11929 (insert "\n")
11930 (if ingroup (insert " "))
11931 (setq cnt 0)))))
11932 (insert "\n")
11933 (goto-char (point-min))
11934 (if (not expert) (org-fit-window-to-buffer))
11935 (message "[a-z..]:Set [SPC]:clear")
11936 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11937 (cond
11938 ((or (= c ?\C-g)
11939 (and (= c ?q) (not (rassoc c fulltable))))
11940 (setq quit-flag t))
11941 ((= c ?\ ) nil)
11942 ((setq e (rassoc c fulltable) tg (car e))
11944 (t (setq quit-flag t)))))))
11946 (defun org-entry-is-todo-p ()
11947 (member (org-get-todo-state) org-not-done-keywords))
11949 (defun org-entry-is-done-p ()
11950 (member (org-get-todo-state) org-done-keywords))
11952 (defun org-get-todo-state ()
11953 (save-excursion
11954 (org-back-to-heading t)
11955 (and (looking-at org-todo-line-regexp)
11956 (match-end 2)
11957 (match-string 2))))
11959 (defun org-at-date-range-p (&optional inactive-ok)
11960 "Is the cursor inside a date range?"
11961 (interactive)
11962 (save-excursion
11963 (catch 'exit
11964 (let ((pos (point)))
11965 (skip-chars-backward "^[<\r\n")
11966 (skip-chars-backward "<[")
11967 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11968 (>= (match-end 0) pos)
11969 (throw 'exit t))
11970 (skip-chars-backward "^<[\r\n")
11971 (skip-chars-backward "<[")
11972 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11973 (>= (match-end 0) pos)
11974 (throw 'exit t)))
11975 nil)))
11977 (defun org-get-repeat (&optional tagline)
11978 "Check if there is a deadline/schedule with repeater in this entry."
11979 (save-match-data
11980 (save-excursion
11981 (org-back-to-heading t)
11982 (and (re-search-forward (if tagline
11983 (concat tagline "\\s-*" org-repeat-re)
11984 org-repeat-re)
11985 (org-entry-end-position) t)
11986 (match-string-no-properties 1)))))
11988 (defvar org-last-changed-timestamp)
11989 (defvar org-last-inserted-timestamp)
11990 (defvar org-log-post-message)
11991 (defvar org-log-note-purpose)
11992 (defvar org-log-note-how)
11993 (defvar org-log-note-extra)
11994 (defun org-auto-repeat-maybe (done-word)
11995 "Check if the current headline contains a repeated deadline/schedule.
11996 If yes, set TODO state back to what it was and change the base date
11997 of repeating deadline/scheduled time stamps to new date.
11998 This function is run automatically after each state change to a DONE state."
11999 ;; last-state is dynamically scoped into this function
12000 (let* ((repeat (org-get-repeat))
12001 (aa (assoc org-last-state org-todo-kwd-alist))
12002 (interpret (nth 1 aa))
12003 (head (nth 2 aa))
12004 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12005 (msg "Entry repeats: ")
12006 (org-log-done nil)
12007 (org-todo-log-states nil)
12008 re type n what ts time to-state)
12009 (when repeat
12010 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12011 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12012 org-todo-repeat-to-state))
12013 (unless (and to-state (member to-state org-todo-keywords-1))
12014 (setq to-state (if (eq interpret 'type) org-last-state head)))
12015 (org-todo to-state)
12016 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12017 (org-entry-put nil "LAST_REPEAT" (format-time-string
12018 (org-time-stamp-format t t))))
12019 (when org-log-repeat
12020 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12021 (memq 'org-add-log-note post-command-hook))
12022 ;; OK, we are already setup for some record
12023 (if (eq org-log-repeat 'note)
12024 ;; make sure we take a note, not only a time stamp
12025 (setq org-log-note-how 'note))
12026 ;; Set up for taking a record
12027 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12028 org-last-state
12029 'findpos org-log-repeat)))
12030 (org-back-to-heading t)
12031 (org-add-planning-info nil nil 'closed)
12032 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12033 org-deadline-time-regexp "\\)\\|\\("
12034 org-ts-regexp "\\)"))
12035 (while (re-search-forward
12036 re (save-excursion (outline-next-heading) (point)) t)
12037 (setq type (if (match-end 1) org-scheduled-string
12038 (if (match-end 3) org-deadline-string "Plain:"))
12039 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12040 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12041 (setq n (string-to-number (match-string 2 ts))
12042 what (match-string 3 ts))
12043 (if (equal what "w") (setq n (* n 7) what "d"))
12044 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12045 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12046 ;; Preparation, see if we need to modify the start date for the change
12047 (when (match-end 1)
12048 (setq time (save-match-data (org-time-string-to-time ts)))
12049 (cond
12050 ((equal (match-string 1 ts) ".")
12051 ;; Shift starting date to today
12052 (org-timestamp-change
12053 (- (org-today) (time-to-days time))
12054 'day))
12055 ((equal (match-string 1 ts) "+")
12056 (let ((nshiftmax 10) (nshift 0))
12057 (while (or (= nshift 0)
12058 (<= (time-to-days time)
12059 (time-to-days (current-time))))
12060 (when (= (incf nshift) nshiftmax)
12061 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12062 (error "Abort")))
12063 (org-timestamp-change n (cdr (assoc what whata)))
12064 (org-at-timestamp-p t)
12065 (setq ts (match-string 1))
12066 (setq time (save-match-data (org-time-string-to-time ts)))))
12067 (org-timestamp-change (- n) (cdr (assoc what whata)))
12068 ;; rematch, so that we have everything in place for the real shift
12069 (org-at-timestamp-p t)
12070 (setq ts (match-string 1))
12071 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12072 (org-timestamp-change n (cdr (assoc what whata)))
12073 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12074 (setq org-log-post-message msg)
12075 (message "%s" msg))))
12077 (defun org-show-todo-tree (arg)
12078 "Make a compact tree which shows all headlines marked with TODO.
12079 The tree will show the lines where the regexp matches, and all higher
12080 headlines above the match.
12081 With a \\[universal-argument] prefix, prompt for a regexp to match.
12082 With a numeric prefix N, construct a sparse tree for the Nth element
12083 of `org-todo-keywords-1'."
12084 (interactive "P")
12085 (let ((case-fold-search nil)
12086 (kwd-re
12087 (cond ((null arg) org-not-done-regexp)
12088 ((equal arg '(4))
12089 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12090 (mapcar 'list org-todo-keywords-1))))
12091 (concat "\\("
12092 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12093 "\\)\\>")))
12094 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12095 (regexp-quote (nth (1- (prefix-numeric-value arg))
12096 org-todo-keywords-1)))
12097 (t (error "Invalid prefix argument: %s" arg)))))
12098 (message "%d TODO entries found"
12099 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12101 (defun org-deadline (&optional remove time)
12102 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12103 With argument REMOVE, remove any deadline from the item.
12104 With argument TIME, set the deadline at the corresponding date. TIME
12105 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12106 (interactive "P")
12107 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12108 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12109 'region-start-level 'region))
12110 org-loop-over-headlines-in-active-region)
12111 (org-map-entries
12112 `(org-deadline ',remove ,time)
12113 org-loop-over-headlines-in-active-region
12114 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12115 (let* ((old-date (org-entry-get nil "DEADLINE"))
12116 (repeater (and old-date
12117 (string-match
12118 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12119 old-date)
12120 (match-string 1 old-date))))
12121 (if remove
12122 (progn
12123 (when (and old-date org-log-redeadline)
12124 (org-add-log-setup 'deldeadline nil old-date 'findpos
12125 org-log-redeadline))
12126 (org-remove-timestamp-with-keyword org-deadline-string)
12127 (message "Item no longer has a deadline."))
12128 (org-add-planning-info 'deadline time 'closed)
12129 (when (and old-date org-log-redeadline
12130 (not (equal old-date
12131 (substring org-last-inserted-timestamp 1 -1))))
12132 (org-add-log-setup 'redeadline nil old-date 'findpos
12133 org-log-redeadline))
12134 (when repeater
12135 (save-excursion
12136 (org-back-to-heading t)
12137 (when (re-search-forward (concat org-deadline-string " "
12138 org-last-inserted-timestamp)
12139 (save-excursion
12140 (outline-next-heading) (point)) t)
12141 (goto-char (1- (match-end 0)))
12142 (insert " " repeater)
12143 (setq org-last-inserted-timestamp
12144 (concat (substring org-last-inserted-timestamp 0 -1)
12145 " " repeater
12146 (substring org-last-inserted-timestamp -1))))))
12147 (message "Deadline on %s" org-last-inserted-timestamp)))))
12149 (defun org-schedule (&optional remove time)
12150 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12151 With argument REMOVE, remove any scheduling date from the item.
12152 With argument TIME, scheduled at the corresponding date. TIME can
12153 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12154 (interactive "P")
12155 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12156 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12157 'region-start-level 'region))
12158 org-loop-over-headlines-in-active-region)
12159 (org-map-entries
12160 `(org-schedule ',remove ,time)
12161 org-loop-over-headlines-in-active-region
12162 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12163 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12164 (repeater (and old-date
12165 (string-match
12166 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12167 old-date)
12168 (match-string 1 old-date))))
12169 (if remove
12170 (progn
12171 (when (and old-date org-log-reschedule)
12172 (org-add-log-setup 'delschedule nil old-date 'findpos
12173 org-log-reschedule))
12174 (org-remove-timestamp-with-keyword org-scheduled-string)
12175 (message "Item is no longer scheduled."))
12176 (org-add-planning-info 'scheduled time 'closed)
12177 (when (and old-date org-log-reschedule
12178 (not (equal old-date
12179 (substring org-last-inserted-timestamp 1 -1))))
12180 (org-add-log-setup 'reschedule nil old-date 'findpos
12181 org-log-reschedule))
12182 (when repeater
12183 (save-excursion
12184 (org-back-to-heading t)
12185 (when (re-search-forward (concat org-scheduled-string " "
12186 org-last-inserted-timestamp)
12187 (save-excursion
12188 (outline-next-heading) (point)) t)
12189 (goto-char (1- (match-end 0)))
12190 (insert " " repeater)
12191 (setq org-last-inserted-timestamp
12192 (concat (substring org-last-inserted-timestamp 0 -1)
12193 " " repeater
12194 (substring org-last-inserted-timestamp -1))))))
12195 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12197 (defun org-get-scheduled-time (pom &optional inherit)
12198 "Get the scheduled time as a time tuple, of a format suitable
12199 for calling org-schedule with, or if there is no scheduling,
12200 returns nil."
12201 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12202 (when time
12203 (apply 'encode-time (org-parse-time-string time)))))
12205 (defun org-get-deadline-time (pom &optional inherit)
12206 "Get the deadline as a time tuple, of a format suitable for
12207 calling org-deadline with, or if there is no scheduling, returns
12208 nil."
12209 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12210 (when time
12211 (apply 'encode-time (org-parse-time-string time)))))
12213 (defun org-remove-timestamp-with-keyword (keyword)
12214 "Remove all time stamps with KEYWORD in the current entry."
12215 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12216 beg)
12217 (save-excursion
12218 (org-back-to-heading t)
12219 (setq beg (point))
12220 (outline-next-heading)
12221 (while (re-search-backward re beg t)
12222 (replace-match "")
12223 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12224 (equal (char-before) ?\ ))
12225 (backward-delete-char 1)
12226 (if (string-match "^[ \t]*$" (buffer-substring
12227 (point-at-bol) (point-at-eol)))
12228 (delete-region (point-at-bol)
12229 (min (point-max) (1+ (point-at-eol))))))))))
12231 (defun org-add-planning-info (what &optional time &rest remove)
12232 "Insert new timestamp with keyword in the line directly after the headline.
12233 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12234 If non is given, the user is prompted for a date.
12235 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12236 be removed."
12237 (interactive)
12238 (let (org-time-was-given org-end-time-was-given ts
12239 end default-time default-input)
12241 (catch 'exit
12242 (when (and (memq what '(scheduled deadline))
12243 (or (not time)
12244 (and (stringp time)
12245 (string-match "^[-+]+[0-9]" time))))
12246 ;; Try to get a default date/time from existing timestamp
12247 (save-excursion
12248 (org-back-to-heading t)
12249 (setq end (save-excursion (outline-next-heading) (point)))
12250 (when (re-search-forward (if (eq what 'scheduled)
12251 org-scheduled-time-regexp
12252 org-deadline-time-regexp)
12253 end t)
12254 (setq ts (match-string 1)
12255 default-time
12256 (apply 'encode-time (org-parse-time-string ts))
12257 default-input (and ts (org-get-compact-tod ts))))))
12258 (when what
12259 (setq time
12260 (if (stringp time)
12261 ;; This is a string (relative or absolute), set proper date
12262 (apply 'encode-time
12263 (org-read-date-analyze
12264 time default-time (decode-time default-time)))
12265 ;; If necessary, get the time from the user
12266 (or time (org-read-date nil 'to-time nil nil
12267 default-time default-input)))))
12269 (when (and org-insert-labeled-timestamps-at-point
12270 (member what '(scheduled deadline)))
12271 (insert
12272 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12273 (org-insert-time-stamp time org-time-was-given
12274 nil nil nil (list org-end-time-was-given))
12275 (setq what nil))
12276 (save-excursion
12277 (save-restriction
12278 (let (col list elt ts buffer-invisibility-spec)
12279 (org-back-to-heading t)
12280 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12281 (goto-char (match-end 1))
12282 (setq col (current-column))
12283 (goto-char (match-end 0))
12284 (if (eobp) (insert "\n") (forward-char 1))
12285 (when (and (not what)
12286 (not (looking-at
12287 (concat "[ \t]*"
12288 org-keyword-time-not-clock-regexp))))
12289 ;; Nothing to add, nothing to remove...... :-)
12290 (throw 'exit nil))
12291 (if (and (not (looking-at org-outline-regexp))
12292 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12293 "[^\r\n]*"))
12294 (not (equal (match-string 1) org-clock-string)))
12295 (narrow-to-region (match-beginning 0) (match-end 0))
12296 (insert-before-markers "\n")
12297 (backward-char 1)
12298 (narrow-to-region (point) (point))
12299 (and org-adapt-indentation (org-indent-to-column col)))
12300 ;; Check if we have to remove something.
12301 (setq list (cons what remove))
12302 (while list
12303 (setq elt (pop list))
12304 (when (or (and (eq elt 'scheduled)
12305 (re-search-forward org-scheduled-time-regexp nil t))
12306 (and (eq elt 'deadline)
12307 (re-search-forward org-deadline-time-regexp nil t))
12308 (and (eq elt 'closed)
12309 (re-search-forward org-closed-time-regexp nil t)))
12310 (replace-match "")
12311 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12312 (and (looking-at "[ \t]+") (replace-match ""))
12313 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12314 (when what
12315 (insert
12316 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12317 (cond ((eq what 'scheduled) org-scheduled-string)
12318 ((eq what 'deadline) org-deadline-string)
12319 ((eq what 'closed) org-closed-string))
12320 " ")
12321 (setq ts (org-insert-time-stamp
12322 time
12323 (or org-time-was-given
12324 (and (eq what 'closed) org-log-done-with-time))
12325 (eq what 'closed)
12326 nil nil (list org-end-time-was-given)))
12327 (insert
12328 (if (not (or (bolp) (eq (char-before) ?\ )
12329 (memq (char-after) '(32 10))
12330 (eobp))) " " ""))
12331 (end-of-line 1))
12332 (goto-char (point-min))
12333 (widen)
12334 (if (and (looking-at "[ \t]*\n")
12335 (equal (char-before) ?\n))
12336 (delete-region (1- (point)) (point-at-eol)))
12337 ts))))))
12339 (defvar org-log-note-marker (make-marker))
12340 (defvar org-log-note-purpose nil)
12341 (defvar org-log-note-state nil)
12342 (defvar org-log-note-previous-state nil)
12343 (defvar org-log-note-how nil)
12344 (defvar org-log-note-extra nil)
12345 (defvar org-log-note-window-configuration nil)
12346 (defvar org-log-note-return-to (make-marker))
12347 (defvar org-log-note-effective-time nil
12348 "Remembered current time so that dynamically scoped
12349 `org-extend-today-until' affects tha timestamps in state change
12350 log")
12352 (defvar org-log-post-message nil
12353 "Message to be displayed after a log note has been stored.
12354 The auto-repeater uses this.")
12356 (defun org-add-note ()
12357 "Add a note to the current entry.
12358 This is done in the same way as adding a state change note."
12359 (interactive)
12360 (org-add-log-setup 'note nil nil 'findpos nil))
12362 (defvar org-property-end-re)
12363 (defun org-add-log-setup (&optional purpose state prev-state
12364 findpos how extra)
12365 "Set up the post command hook to take a note.
12366 If this is about to TODO state change, the new state is expected in STATE.
12367 When FINDPOS is non-nil, find the correct position for the note in
12368 the current entry. If not, assume that it can be inserted at point.
12369 HOW is an indicator what kind of note should be created.
12370 EXTRA is additional text that will be inserted into the notes buffer."
12371 (let* ((org-log-into-drawer (org-log-into-drawer))
12372 (drawer (cond ((stringp org-log-into-drawer)
12373 org-log-into-drawer)
12374 (org-log-into-drawer "LOGBOOK")
12375 (t nil))))
12376 (save-restriction
12377 (save-excursion
12378 (when findpos
12379 (org-back-to-heading t)
12380 (narrow-to-region (point) (save-excursion
12381 (outline-next-heading) (point)))
12382 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12383 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12384 "[^\r\n]*\\)?"))
12385 (goto-char (match-end 0))
12386 (cond
12387 (drawer
12388 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12389 nil t)
12390 (progn
12391 (goto-char (match-end 0))
12392 (or org-log-states-order-reversed
12393 (and (re-search-forward org-property-end-re nil t)
12394 (goto-char (1- (match-beginning 0))))))
12395 (insert "\n:" drawer ":\n:END:")
12396 (beginning-of-line 0)
12397 (org-indent-line-function)
12398 (beginning-of-line 2)
12399 (org-indent-line-function)
12400 (end-of-line 0)))
12401 ((and org-log-state-notes-insert-after-drawers
12402 (save-excursion
12403 (forward-line) (looking-at org-drawer-regexp)))
12404 (forward-line)
12405 (while (looking-at org-drawer-regexp)
12406 (goto-char (match-end 0))
12407 (re-search-forward org-property-end-re (point-max) t)
12408 (forward-line))
12409 (forward-line -1)))
12410 (unless org-log-states-order-reversed
12411 (and (= (char-after) ?\n) (forward-char 1))
12412 (org-skip-over-state-notes)
12413 (skip-chars-backward " \t\n\r")))
12414 (move-marker org-log-note-marker (point))
12415 (setq org-log-note-purpose purpose
12416 org-log-note-state state
12417 org-log-note-previous-state prev-state
12418 org-log-note-how how
12419 org-log-note-extra extra
12420 org-log-note-effective-time (org-current-effective-time))
12421 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12423 (defun org-skip-over-state-notes ()
12424 "Skip past the list of State notes in an entry."
12425 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12426 (when (ignore-errors (goto-char (org-in-item-p)))
12427 (let* ((struct (org-list-struct))
12428 (prevs (org-list-prevs-alist struct)))
12429 (while (looking-at "[ \t]*- State")
12430 (goto-char (or (org-list-get-next-item (point) struct prevs)
12431 (org-list-get-item-end (point) struct)))))))
12433 (defun org-add-log-note (&optional purpose)
12434 "Pop up a window for taking a note, and add this note later at point."
12435 (remove-hook 'post-command-hook 'org-add-log-note)
12436 (setq org-log-note-window-configuration (current-window-configuration))
12437 (delete-other-windows)
12438 (move-marker org-log-note-return-to (point))
12439 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12440 (goto-char org-log-note-marker)
12441 (org-switch-to-buffer-other-window "*Org Note*")
12442 (erase-buffer)
12443 (if (memq org-log-note-how '(time state))
12444 (let (current-prefix-arg) (org-store-log-note))
12445 (let ((org-inhibit-startup t)) (org-mode))
12446 (insert (format "# Insert note for %s.
12447 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12448 (cond
12449 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12450 ((eq org-log-note-purpose 'done) "closed todo item")
12451 ((eq org-log-note-purpose 'state)
12452 (format "state change from \"%s\" to \"%s\""
12453 (or org-log-note-previous-state "")
12454 (or org-log-note-state "")))
12455 ((eq org-log-note-purpose 'reschedule)
12456 "rescheduling")
12457 ((eq org-log-note-purpose 'delschedule)
12458 "no longer scheduled")
12459 ((eq org-log-note-purpose 'redeadline)
12460 "changing deadline")
12461 ((eq org-log-note-purpose 'deldeadline)
12462 "removing deadline")
12463 ((eq org-log-note-purpose 'refile)
12464 "refiling")
12465 ((eq org-log-note-purpose 'note)
12466 "this entry")
12467 (t (error "This should not happen")))))
12468 (if org-log-note-extra (insert org-log-note-extra))
12469 (org-set-local 'org-finish-function 'org-store-log-note)
12470 (run-hooks 'org-log-buffer-setup-hook)))
12472 (defvar org-note-abort nil) ; dynamically scoped
12473 (defun org-store-log-note ()
12474 "Finish taking a log note, and insert it to where it belongs."
12475 (let ((txt (buffer-string))
12476 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12477 lines ind bul)
12478 (kill-buffer (current-buffer))
12479 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12480 (setq txt (replace-match "" t t txt)))
12481 (if (string-match "\\s-+\\'" txt)
12482 (setq txt (replace-match "" t t txt)))
12483 (setq lines (org-split-string txt "\n"))
12484 (when (and note (string-match "\\S-" note))
12485 (setq note
12486 (org-replace-escapes
12487 note
12488 (list (cons "%u" (user-login-name))
12489 (cons "%U" user-full-name)
12490 (cons "%t" (format-time-string
12491 (org-time-stamp-format 'long 'inactive)
12492 org-log-note-effective-time))
12493 (cons "%T" (format-time-string
12494 (org-time-stamp-format 'long nil)
12495 org-log-note-effective-time))
12496 (cons "%d" (format-time-string
12497 (org-time-stamp-format nil 'inactive)
12498 org-log-note-effective-time))
12499 (cons "%D" (format-time-string
12500 (org-time-stamp-format nil nil)
12501 org-log-note-effective-time))
12502 (cons "%s" (if org-log-note-state
12503 (concat "\"" org-log-note-state "\"")
12504 ""))
12505 (cons "%S" (if org-log-note-previous-state
12506 (concat "\"" org-log-note-previous-state "\"")
12507 "\"\"")))))
12508 (if lines (setq note (concat note " \\\\")))
12509 (push note lines))
12510 (when (or current-prefix-arg org-note-abort)
12511 (when org-log-into-drawer
12512 (org-remove-empty-drawer-at
12513 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12514 org-log-note-marker))
12515 (setq lines nil))
12516 (when lines
12517 (with-current-buffer (marker-buffer org-log-note-marker)
12518 (save-excursion
12519 (goto-char org-log-note-marker)
12520 (move-marker org-log-note-marker nil)
12521 (end-of-line 1)
12522 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12523 (setq ind (save-excursion
12524 (if (ignore-errors (goto-char (org-in-item-p)))
12525 (let ((struct (org-list-struct)))
12526 (org-list-get-ind
12527 (org-list-get-top-point struct) struct))
12528 (skip-chars-backward " \r\t\n")
12529 (cond
12530 ((and (org-at-heading-p)
12531 org-adapt-indentation)
12532 (1+ (org-current-level)))
12533 ((org-at-heading-p) 0)
12534 (t (org-get-indentation))))))
12535 (setq bul (org-list-bullet-string "-"))
12536 (org-indent-line-to ind)
12537 (insert bul (pop lines))
12538 (let ((ind-body (+ (length bul) ind)))
12539 (while lines
12540 (insert "\n")
12541 (org-indent-line-to ind-body)
12542 (insert (pop lines))))
12543 (message "Note stored")
12544 (org-back-to-heading t)
12545 (org-cycle-hide-drawers 'children)))))
12546 (set-window-configuration org-log-note-window-configuration)
12547 (with-current-buffer (marker-buffer org-log-note-return-to)
12548 (goto-char org-log-note-return-to))
12549 (move-marker org-log-note-return-to nil)
12550 (and org-log-post-message (message "%s" org-log-post-message)))
12552 (defun org-remove-empty-drawer-at (drawer pos)
12553 "Remove an empty drawer DRAWER at position POS.
12554 POS may also be a marker."
12555 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12556 (save-excursion
12557 (save-restriction
12558 (widen)
12559 (goto-char pos)
12560 (if (org-in-regexp
12561 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12562 (replace-match ""))))))
12564 (defun org-sparse-tree (&optional arg)
12565 "Create a sparse tree, prompt for the details.
12566 This command can create sparse trees. You first need to select the type
12567 of match used to create the tree:
12569 t Show all TODO entries.
12570 T Show entries with a specific TODO keyword.
12571 m Show entries selected by a tags/property match.
12572 p Enter a property name and its value (both with completion on existing
12573 names/values) and show entries with that property.
12574 r Show entries matching a regular expression (`/' can be used as well)
12575 d Show deadlines due within `org-deadline-warning-days'.
12576 b Show deadlines and scheduled items before a date.
12577 a Show deadlines and scheduled items after a date."
12578 (interactive "P")
12579 (let (ans kwd value)
12580 (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")
12581 (setq ans (read-char-exclusive))
12582 (cond
12583 ((equal ans ?d)
12584 (call-interactively 'org-check-deadlines))
12585 ((equal ans ?b)
12586 (call-interactively 'org-check-before-date))
12587 ((equal ans ?a)
12588 (call-interactively 'org-check-after-date))
12589 ((equal ans ?D)
12590 (call-interactively 'org-check-dates-range))
12591 ((equal ans ?t)
12592 (org-show-todo-tree nil))
12593 ((equal ans ?T)
12594 (org-show-todo-tree '(4)))
12595 ((member ans '(?T ?m))
12596 (call-interactively 'org-match-sparse-tree))
12597 ((member ans '(?p ?P))
12598 (setq kwd (org-icompleting-read "Property: "
12599 (mapcar 'list (org-buffer-property-keys))))
12600 (setq value (org-icompleting-read "Value: "
12601 (mapcar 'list (org-property-values kwd))))
12602 (unless (string-match "\\`{.*}\\'" value)
12603 (setq value (concat "\"" value "\"")))
12604 (org-match-sparse-tree arg (concat kwd "=" value)))
12605 ((member ans '(?r ?R ?/))
12606 (call-interactively 'org-occur))
12607 (t (error "No such sparse tree command \"%c\"" ans)))))
12609 (defvar org-occur-highlights nil
12610 "List of overlays used for occur matches.")
12611 (make-variable-buffer-local 'org-occur-highlights)
12612 (defvar org-occur-parameters nil
12613 "Parameters of the active org-occur calls.
12614 This is a list, each call to org-occur pushes as cons cell,
12615 containing the regular expression and the callback, onto the list.
12616 The list can contain several entries if `org-occur' has been called
12617 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12618 will only contain one set of parameters. When the highlights are
12619 removed (for example with `C-c C-c', or with the next edit (depending
12620 on `org-remove-highlights-with-change'), this variable is emptied
12621 as well.")
12622 (make-variable-buffer-local 'org-occur-parameters)
12624 (defun org-occur (regexp &optional keep-previous callback)
12625 "Make a compact tree which shows all matches of REGEXP.
12626 The tree will show the lines where the regexp matches, and all higher
12627 headlines above the match. It will also show the heading after the match,
12628 to make sure editing the matching entry is easy.
12629 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12630 call to `org-occur' will be kept, to allow stacking of calls to this
12631 command.
12632 If CALLBACK is non-nil, it is a function which is called to confirm
12633 that the match should indeed be shown."
12634 (interactive "sRegexp: \nP")
12635 (when (equal regexp "")
12636 (error "Regexp cannot be empty"))
12637 (unless keep-previous
12638 (org-remove-occur-highlights nil nil t))
12639 (push (cons regexp callback) org-occur-parameters)
12640 (let ((cnt 0))
12641 (save-excursion
12642 (goto-char (point-min))
12643 (if (or (not keep-previous) ; do not want to keep
12644 (not org-occur-highlights)) ; no previous matches
12645 ;; hide everything
12646 (org-overview))
12647 (while (re-search-forward regexp nil t)
12648 (when (or (not callback)
12649 (save-match-data (funcall callback)))
12650 (setq cnt (1+ cnt))
12651 (when org-highlight-sparse-tree-matches
12652 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12653 (org-show-context 'occur-tree))))
12654 (when org-remove-highlights-with-change
12655 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12656 nil 'local))
12657 (unless org-sparse-tree-open-archived-trees
12658 (org-hide-archived-subtrees (point-min) (point-max)))
12659 (run-hooks 'org-occur-hook)
12660 (if (org-called-interactively-p 'interactive)
12661 (message "%d match(es) for regexp %s" cnt regexp))
12662 cnt))
12664 (defun org-occur-next-match (&optional n reset)
12665 "Function for `next-error-function' to find sparse tree matches.
12666 N is the number of matches to move, when negative move backwards.
12667 RESET is entirely ignored - this function always goes back to the
12668 starting point when no match is found."
12669 (let* ((limit (if (< n 0) (point-min) (point-max)))
12670 (search-func (if (< n 0)
12671 'previous-single-char-property-change
12672 'next-single-char-property-change))
12673 (n (abs n))
12674 (pos (point))
12676 (catch 'exit
12677 (while (setq p1 (funcall search-func (point) 'org-type))
12678 (when (equal p1 limit)
12679 (goto-char pos)
12680 (error "No more matches"))
12681 (when (equal (get-char-property p1 'org-type) 'org-occur)
12682 (setq n (1- n))
12683 (when (= n 0)
12684 (goto-char p1)
12685 (throw 'exit (point))))
12686 (goto-char p1))
12687 (goto-char p1)
12688 (error "No more matches"))))
12690 (defun org-show-context (&optional key)
12691 "Make sure point and context are visible.
12692 How much context is shown depends upon the variables
12693 `org-show-hierarchy-above', `org-show-following-heading',
12694 `org-show-entry-below' and `org-show-siblings'."
12695 (let ((heading-p (org-at-heading-p t))
12696 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12697 (following-p (org-get-alist-option org-show-following-heading key))
12698 (entry-p (org-get-alist-option org-show-entry-below key))
12699 (siblings-p (org-get-alist-option org-show-siblings key)))
12700 (catch 'exit
12701 ;; Show heading or entry text
12702 (if (and heading-p (not entry-p))
12703 (org-flag-heading nil) ; only show the heading
12704 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12705 (org-show-hidden-entry))) ; show entire entry
12706 (when following-p
12707 ;; Show next sibling, or heading below text
12708 (save-excursion
12709 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12710 (org-flag-heading nil))))
12711 (when siblings-p (org-show-siblings))
12712 (when hierarchy-p
12713 ;; show all higher headings, possibly with siblings
12714 (save-excursion
12715 (while (and (condition-case nil
12716 (progn (org-up-heading-all 1) t)
12717 (error nil))
12718 (not (bobp)))
12719 (org-flag-heading nil)
12720 (when siblings-p (org-show-siblings))))))))
12722 (defvar org-reveal-start-hook nil
12723 "Hook run before revealing a location.")
12725 (defun org-reveal (&optional siblings)
12726 "Show current entry, hierarchy above it, and the following headline.
12727 This can be used to show a consistent set of context around locations
12728 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12729 not t for the search context.
12731 With optional argument SIBLINGS, on each level of the hierarchy all
12732 siblings are shown. This repairs the tree structure to what it would
12733 look like when opened with hierarchical calls to `org-cycle'.
12734 With double optional argument \\[universal-argument] \\[universal-argument], \
12735 go to the parent and show the
12736 entire tree."
12737 (interactive "P")
12738 (run-hooks 'org-reveal-start-hook)
12739 (let ((org-show-hierarchy-above t)
12740 (org-show-following-heading t)
12741 (org-show-siblings (if siblings t org-show-siblings)))
12742 (org-show-context nil))
12743 (when (equal siblings '(16))
12744 (save-excursion
12745 (when (org-up-heading-safe)
12746 (org-show-subtree)
12747 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12749 (defun org-highlight-new-match (beg end)
12750 "Highlight from BEG to END and mark the highlight is an occur headline."
12751 (let ((ov (make-overlay beg end)))
12752 (overlay-put ov 'face 'secondary-selection)
12753 (overlay-put ov 'org-type 'org-occur)
12754 (push ov org-occur-highlights)))
12756 (defun org-remove-occur-highlights (&optional beg end noremove)
12757 "Remove the occur highlights from the buffer.
12758 BEG and END are ignored. If NOREMOVE is nil, remove this function
12759 from the `before-change-functions' in the current buffer."
12760 (interactive)
12761 (unless org-inhibit-highlight-removal
12762 (mapc 'delete-overlay org-occur-highlights)
12763 (setq org-occur-highlights nil)
12764 (setq org-occur-parameters nil)
12765 (unless noremove
12766 (remove-hook 'before-change-functions
12767 'org-remove-occur-highlights 'local))))
12769 ;;;; Priorities
12771 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12772 "Regular expression matching the priority indicator.")
12774 (defvar org-remove-priority-next-time nil)
12776 (defun org-priority-up ()
12777 "Increase the priority of the current item."
12778 (interactive)
12779 (org-priority 'up))
12781 (defun org-priority-down ()
12782 "Decrease the priority of the current item."
12783 (interactive)
12784 (org-priority 'down))
12786 (defun org-priority (&optional action)
12787 "Change the priority of an item by ARG.
12788 ACTION can be `set', `up', `down', or a character."
12789 (interactive)
12790 (unless org-enable-priority-commands
12791 (error "Priority commands are disabled"))
12792 (setq action (or action 'set))
12793 (let (current new news have remove)
12794 (save-excursion
12795 (org-back-to-heading t)
12796 (if (looking-at org-priority-regexp)
12797 (setq current (string-to-char (match-string 2))
12798 have t))
12799 (cond
12800 ((eq action 'remove)
12801 (setq remove t new ?\ ))
12802 ((or (eq action 'set)
12803 (if (featurep 'xemacs) (characterp action) (integerp action)))
12804 (if (not (eq action 'set))
12805 (setq new action)
12806 (message "Priority %c-%c, SPC to remove: "
12807 org-highest-priority org-lowest-priority)
12808 (save-match-data
12809 (setq new (read-char-exclusive))))
12810 (if (and (= (upcase org-highest-priority) org-highest-priority)
12811 (= (upcase org-lowest-priority) org-lowest-priority))
12812 (setq new (upcase new)))
12813 (cond ((equal new ?\ ) (setq remove t))
12814 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12815 (error "Priority must be between `%c' and `%c'"
12816 org-highest-priority org-lowest-priority))))
12817 ((eq action 'up)
12818 (setq new (if have
12819 (1- current) ; normal cycling
12820 ;; last priority was empty
12821 (if (eq last-command this-command)
12822 org-lowest-priority ; wrap around empty to lowest
12823 ;; default
12824 (if org-priority-start-cycle-with-default
12825 org-default-priority
12826 (1- org-default-priority))))))
12827 ((eq action 'down)
12828 (setq new (if have
12829 (1+ current) ; normal cycling
12830 ;; last priority was empty
12831 (if (eq last-command this-command)
12832 org-highest-priority ; wrap around empty to highest
12833 ;; default
12834 (if org-priority-start-cycle-with-default
12835 org-default-priority
12836 (1+ org-default-priority))))))
12837 (t (error "Invalid action")))
12838 (if (or (< (upcase new) org-highest-priority)
12839 (> (upcase new) org-lowest-priority))
12840 (if (and (memq action '(up down))
12841 (not have) (not (eq last-command this-command)))
12842 ;; `new' is from default priority
12843 (error
12844 "The default can not be set, see `org-default-priority' why")
12845 ;; normal cycling: `new' is beyond highest/lowest priority
12846 ;; and is wrapped around to the empty priority
12847 (setq remove t)))
12848 (setq news (format "%c" new))
12849 (if have
12850 (if remove
12851 (replace-match "" t t nil 1)
12852 (replace-match news t t nil 2))
12853 (if remove
12854 (error "No priority cookie found in line")
12855 (let ((case-fold-search nil))
12856 (looking-at org-todo-line-regexp))
12857 (if (match-end 2)
12858 (progn
12859 (goto-char (match-end 2))
12860 (insert " [#" news "]"))
12861 (goto-char (match-beginning 3))
12862 (insert "[#" news "] "))))
12863 (org-preserve-lc (org-set-tags nil 'align)))
12864 (if remove
12865 (message "Priority removed")
12866 (message "Priority of current item set to %s" news))))
12868 (defun org-get-priority (s)
12869 "Find priority cookie and return priority."
12870 (if (functionp org-get-priority-function)
12871 (funcall org-get-priority-function)
12872 (save-match-data
12873 (if (not (string-match org-priority-regexp s))
12874 (* 1000 (- org-lowest-priority org-default-priority))
12875 (* 1000 (- org-lowest-priority
12876 (string-to-char (match-string 2 s))))))))
12878 ;;;; Tags
12880 (defvar org-agenda-archives-mode)
12881 (defvar org-map-continue-from nil
12882 "Position from where mapping should continue.
12883 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12885 (defvar org-scanner-tags nil
12886 "The current tag list while the tags scanner is running.")
12887 (defvar org-trust-scanner-tags nil
12888 "Should `org-get-tags-at' use the tags for the scanner.
12889 This is for internal dynamical scoping only.
12890 When this is non-nil, the function `org-get-tags-at' will return the value
12891 of `org-scanner-tags' instead of building the list by itself. This
12892 can lead to large speed-ups when the tags scanner is used in a file with
12893 many entries, and when the list of tags is retrieved, for example to
12894 obtain a list of properties. Building the tags list for each entry in such
12895 a file becomes an N^2 operation - but with this variable set, it scales
12896 as N.")
12898 (defun org-scan-tags (action matcher todo-only &optional start-level)
12899 "Scan headline tags with inheritance and produce output ACTION.
12901 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12902 or `agenda' to produce an entry list for an agenda view. It can also be
12903 a Lisp form or a function that should be called at each matched headline, in
12904 this case the return value is a list of all return values from these calls.
12906 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12907 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12908 only lines with a not-done TODO keyword are included in the output.
12909 This should be the same variable that was scoped into
12910 and set by `org-make-tags-matcher' when it constructed MATCHER.
12912 START-LEVEL can be a string with asterisks, reducing the scope to
12913 headlines matching this string."
12914 (require 'org-agenda)
12915 (let* ((re (concat "^"
12916 (if start-level
12917 ;; Get the correct level to match
12918 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12919 org-outline-regexp)
12920 " *\\(\\<\\("
12921 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12922 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12923 (props (list 'face 'default
12924 'done-face 'org-agenda-done
12925 'undone-face 'default
12926 'mouse-face 'highlight
12927 'org-not-done-regexp org-not-done-regexp
12928 'org-todo-regexp org-todo-regexp
12929 'org-complex-heading-regexp org-complex-heading-regexp
12930 'help-echo
12931 (format "mouse-2 or RET jump to org file %s"
12932 (abbreviate-file-name
12933 (or (buffer-file-name (buffer-base-buffer))
12934 (buffer-name (buffer-base-buffer)))))))
12935 (case-fold-search nil)
12936 (org-map-continue-from nil)
12937 lspos tags tags-list
12938 (tags-alist (list (cons 0 org-file-tags)))
12939 (llast 0) rtn rtn1 level category i txt
12940 todo marker entry priority)
12941 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12942 (setq action (list 'lambda nil action)))
12943 (save-excursion
12944 (goto-char (point-min))
12945 (when (eq action 'sparse-tree)
12946 (org-overview)
12947 (org-remove-occur-highlights))
12948 (while (re-search-forward re nil t)
12949 (setq org-map-continue-from nil)
12950 (catch :skip
12951 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12952 tags (if (match-end 4) (org-match-string-no-properties 4)))
12953 (goto-char (setq lspos (match-beginning 0)))
12954 (setq level (org-reduced-level (funcall outline-level))
12955 category (org-get-category))
12956 (setq i llast llast level)
12957 ;; remove tag lists from same and sublevels
12958 (while (>= i level)
12959 (when (setq entry (assoc i tags-alist))
12960 (setq tags-alist (delete entry tags-alist)))
12961 (setq i (1- i)))
12962 ;; add the next tags
12963 (when tags
12964 (setq tags (org-split-string tags ":")
12965 tags-alist
12966 (cons (cons level tags) tags-alist)))
12967 ;; compile tags for current headline
12968 (setq tags-list
12969 (if org-use-tag-inheritance
12970 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12971 tags)
12972 org-scanner-tags tags-list)
12973 (when org-use-tag-inheritance
12974 (setcdr (car tags-alist)
12975 (mapcar (lambda (x)
12976 (setq x (copy-sequence x))
12977 (org-add-prop-inherited x))
12978 (cdar tags-alist))))
12979 (when (and tags org-use-tag-inheritance
12980 (or (not (eq t org-use-tag-inheritance))
12981 org-tags-exclude-from-inheritance))
12982 ;; selective inheritance, remove uninherited ones
12983 (setcdr (car tags-alist)
12984 (org-remove-uninherited-tags (cdar tags-alist))))
12985 (when (and
12987 ;; eval matcher only when the todo condition is OK
12988 (and (or (not todo-only) (member todo org-not-done-keywords))
12989 (let ((case-fold-search t) (org-trust-scanner-tags t))
12990 (eval matcher)))
12992 ;; Call the skipper, but return t if it does not skip,
12993 ;; so that the `and' form continues evaluating
12994 (progn
12995 (unless (eq action 'sparse-tree) (org-agenda-skip))
12998 ;; Check if timestamps are deselecting this entry
12999 (or (not todo-only)
13000 (and (member todo org-not-done-keywords)
13001 (or (not org-agenda-tags-todo-honor-ignore-options)
13002 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13004 ;; Extra check for the archive tag
13005 ;; FIXME: Does the skipper already do this????
13007 (not (member org-archive-tag tags-list))
13008 ;; we have an archive tag, should we use this anyway?
13009 (or (not org-agenda-skip-archived-trees)
13010 (and (eq action 'agenda) org-agenda-archives-mode))))
13012 ;; select this headline
13014 (cond
13015 ((eq action 'sparse-tree)
13016 (and org-highlight-sparse-tree-matches
13017 (org-get-heading) (match-end 0)
13018 (org-highlight-new-match
13019 (match-beginning 1) (match-end 1)))
13020 (org-show-context 'tags-tree))
13021 ((eq action 'agenda)
13022 (setq txt (org-agenda-format-item
13024 (concat
13025 (if (eq org-tags-match-list-sublevels 'indented)
13026 (make-string (1- level) ?.) "")
13027 (org-get-heading))
13028 category
13029 tags-list)
13030 priority (org-get-priority txt))
13031 (goto-char lspos)
13032 (setq marker (org-agenda-new-marker))
13033 (org-add-props txt props
13034 'org-marker marker 'org-hd-marker marker 'org-category category
13035 'todo-state todo
13036 'priority priority 'type "tagsmatch")
13037 (push txt rtn))
13038 ((functionp action)
13039 (setq org-map-continue-from nil)
13040 (save-excursion
13041 (setq rtn1 (funcall action))
13042 (push rtn1 rtn)))
13043 (t (error "Invalid action")))
13045 ;; if we are to skip sublevels, jump to end of subtree
13046 (unless org-tags-match-list-sublevels
13047 (org-end-of-subtree t)
13048 (backward-char 1))))
13049 ;; Get the correct position from where to continue
13050 (if org-map-continue-from
13051 (goto-char org-map-continue-from)
13052 (and (= (point) lspos) (end-of-line 1)))))
13053 (when (and (eq action 'sparse-tree)
13054 (not org-sparse-tree-open-archived-trees))
13055 (org-hide-archived-subtrees (point-min) (point-max)))
13056 (nreverse rtn)))
13058 (defun org-remove-uninherited-tags (tags)
13059 "Remove all tags that are not inherited from the list TAGS."
13060 (cond
13061 ((eq org-use-tag-inheritance t)
13062 (if org-tags-exclude-from-inheritance
13063 (org-delete-all org-tags-exclude-from-inheritance tags)
13064 tags))
13065 ((not org-use-tag-inheritance) nil)
13066 ((stringp org-use-tag-inheritance)
13067 (delq nil (mapcar
13068 (lambda (x)
13069 (if (and (string-match org-use-tag-inheritance x)
13070 (not (member x org-tags-exclude-from-inheritance)))
13071 x nil))
13072 tags)))
13073 ((listp org-use-tag-inheritance)
13074 (delq nil (mapcar
13075 (lambda (x)
13076 (if (member x org-use-tag-inheritance) x nil))
13077 tags)))))
13079 (defun org-match-sparse-tree (&optional todo-only match)
13080 "Create a sparse tree according to tags string MATCH.
13081 MATCH can contain positive and negative selection of tags, like
13082 \"+WORK+URGENT-WITHBOSS\".
13083 If optional argument TODO-ONLY is non-nil, only select lines that are
13084 also TODO lines."
13085 (interactive "P")
13086 (org-prepare-agenda-buffers (list (current-buffer)))
13087 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13089 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13091 (defvar org-cached-props nil)
13092 (defun org-cached-entry-get (pom property)
13093 (if (or (eq t org-use-property-inheritance)
13094 (and (stringp org-use-property-inheritance)
13095 (string-match org-use-property-inheritance property))
13096 (and (listp org-use-property-inheritance)
13097 (member property org-use-property-inheritance)))
13098 ;; Caching is not possible, check it directly
13099 (org-entry-get pom property 'inherit)
13100 ;; Get all properties, so that we can do complicated checks easily
13101 (cdr (assoc property (or org-cached-props
13102 (setq org-cached-props
13103 (org-entry-properties pom)))))))
13105 (defun org-global-tags-completion-table (&optional files)
13106 "Return the list of all tags in all agenda buffer/files.
13107 Optional FILES argument is a list of files to which can be used
13108 instead of the agenda files."
13109 (save-excursion
13110 (org-uniquify
13111 (delq nil
13112 (apply 'append
13113 (mapcar
13114 (lambda (file)
13115 (set-buffer (find-file-noselect file))
13116 (append (org-get-buffer-tags)
13117 (mapcar (lambda (x) (if (stringp (car-safe x))
13118 (list (car-safe x)) nil))
13119 org-tag-alist)))
13120 (if (and files (car files))
13121 files
13122 (org-agenda-files))))))))
13124 (defun org-make-tags-matcher (match)
13125 "Create the TAGS/TODO matcher form for the selection string MATCH.
13127 The variable `todo-only' is scoped dynamically into this function; it will be
13128 set to t if the matcher restricts matching to TODO entries,
13129 otherwise will not be touched.
13131 Returns a cons of the selection string MATCH and the constructed
13132 lisp form implementing the matcher. The matcher is to be
13133 evaluated at an Org entry, with point on the headline,
13134 and returns t if the entry matches the
13135 selection string MATCH. The returned lisp form references
13136 two variables with information about the entry, which must be
13137 bound around the form's evaluation: todo, the TODO keyword at the
13138 entry (or nil of none); and tags-list, the list of all tags at the
13139 entry including inherited ones. Additionally, the category
13140 of the entry (if any) must be specified as the text property
13141 'org-category on the headline.
13143 See also `org-scan-tags'.
13145 (declare (special todo-only))
13146 (unless (boundp 'todo-only)
13147 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13148 (unless match
13149 ;; Get a new match request, with completion
13150 (let ((org-last-tags-completion-table
13151 (org-global-tags-completion-table)))
13152 (setq match (org-completing-read-no-i
13153 "Match: " 'org-tags-completion-function nil nil nil
13154 'org-tags-history))))
13156 ;; Parse the string and create a lisp form
13157 (let ((match0 match)
13158 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13159 minus tag mm
13160 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13161 orterms term orlist re-p str-p level-p level-op time-p
13162 prop-p pn pv po gv rest)
13163 (if (string-match "/+" match)
13164 ;; match contains also a todo-matching request
13165 (progn
13166 (setq tagsmatch (substring match 0 (match-beginning 0))
13167 todomatch (substring match (match-end 0)))
13168 (if (string-match "^!" todomatch)
13169 (setq todo-only t todomatch (substring todomatch 1)))
13170 (if (string-match "^\\s-*$" todomatch)
13171 (setq todomatch nil)))
13172 ;; only matching tags
13173 (setq tagsmatch match todomatch nil))
13175 ;; Make the tags matcher
13176 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13177 (setq tagsmatcher t)
13178 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13179 (while (setq term (pop orterms))
13180 (while (and (equal (substring term -1) "\\") orterms)
13181 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13182 (while (string-match re term)
13183 (setq rest (substring term (match-end 0))
13184 minus (and (match-end 1)
13185 (equal (match-string 1 term) "-"))
13186 tag (save-match-data (replace-regexp-in-string
13187 "\\\\-" "-"
13188 (match-string 2 term)))
13189 re-p (equal (string-to-char tag) ?{)
13190 level-p (match-end 4)
13191 prop-p (match-end 5)
13192 mm (cond
13193 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13194 (level-p
13195 (setq level-op (org-op-to-function (match-string 3 term)))
13196 `(,level-op level ,(string-to-number
13197 (match-string 4 term))))
13198 (prop-p
13199 (setq pn (match-string 5 term)
13200 po (match-string 6 term)
13201 pv (match-string 7 term)
13202 re-p (equal (string-to-char pv) ?{)
13203 str-p (equal (string-to-char pv) ?\")
13204 time-p (save-match-data
13205 (string-match "^\"[[<].*[]>]\"$" pv))
13206 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13207 (if time-p (setq pv (org-matcher-time pv)))
13208 (setq po (org-op-to-function po (if time-p 'time str-p)))
13209 (cond
13210 ((equal pn "CATEGORY")
13211 (setq gv '(get-text-property (point) 'org-category)))
13212 ((equal pn "TODO")
13213 (setq gv 'todo))
13215 (setq gv `(org-cached-entry-get nil ,pn))))
13216 (if re-p
13217 (if (eq po 'org<>)
13218 `(not (string-match ,pv (or ,gv "")))
13219 `(string-match ,pv (or ,gv "")))
13220 (if str-p
13221 `(,po (or ,gv "") ,pv)
13222 `(,po (string-to-number (or ,gv ""))
13223 ,(string-to-number pv) ))))
13224 (t `(member ,tag tags-list)))
13225 mm (if minus (list 'not mm) mm)
13226 term rest)
13227 (push mm tagsmatcher))
13228 (push (if (> (length tagsmatcher) 1)
13229 (cons 'and tagsmatcher)
13230 (car tagsmatcher))
13231 orlist)
13232 (setq tagsmatcher nil))
13233 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13234 (setq tagsmatcher
13235 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13236 ;; Make the todo matcher
13237 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13238 (setq todomatcher t)
13239 (setq orterms (org-split-string todomatch "|") orlist nil)
13240 (while (setq term (pop orterms))
13241 (while (string-match re term)
13242 (setq minus (and (match-end 1)
13243 (equal (match-string 1 term) "-"))
13244 kwd (match-string 2 term)
13245 re-p (equal (string-to-char kwd) ?{)
13246 term (substring term (match-end 0))
13247 mm (if re-p
13248 `(string-match ,(substring kwd 1 -1) todo)
13249 (list 'equal 'todo kwd))
13250 mm (if minus (list 'not mm) mm))
13251 (push mm todomatcher))
13252 (push (if (> (length todomatcher) 1)
13253 (cons 'and todomatcher)
13254 (car todomatcher))
13255 orlist)
13256 (setq todomatcher nil))
13257 (setq todomatcher (if (> (length orlist) 1)
13258 (cons 'or orlist) (car orlist))))
13260 ;; Return the string and lisp forms of the matcher
13261 (setq matcher (if todomatcher
13262 (list 'and tagsmatcher todomatcher)
13263 tagsmatcher))
13264 (when todo-only
13265 (setq matcher (list 'and '(member todo org-not-done-keywords)
13266 matcher)))
13267 (cons match0 matcher)))
13269 (defun org-op-to-function (op &optional stringp)
13270 "Turn an operator into the appropriate function."
13271 (setq op
13272 (cond
13273 ((equal op "<" ) '(< string< org-time<))
13274 ((equal op ">" ) '(> org-string> org-time>))
13275 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13276 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13277 ((member op '("=" "==")) '(= string= org-time=))
13278 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13279 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13281 (defun org<> (a b) (not (= a b)))
13282 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13283 (defun org-string>= (a b) (not (string< a b)))
13284 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13285 (defun org-string<> (a b) (not (string= a b)))
13286 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13287 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13288 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13289 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13290 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13291 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13292 (defun org-2ft (s)
13293 "Convert S to a floating point time.
13294 If S is already a number, just return it. If it is a string, parse
13295 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13296 (cond
13297 ((numberp s) s)
13298 ((stringp s)
13299 (condition-case nil
13300 (float-time (apply 'encode-time (org-parse-time-string s)))
13301 (error 0.)))
13302 (t 0.)))
13304 (defun org-time-today ()
13305 "Time in seconds today at 0:00.
13306 Returns the float number of seconds since the beginning of the
13307 epoch to the beginning of today (00:00)."
13308 (float-time (apply 'encode-time
13309 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13311 (defun org-matcher-time (s)
13312 "Interpret a time comparison value."
13313 (save-match-data
13314 (cond
13315 ((string= s "<now>") (float-time))
13316 ((string= s "<today>") (org-time-today))
13317 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13318 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13319 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13320 (+ (org-time-today)
13321 (* (string-to-number (match-string 1 s))
13322 (cdr (assoc (match-string 2 s)
13323 '(("d" . 86400.0) ("w" . 604800.0)
13324 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13325 (t (org-2ft s)))))
13327 (defun org-match-any-p (re list)
13328 "Does re match any element of list?"
13329 (setq list (mapcar (lambda (x) (string-match re x)) list))
13330 (delq nil list))
13332 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13333 (defvar org-tags-overlay (make-overlay 1 1))
13334 (org-detach-overlay org-tags-overlay)
13336 (defun org-get-local-tags-at (&optional pos)
13337 "Get a list of tags defined in the current headline."
13338 (org-get-tags-at pos 'local))
13340 (defun org-get-local-tags ()
13341 "Get a list of tags defined in the current headline."
13342 (org-get-tags-at nil 'local))
13344 (defun org-get-tags-at (&optional pos local)
13345 "Get a list of all headline tags applicable at POS.
13346 POS defaults to point. If tags are inherited, the list contains
13347 the targets in the same sequence as the headlines appear, i.e.
13348 the tags of the current headline come last.
13349 When LOCAL is non-nil, only return tags from the current headline,
13350 ignore inherited ones."
13351 (interactive)
13352 (if (and org-trust-scanner-tags
13353 (or (not pos) (equal pos (point)))
13354 (not local))
13355 org-scanner-tags
13356 (let (tags ltags lastpos parent)
13357 (save-excursion
13358 (save-restriction
13359 (widen)
13360 (goto-char (or pos (point)))
13361 (save-match-data
13362 (catch 'done
13363 (condition-case nil
13364 (progn
13365 (org-back-to-heading t)
13366 (while (not (equal lastpos (point)))
13367 (setq lastpos (point))
13368 (when (looking-at
13369 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13370 (setq ltags (org-split-string
13371 (org-match-string-no-properties 1) ":"))
13372 (when parent
13373 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13374 (setq tags (append
13375 (if parent
13376 (org-remove-uninherited-tags ltags)
13377 ltags)
13378 tags)))
13379 (or org-use-tag-inheritance (throw 'done t))
13380 (if local (throw 'done t))
13381 (or (org-up-heading-safe) (error nil))
13382 (setq parent t)))
13383 (error nil)))))
13384 (if local
13385 tags
13386 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13388 (defun org-add-prop-inherited (s)
13389 (add-text-properties 0 (length s) '(inherited t) s)
13392 (defun org-toggle-tag (tag &optional onoff)
13393 "Toggle the tag TAG for the current line.
13394 If ONOFF is `on' or `off', don't toggle but set to this state."
13395 (let (res current)
13396 (save-excursion
13397 (org-back-to-heading t)
13398 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13399 (point-at-eol) t)
13400 (progn
13401 (setq current (match-string 1))
13402 (replace-match ""))
13403 (setq current ""))
13404 (setq current (nreverse (org-split-string current ":")))
13405 (cond
13406 ((eq onoff 'on)
13407 (setq res t)
13408 (or (member tag current) (push tag current)))
13409 ((eq onoff 'off)
13410 (or (not (member tag current)) (setq current (delete tag current))))
13411 (t (if (member tag current)
13412 (setq current (delete tag current))
13413 (setq res t)
13414 (push tag current))))
13415 (end-of-line 1)
13416 (if current
13417 (progn
13418 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13419 (org-set-tags nil t))
13420 (delete-horizontal-space))
13421 (run-hooks 'org-after-tags-change-hook))
13422 res))
13424 (defun org-align-tags-here (to-col)
13425 ;; Assumes that this is a headline
13426 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13427 (beginning-of-line 1)
13428 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13429 (< pos (match-beginning 2)))
13430 (progn
13431 (setq tags-l (- (match-end 2) (match-beginning 2)))
13432 (goto-char (match-beginning 1))
13433 (insert " ")
13434 (delete-region (point) (1+ (match-beginning 2)))
13435 (setq ncol (max (current-column)
13436 (1+ col)
13437 (if (> to-col 0)
13438 to-col
13439 (- (abs to-col) tags-l))))
13440 (setq p (point))
13441 (insert (make-string (- ncol (current-column)) ?\ ))
13442 (setq ncol (current-column))
13443 (when indent-tabs-mode (tabify p (point-at-eol)))
13444 (org-move-to-column (min ncol col) t))
13445 (goto-char pos))))
13447 (defun org-set-tags-command (&optional arg just-align)
13448 "Call the set-tags command for the current entry."
13449 (interactive "P")
13450 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13451 (org-set-tags arg just-align)
13452 (save-excursion
13453 (org-back-to-heading t)
13454 (org-set-tags arg just-align))))
13456 (defun org-set-tags-to (data)
13457 "Set the tags of the current entry to DATA, replacing the current tags.
13458 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13459 If DATA is nil or the empty string, any tags will be removed."
13460 (interactive "sTags: ")
13461 (setq data
13462 (cond
13463 ((eq data nil) "")
13464 ((equal data "") "")
13465 ((stringp data)
13466 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13467 ":"))
13468 ((listp data)
13469 (concat ":" (mapconcat 'identity data ":") ":"))
13470 (t nil)))
13471 (when data
13472 (save-excursion
13473 (org-back-to-heading t)
13474 (when (looking-at org-complex-heading-regexp)
13475 (if (match-end 5)
13476 (progn
13477 (goto-char (match-beginning 5))
13478 (insert data)
13479 (delete-region (point) (point-at-eol))
13480 (org-set-tags nil 'align))
13481 (goto-char (point-at-eol))
13482 (insert " " data)
13483 (org-set-tags nil 'align)))
13484 (beginning-of-line 1)
13485 (if (looking-at ".*?\\([ \t]+\\)$")
13486 (delete-region (match-beginning 1) (match-end 1))))))
13488 (defun org-align-all-tags ()
13489 "Align the tags i all headings."
13490 (interactive)
13491 (save-excursion
13492 (or (ignore-errors (org-back-to-heading t))
13493 (outline-next-heading))
13494 (if (org-at-heading-p)
13495 (org-set-tags t)
13496 (message "No headings"))))
13498 (defvar org-indent-indentation-per-level)
13499 (defun org-set-tags (&optional arg just-align)
13500 "Set the tags for the current headline.
13501 With prefix ARG, realign all tags in headings in the current buffer."
13502 (interactive "P")
13503 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13504 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13505 'region-start-level 'region))
13506 org-loop-over-headlines-in-active-region)
13507 (org-map-entries
13508 ;; We don't use ARG and JUST-ALIGN here these args are not
13509 ;; useful when looping over headlines
13510 `(org-set-tags)
13511 org-loop-over-headlines-in-active-region
13512 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13513 (let* ((re org-outline-regexp-bol)
13514 (current (unless arg (org-get-tags-string)))
13515 (col (current-column))
13516 (org-setting-tags t)
13517 table current-tags inherited-tags ; computed below when needed
13518 tags p0 c0 c1 rpl di tc level)
13519 (if arg
13520 (save-excursion
13521 (goto-char (point-min))
13522 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13523 (while (re-search-forward re nil t)
13524 (org-set-tags nil t)
13525 (end-of-line 1)))
13526 (message "All tags realigned to column %d" org-tags-column))
13527 (if just-align
13528 (setq tags current)
13529 ;; Get a new set of tags from the user
13530 (save-excursion
13531 (setq table (append org-tag-persistent-alist
13532 (or org-tag-alist (org-get-buffer-tags))
13533 (and
13534 org-complete-tags-always-offer-all-agenda-tags
13535 (org-global-tags-completion-table
13536 (org-agenda-files))))
13537 org-last-tags-completion-table table
13538 current-tags (org-split-string current ":")
13539 inherited-tags (nreverse
13540 (nthcdr (length current-tags)
13541 (nreverse (org-get-tags-at))))
13542 tags
13543 (if (or (eq t org-use-fast-tag-selection)
13544 (and org-use-fast-tag-selection
13545 (delq nil (mapcar 'cdr table))))
13546 (org-fast-tag-selection
13547 current-tags inherited-tags table
13548 (if org-fast-tag-selection-include-todo
13549 org-todo-key-alist))
13550 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13551 (org-trim
13552 (org-icompleting-read "Tags: "
13553 'org-tags-completion-function
13554 nil nil current 'org-tags-history))))))
13555 (while (string-match "[-+&]+" tags)
13556 ;; No boolean logic, just a list
13557 (setq tags (replace-match ":" t t tags))))
13559 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13561 (if org-tags-sort-function
13562 (setq tags (mapconcat 'identity
13563 (sort (org-split-string
13564 tags (org-re "[^[:alnum:]_@#%]+"))
13565 org-tags-sort-function) ":")))
13567 (if (string-match "\\`[\t ]*\\'" tags)
13568 (setq tags "")
13569 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13570 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13572 ;; Insert new tags at the correct column
13573 (beginning-of-line 1)
13574 (setq level (or (and (looking-at org-outline-regexp)
13575 (- (match-end 0) (point) 1))
13577 (cond
13578 ((and (equal current "") (equal tags "")))
13579 ((re-search-forward
13580 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13581 (point-at-eol) t)
13582 (if (equal tags "")
13583 (setq rpl "")
13584 (goto-char (match-beginning 0))
13585 (setq c0 (current-column)
13586 ;; compute offset for the case of org-indent-mode active
13587 di (if org-indent-mode
13588 (* (1- org-indent-indentation-per-level) (1- level))
13590 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13591 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13592 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13593 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13594 (replace-match rpl t t)
13595 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13596 tags)
13597 (t (error "Tags alignment failed")))
13598 (org-move-to-column col)
13599 (unless just-align
13600 (run-hooks 'org-after-tags-change-hook))))))
13602 (defun org-change-tag-in-region (beg end tag off)
13603 "Add or remove TAG for each entry in the region.
13604 This works in the agenda, and also in an org-mode buffer."
13605 (interactive
13606 (list (region-beginning) (region-end)
13607 (let ((org-last-tags-completion-table
13608 (if (derived-mode-p 'org-mode)
13609 (org-get-buffer-tags)
13610 (org-global-tags-completion-table))))
13611 (org-icompleting-read
13612 "Tag: " 'org-tags-completion-function nil nil nil
13613 'org-tags-history))
13614 (progn
13615 (message "[s]et or [r]emove? ")
13616 (equal (read-char-exclusive) ?r))))
13617 (if (fboundp 'deactivate-mark) (deactivate-mark))
13618 (let ((agendap (equal major-mode 'org-agenda-mode))
13619 l1 l2 m buf pos newhead (cnt 0))
13620 (goto-char end)
13621 (setq l2 (1- (org-current-line)))
13622 (goto-char beg)
13623 (setq l1 (org-current-line))
13624 (loop for l from l1 to l2 do
13625 (org-goto-line l)
13626 (setq m (get-text-property (point) 'org-hd-marker))
13627 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13628 (and agendap m))
13629 (setq buf (if agendap (marker-buffer m) (current-buffer))
13630 pos (if agendap m (point)))
13631 (with-current-buffer buf
13632 (save-excursion
13633 (save-restriction
13634 (goto-char pos)
13635 (setq cnt (1+ cnt))
13636 (org-toggle-tag tag (if off 'off 'on))
13637 (setq newhead (org-get-heading)))))
13638 (and agendap (org-agenda-change-all-lines newhead m))))
13639 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13641 (defun org-tags-completion-function (string predicate &optional flag)
13642 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13643 (confirm (lambda (x) (stringp (car x)))))
13644 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13645 (setq s1 (match-string 1 string)
13646 s2 (match-string 2 string))
13647 (setq s1 "" s2 string))
13648 (cond
13649 ((eq flag nil)
13650 ;; try completion
13651 (setq rtn (try-completion s2 ctable confirm))
13652 (if (stringp rtn)
13653 (setq rtn
13654 (concat s1 s2 (substring rtn (length s2))
13655 (if (and org-add-colon-after-tag-completion
13656 (assoc rtn ctable))
13657 ":" ""))))
13658 rtn)
13659 ((eq flag t)
13660 ;; all-completions
13661 (all-completions s2 ctable confirm)
13663 ((eq flag 'lambda)
13664 ;; exact match?
13665 (assoc s2 ctable)))
13668 (defun org-fast-tag-insert (kwd tags face &optional end)
13669 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13670 (insert (format "%-12s" (concat kwd ":"))
13671 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13672 (or end "")))
13674 (defun org-fast-tag-show-exit (flag)
13675 (save-excursion
13676 (org-goto-line 3)
13677 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13678 (replace-match ""))
13679 (when flag
13680 (end-of-line 1)
13681 (org-move-to-column (- (window-width) 19) t)
13682 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13684 (defun org-set-current-tags-overlay (current prefix)
13685 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13686 (if (featurep 'xemacs)
13687 (org-overlay-display org-tags-overlay (concat prefix s)
13688 'secondary-selection)
13689 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13690 (org-overlay-display org-tags-overlay (concat prefix s)))))
13692 (defvar org-last-tag-selection-key nil)
13693 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13694 "Fast tag selection with single keys.
13695 CURRENT is the current list of tags in the headline, INHERITED is the
13696 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13697 possibly with grouping information. TODO-TABLE is a similar table with
13698 TODO keywords, should these have keys assigned to them.
13699 If the keys are nil, a-z are automatically assigned.
13700 Returns the new tags string, or nil to not change the current settings."
13701 (let* ((fulltable (append table todo-table))
13702 (maxlen (apply 'max (mapcar
13703 (lambda (x)
13704 (if (stringp (car x)) (string-width (car x)) 0))
13705 fulltable)))
13706 (buf (current-buffer))
13707 (expert (eq org-fast-tag-selection-single-key 'expert))
13708 (buffer-tags nil)
13709 (fwidth (+ maxlen 3 1 3))
13710 (ncol (/ (- (window-width) 4) fwidth))
13711 (i-face 'org-done)
13712 (c-face 'org-todo)
13713 tg cnt e c char c1 c2 ntable tbl rtn
13714 ov-start ov-end ov-prefix
13715 (exit-after-next org-fast-tag-selection-single-key)
13716 (done-keywords org-done-keywords)
13717 groups ingroup)
13718 (save-excursion
13719 (beginning-of-line 1)
13720 (if (looking-at
13721 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13722 (setq ov-start (match-beginning 1)
13723 ov-end (match-end 1)
13724 ov-prefix "")
13725 (setq ov-start (1- (point-at-eol))
13726 ov-end (1+ ov-start))
13727 (skip-chars-forward "^\n\r")
13728 (setq ov-prefix
13729 (concat
13730 (buffer-substring (1- (point)) (point))
13731 (if (> (current-column) org-tags-column)
13733 (make-string (- org-tags-column (current-column)) ?\ ))))))
13734 (move-overlay org-tags-overlay ov-start ov-end)
13735 (save-window-excursion
13736 (if expert
13737 (set-buffer (get-buffer-create " *Org tags*"))
13738 (delete-other-windows)
13739 (split-window-vertically)
13740 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13741 (erase-buffer)
13742 (org-set-local 'org-done-keywords done-keywords)
13743 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13744 (org-fast-tag-insert "Current" current c-face "\n\n")
13745 (org-fast-tag-show-exit exit-after-next)
13746 (org-set-current-tags-overlay current ov-prefix)
13747 (setq tbl fulltable char ?a cnt 0)
13748 (while (setq e (pop tbl))
13749 (cond
13750 ((equal (car e) :startgroup)
13751 (push '() groups) (setq ingroup t)
13752 (when (not (= cnt 0))
13753 (setq cnt 0)
13754 (insert "\n"))
13755 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13756 ((equal (car e) :endgroup)
13757 (setq ingroup nil cnt 0)
13758 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13759 ((equal e '(:newline))
13760 (when (not (= cnt 0))
13761 (setq cnt 0)
13762 (insert "\n")
13763 (setq e (car tbl))
13764 (while (equal (car tbl) '(:newline))
13765 (insert "\n")
13766 (setq tbl (cdr tbl)))))
13768 (setq tg (copy-sequence (car e)) c2 nil)
13769 (if (cdr e)
13770 (setq c (cdr e))
13771 ;; automatically assign a character.
13772 (setq c1 (string-to-char
13773 (downcase (substring
13774 tg (if (= (string-to-char tg) ?@) 1 0)))))
13775 (if (or (rassoc c1 ntable) (rassoc c1 table))
13776 (while (or (rassoc char ntable) (rassoc char table))
13777 (setq char (1+ char)))
13778 (setq c2 c1))
13779 (setq c (or c2 char)))
13780 (if ingroup (push tg (car groups)))
13781 (setq tg (org-add-props tg nil 'face
13782 (cond
13783 ((not (assoc tg table))
13784 (org-get-todo-face tg))
13785 ((member tg current) c-face)
13786 ((member tg inherited) i-face)
13787 (t nil))))
13788 (if (and (= cnt 0) (not ingroup)) (insert " "))
13789 (insert "[" c "] " tg (make-string
13790 (- fwidth 4 (length tg)) ?\ ))
13791 (push (cons tg c) ntable)
13792 (when (= (setq cnt (1+ cnt)) ncol)
13793 (insert "\n")
13794 (if ingroup (insert " "))
13795 (setq cnt 0)))))
13796 (setq ntable (nreverse ntable))
13797 (insert "\n")
13798 (goto-char (point-min))
13799 (if (not expert) (org-fit-window-to-buffer))
13800 (setq rtn
13801 (catch 'exit
13802 (while t
13803 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13804 (if (not groups) "no " "")
13805 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13806 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13807 (setq org-last-tag-selection-key c)
13808 (cond
13809 ((= c ?\r) (throw 'exit t))
13810 ((= c ?!)
13811 (setq groups (not groups))
13812 (goto-char (point-min))
13813 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13814 ((= c ?\C-c)
13815 (if (not expert)
13816 (org-fast-tag-show-exit
13817 (setq exit-after-next (not exit-after-next)))
13818 (setq expert nil)
13819 (delete-other-windows)
13820 (set-window-buffer (split-window-vertically) " *Org tags*")
13821 (org-switch-to-buffer-other-window " *Org tags*")
13822 (org-fit-window-to-buffer)))
13823 ((or (= c ?\C-g)
13824 (and (= c ?q) (not (rassoc c ntable))))
13825 (org-detach-overlay org-tags-overlay)
13826 (setq quit-flag t))
13827 ((= c ?\ )
13828 (setq current nil)
13829 (if exit-after-next (setq exit-after-next 'now)))
13830 ((= c ?\t)
13831 (condition-case nil
13832 (setq tg (org-icompleting-read
13833 "Tag: "
13834 (or buffer-tags
13835 (with-current-buffer buf
13836 (org-get-buffer-tags)))))
13837 (quit (setq tg "")))
13838 (when (string-match "\\S-" tg)
13839 (add-to-list 'buffer-tags (list tg))
13840 (if (member tg current)
13841 (setq current (delete tg current))
13842 (push tg current)))
13843 (if exit-after-next (setq exit-after-next 'now)))
13844 ((setq e (rassoc c todo-table) tg (car e))
13845 (with-current-buffer buf
13846 (save-excursion (org-todo tg)))
13847 (if exit-after-next (setq exit-after-next 'now)))
13848 ((setq e (rassoc c ntable) tg (car e))
13849 (if (member tg current)
13850 (setq current (delete tg current))
13851 (loop for g in groups do
13852 (if (member tg g)
13853 (mapc (lambda (x)
13854 (setq current (delete x current)))
13855 g)))
13856 (push tg current))
13857 (if exit-after-next (setq exit-after-next 'now))))
13859 ;; Create a sorted list
13860 (setq current
13861 (sort current
13862 (lambda (a b)
13863 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13864 (if (eq exit-after-next 'now) (throw 'exit t))
13865 (goto-char (point-min))
13866 (beginning-of-line 2)
13867 (delete-region (point) (point-at-eol))
13868 (org-fast-tag-insert "Current" current c-face)
13869 (org-set-current-tags-overlay current ov-prefix)
13870 (while (re-search-forward
13871 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13872 (setq tg (match-string 1))
13873 (add-text-properties
13874 (match-beginning 1) (match-end 1)
13875 (list 'face
13876 (cond
13877 ((member tg current) c-face)
13878 ((member tg inherited) i-face)
13879 (t (get-text-property (match-beginning 1) 'face))))))
13880 (goto-char (point-min)))))
13881 (org-detach-overlay org-tags-overlay)
13882 (if rtn
13883 (mapconcat 'identity current ":")
13884 nil))))
13886 (defun org-get-tags-string ()
13887 "Get the TAGS string in the current headline."
13888 (unless (org-at-heading-p t)
13889 (error "Not on a heading"))
13890 (save-excursion
13891 (beginning-of-line 1)
13892 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13893 (org-match-string-no-properties 1)
13894 "")))
13896 (defun org-get-tags ()
13897 "Get the list of tags specified in the current headline."
13898 (org-split-string (org-get-tags-string) ":"))
13900 (defun org-get-buffer-tags ()
13901 "Get a table of all tags used in the buffer, for completion."
13902 (let (tags)
13903 (save-excursion
13904 (goto-char (point-min))
13905 (while (re-search-forward
13906 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13907 (when (equal (char-after (point-at-bol 0)) ?*)
13908 (mapc (lambda (x) (add-to-list 'tags x))
13909 (org-split-string (org-match-string-no-properties 1) ":")))))
13910 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13911 (mapcar 'list tags)))
13913 ;;;; The mapping API
13915 ;;;###autoload
13916 (defun org-map-entries (func &optional match scope &rest skip)
13917 "Call FUNC at each headline selected by MATCH in SCOPE.
13919 FUNC is a function or a lisp form. The function will be called without
13920 arguments, with the cursor positioned at the beginning of the headline.
13921 The return values of all calls to the function will be collected and
13922 returned as a list.
13924 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13925 does not need to preserve point. After evaluation, the cursor will be
13926 moved to the end of the line (presumably of the headline of the
13927 processed entry) and search continues from there. Under some
13928 circumstances, this may not produce the wanted results. For example,
13929 if you have removed (e.g. archived) the current (sub)tree it could
13930 mean that the next entry will be skipped entirely. In such cases, you
13931 can specify the position from where search should continue by making
13932 FUNC set the variable `org-map-continue-from' to the desired buffer
13933 position.
13935 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13936 Only headlines that are matched by this query will be considered during
13937 the iteration. When MATCH is nil or t, all headlines will be
13938 visited by the iteration.
13940 SCOPE determines the scope of this command. It can be any of:
13942 nil The current buffer, respecting the restriction if any
13943 tree The subtree started with the entry at point
13944 region The entries within the active region, if any
13945 region-start-level
13946 The entries within the active region, but only those at
13947 the same level than the first one.
13948 file The current buffer, without restriction
13949 file-with-archives
13950 The current buffer, and any archives associated with it
13951 agenda All agenda files
13952 agenda-with-archives
13953 All agenda files with any archive files associated with them
13954 \(file1 file2 ...)
13955 If this is a list, all files in the list will be scanned
13957 The remaining args are treated as settings for the skipping facilities of
13958 the scanner. The following items can be given here:
13960 archive skip trees with the archive tag.
13961 comment skip trees with the COMMENT keyword
13962 function or Emacs Lisp form:
13963 will be used as value for `org-agenda-skip-function', so whenever
13964 the function returns t, FUNC will not be called for that
13965 entry and search will continue from the point where the
13966 function leaves it.
13968 If your function needs to retrieve the tags including inherited tags
13969 at the *current* entry, you can use the value of the variable
13970 `org-scanner-tags' which will be much faster than getting the value
13971 with `org-get-tags-at'. If your function gets properties with
13972 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13973 to t around the call to `org-entry-properties' to get the same speedup.
13974 Note that if your function moves around to retrieve tags and properties at
13975 a *different* entry, you cannot use these techniques."
13976 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13977 (not (org-region-active-p)))
13978 (let* ((org-agenda-archives-mode nil) ; just to make sure
13979 (org-agenda-skip-archived-trees (memq 'archive skip))
13980 (org-agenda-skip-comment-trees (memq 'comment skip))
13981 (org-agenda-skip-function
13982 (car (org-delete-all '(comment archive) skip)))
13983 (org-tags-match-list-sublevels t)
13984 (start-level (eq scope 'region-start-level))
13985 matcher file res
13986 org-todo-keywords-for-agenda
13987 org-done-keywords-for-agenda
13988 org-todo-keyword-alist-for-agenda
13989 org-drawers-for-agenda
13990 org-tag-alist-for-agenda
13991 todo-only)
13993 (cond
13994 ((eq match t) (setq matcher t))
13995 ((eq match nil) (setq matcher t))
13996 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13998 (save-excursion
13999 (save-restriction
14000 (cond ((eq scope 'tree)
14001 (org-back-to-heading t)
14002 (org-narrow-to-subtree)
14003 (setq scope nil))
14004 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14005 (org-region-active-p))
14006 ;; If needed, set start-level to a string like "2"
14007 (when start-level
14008 (save-excursion
14009 (goto-char (region-beginning))
14010 (unless (org-at-heading-p) (outline-next-heading))
14011 (setq start-level (org-current-level))))
14012 (narrow-to-region (region-beginning)
14013 (save-excursion
14014 (goto-char (region-end))
14015 (unless (and (bolp) (org-at-heading-p))
14016 (outline-next-heading))
14017 (point)))
14018 (setq scope nil)))
14020 (if (not scope)
14021 (progn
14022 (org-prepare-agenda-buffers
14023 (list (buffer-file-name (current-buffer))))
14024 (setq res (org-scan-tags func matcher todo-only start-level)))
14025 ;; Get the right scope
14026 (cond
14027 ((and scope (listp scope) (symbolp (car scope)))
14028 (setq scope (eval scope)))
14029 ((eq scope 'agenda)
14030 (setq scope (org-agenda-files t)))
14031 ((eq scope 'agenda-with-archives)
14032 (setq scope (org-agenda-files t))
14033 (setq scope (org-add-archive-files scope)))
14034 ((eq scope 'file)
14035 (setq scope (list (buffer-file-name))))
14036 ((eq scope 'file-with-archives)
14037 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14038 (org-prepare-agenda-buffers scope)
14039 (while (setq file (pop scope))
14040 (with-current-buffer (org-find-base-buffer-visiting file)
14041 (save-excursion
14042 (save-restriction
14043 (widen)
14044 (goto-char (point-min))
14045 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14046 res)))
14048 ;;;; Properties
14050 ;;; Setting and retrieving properties
14052 (defconst org-special-properties
14053 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14054 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14055 "The special properties valid in Org-mode.
14057 These are properties that are not defined in the property drawer,
14058 but in some other way.")
14060 (defconst org-default-properties
14061 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14062 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14063 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14064 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14065 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14066 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14067 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14068 "Some properties that are used by Org-mode for various purposes.
14069 Being in this list makes sure that they are offered for completion.")
14071 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14072 "Regular expression matching the first line of a property drawer.")
14074 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14075 "Regular expression matching the last line of a property drawer.")
14077 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14078 "Regular expression matching the first line of a property drawer.")
14080 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14081 "Regular expression matching the first line of a property drawer.")
14083 (defconst org-property-drawer-re
14084 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14085 org-property-end-re "\\)\n?")
14086 "Matches an entire property drawer.")
14088 (defconst org-clock-drawer-re
14089 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14090 org-property-end-re "\\)\n?")
14091 "Matches an entire clock drawer.")
14093 (defsubst org-re-property (property)
14094 "Return a regexp matching PROPERTY.
14095 Match group 1 will be set to the value "
14096 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14098 (defun org-property-action ()
14099 "Do an action on properties."
14100 (interactive)
14101 (let (c)
14102 (org-at-property-p)
14103 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14104 (setq c (read-char-exclusive))
14105 (cond
14106 ((equal c ?s)
14107 (call-interactively 'org-set-property))
14108 ((equal c ?d)
14109 (call-interactively 'org-delete-property))
14110 ((equal c ?D)
14111 (call-interactively 'org-delete-property-globally))
14112 ((equal c ?c)
14113 (call-interactively 'org-compute-property-at-point))
14114 (t (error "No such property action %c" c)))))
14116 (defun org-set-effort (&optional value)
14117 "Set the effort property of the current entry.
14118 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14119 allowed value."
14120 (interactive "P")
14121 (if (equal value 0) (setq value 10))
14122 (let* ((completion-ignore-case t)
14123 (prop org-effort-property)
14124 (cur (org-entry-get nil prop))
14125 (allowed (org-property-get-allowed-values nil prop 'table))
14126 (existing (mapcar 'list (org-property-values prop)))
14128 (val (cond
14129 ((stringp value) value)
14130 ((and allowed (integerp value))
14131 (or (car (nth (1- value) allowed))
14132 (car (org-last allowed))))
14133 (allowed
14134 (message "Select 1-9,0, [RET%s]: %s"
14135 (if cur (concat "=" cur) "")
14136 (mapconcat 'car allowed " "))
14137 (setq rpl (read-char-exclusive))
14138 (if (equal rpl ?\r)
14140 (setq rpl (- rpl ?0))
14141 (if (equal rpl 0) (setq rpl 10))
14142 (if (and (> rpl 0) (<= rpl (length allowed)))
14143 (car (nth (1- rpl) allowed))
14144 (org-completing-read "Effort: " allowed nil))))
14146 (let (org-completion-use-ido org-completion-use-iswitchb)
14147 (org-completing-read
14148 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14149 (concat "[" cur "]") "")
14150 ": ")
14151 existing nil nil "" nil cur))))))
14152 (unless (equal (org-entry-get nil prop) val)
14153 (org-entry-put nil prop val))
14154 (message "%s is now %s" prop val)))
14156 (defun org-at-property-p ()
14157 "Is cursor inside a property drawer?"
14158 (save-excursion
14159 (beginning-of-line 1)
14160 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14161 (save-match-data ;; Used by calling procedures
14162 (let ((p (point))
14163 (range (unless (org-before-first-heading-p)
14164 (org-get-property-block))))
14165 (and range (<= (car range) p) (< p (cdr range))))))))
14167 (defun org-get-property-block (&optional beg end force)
14168 "Return the (beg . end) range of the body of the property drawer.
14169 BEG and END can be beginning and end of subtree, if not given
14170 they will be found.
14171 If the drawer does not exist and FORCE is non-nil, create the drawer."
14172 (catch 'exit
14173 (save-excursion
14174 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14175 (end (or end (progn (outline-next-heading) (point)))))
14176 (goto-char beg)
14177 (if (re-search-forward org-property-start-re end t)
14178 (setq beg (1+ (match-end 0)))
14179 (if force
14180 (save-excursion
14181 (org-insert-property-drawer)
14182 (setq end (progn (outline-next-heading) (point))))
14183 (throw 'exit nil))
14184 (goto-char beg)
14185 (if (re-search-forward org-property-start-re end t)
14186 (setq beg (1+ (match-end 0)))))
14187 (if (re-search-forward org-property-end-re end t)
14188 (setq end (match-beginning 0))
14189 (or force (throw 'exit nil))
14190 (goto-char beg)
14191 (setq end beg)
14192 (org-indent-line-function)
14193 (insert ":END:\n"))
14194 (cons beg end)))))
14196 (defun org-entry-properties (&optional pom which specific)
14197 "Get all properties of the entry at point-or-marker POM.
14198 This includes the TODO keyword, the tags, time strings for deadline,
14199 scheduled, and clocking, and any additional properties defined in the
14200 entry. The return value is an alist, keys may occur multiple times
14201 if the property key was used several times.
14202 POM may also be nil, in which case the current entry is used.
14203 If WHICH is nil or `all', get all properties. If WHICH is
14204 `special' or `standard', only get that subclass. If WHICH
14205 is a string only get exactly this property. SPECIFIC can be a string, the
14206 specific property we are interested in. Specifying it can speed
14207 things up because then unnecessary parsing is avoided."
14208 (setq which (or which 'all))
14209 (org-with-point-at pom
14210 (let ((clockstr (substring org-clock-string 0 -1))
14211 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14212 (case-fold-search nil)
14213 beg end range props sum-props key key1 value string clocksum)
14214 (save-excursion
14215 (when (condition-case nil
14216 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14217 (error nil))
14218 (setq beg (point))
14219 (setq sum-props (get-text-property (point) 'org-summaries))
14220 (setq clocksum (get-text-property (point) :org-clock-minutes))
14221 (outline-next-heading)
14222 (setq end (point))
14223 (when (memq which '(all special))
14224 ;; Get the special properties, like TODO and tags
14225 (goto-char beg)
14226 (when (and (or (not specific) (string= specific "TODO"))
14227 (looking-at org-todo-line-regexp) (match-end 2))
14228 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14229 (when (and (or (not specific) (string= specific "PRIORITY"))
14230 (looking-at org-priority-regexp))
14231 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14232 (when (or (not specific) (string= specific "FILE"))
14233 (push (cons "FILE" buffer-file-name) props))
14234 (when (and (or (not specific) (string= specific "TAGS"))
14235 (setq value (org-get-tags-string))
14236 (string-match "\\S-" value))
14237 (push (cons "TAGS" value) props))
14238 (when (and (or (not specific) (string= specific "ALLTAGS"))
14239 (setq value (org-get-tags-at)))
14240 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14241 ":"))
14242 props))
14243 (when (or (not specific) (string= specific "BLOCKED"))
14244 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14245 (when (or (not specific)
14246 (member specific
14247 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14248 "TIMESTAMP" "TIMESTAMP_IA")))
14249 (catch 'match
14250 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14251 (setq key (if (match-end 1)
14252 (substring (org-match-string-no-properties 1)
14253 0 -1))
14254 string (if (equal key clockstr)
14255 (org-no-properties
14256 (org-trim
14257 (buffer-substring
14258 (match-beginning 3) (goto-char
14259 (point-at-eol)))))
14260 (substring (org-match-string-no-properties 3)
14261 1 -1)))
14262 ;; Get the correct property name from the key. This is
14263 ;; necessary if the user has configured time keywords.
14264 (setq key1 (concat key ":"))
14265 (cond
14266 ((not key)
14267 (setq key
14268 (if (= (char-after (match-beginning 3)) ?\[)
14269 "TIMESTAMP_IA" "TIMESTAMP")))
14270 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14271 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14272 ((equal key1 org-closed-string) (setq key "CLOSED"))
14273 ((equal key1 org-clock-string) (setq key "CLOCK")))
14274 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14275 (progn
14276 (push (cons key string) props)
14277 ;; no need to search further if match is found
14278 (throw 'match t))
14279 (when (or (equal key "CLOCK") (not (assoc key props)))
14280 (push (cons key string) props))))))
14283 (when (memq which '(all standard))
14284 ;; Get the standard properties, like :PROP: ...
14285 (setq range (org-get-property-block beg end))
14286 (when range
14287 (goto-char (car range))
14288 (while (re-search-forward
14289 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14290 (cdr range) t)
14291 (setq key (org-match-string-no-properties 1)
14292 value (org-trim (or (org-match-string-no-properties 2) "")))
14293 (unless (member key excluded)
14294 (push (cons key (or value "")) props)))))
14295 (if clocksum
14296 (push (cons "CLOCKSUM"
14297 (org-columns-number-to-string (/ (float clocksum) 60.)
14298 'add_times))
14299 props))
14300 (unless (assoc "CATEGORY" props)
14301 (push (cons "CATEGORY" (org-get-category)) props))
14302 (append sum-props (nreverse props)))))))
14304 (defun org-entry-get (pom property &optional inherit literal-nil)
14305 "Get value of PROPERTY for entry at point-or-marker POM.
14306 If INHERIT is non-nil and the entry does not have the property,
14307 then also check higher levels of the hierarchy.
14308 If INHERIT is the symbol `selective', use inheritance only if the setting
14309 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14310 If the property is present but empty, the return value is the empty string.
14311 If the property is not present at all, nil is returned.
14313 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14314 do not interpret it as the list atom nil. This is used for inheritance
14315 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14316 (org-with-point-at pom
14317 (if (and inherit (if (eq inherit 'selective)
14318 (org-property-inherit-p property)
14320 (org-entry-get-with-inheritance property literal-nil)
14321 (if (member property org-special-properties)
14322 ;; We need a special property. Use `org-entry-properties' to
14323 ;; retrieve it, but specify the wanted property
14324 (cdr (assoc property (org-entry-properties nil 'special property)))
14325 (let ((range (unless (org-before-first-heading-p)
14326 (org-get-property-block)))
14327 (props (list (or (assoc property org-file-properties)
14328 (assoc property org-global-properties)
14329 (assoc property org-global-properties-fixed))))
14330 val)
14331 (flet ((ap (key)
14332 (when (re-search-forward
14333 (org-re-property key) (cdr range) t)
14334 (setq props
14335 (org-update-property-plist
14337 (if (match-end 1)
14338 (org-match-string-no-properties 1) "")
14339 props)))))
14340 (when (and range (goto-char (car range)))
14341 (ap property)
14342 (goto-char (car range))
14343 (while (ap (concat property "+")))
14344 (setq val (cdr (assoc property props)))
14345 (when val (if literal-nil val (org-not-nil val))))))))))
14347 (defun org-property-or-variable-value (var &optional inherit)
14348 "Check if there is a property fixing the value of VAR.
14349 If yes, return this value. If not, return the current value of the variable."
14350 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14351 (if (and prop (stringp prop) (string-match "\\S-" prop))
14352 (read prop)
14353 (symbol-value var))))
14355 (defun org-entry-delete (pom property)
14356 "Delete the property PROPERTY from entry at point-or-marker POM."
14357 (org-with-point-at pom
14358 (if (member property org-special-properties)
14359 nil ; cannot delete these properties.
14360 (let ((range (org-get-property-block)))
14361 (if (and range
14362 (goto-char (car range))
14363 (re-search-forward
14364 (org-re-property property)
14365 (cdr range) t))
14366 (progn
14367 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14369 nil)))))
14371 ;; Multi-values properties are properties that contain multiple values
14372 ;; These values are assumed to be single words, separated by whitespace.
14373 (defun org-entry-add-to-multivalued-property (pom property value)
14374 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14375 (let* ((old (org-entry-get pom property))
14376 (values (and old (org-split-string old "[ \t]"))))
14377 (setq value (org-entry-protect-space value))
14378 (unless (member value values)
14379 (setq values (cons value values))
14380 (org-entry-put pom property
14381 (mapconcat 'identity values " ")))))
14383 (defun org-entry-remove-from-multivalued-property (pom property value)
14384 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14385 (let* ((old (org-entry-get pom property))
14386 (values (and old (org-split-string old "[ \t]"))))
14387 (setq value (org-entry-protect-space value))
14388 (when (member value values)
14389 (setq values (delete value values))
14390 (org-entry-put pom property
14391 (mapconcat 'identity values " ")))))
14393 (defun org-entry-member-in-multivalued-property (pom property value)
14394 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14395 (let* ((old (org-entry-get pom property))
14396 (values (and old (org-split-string old "[ \t]"))))
14397 (setq value (org-entry-protect-space value))
14398 (member value values)))
14400 (defun org-entry-get-multivalued-property (pom property)
14401 "Return a list of values in a multivalued property."
14402 (let* ((value (org-entry-get pom property))
14403 (values (and value (org-split-string value "[ \t]"))))
14404 (mapcar 'org-entry-restore-space values)))
14406 (defun org-entry-put-multivalued-property (pom property &rest values)
14407 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14408 VALUES should be a list of strings. Spaces will be protected."
14409 (org-entry-put pom property
14410 (mapconcat 'org-entry-protect-space values " "))
14411 (let* ((value (org-entry-get pom property))
14412 (values (and value (org-split-string value "[ \t]"))))
14413 (mapcar 'org-entry-restore-space values)))
14415 (defun org-entry-protect-space (s)
14416 "Protect spaces and newline in string S."
14417 (while (string-match " " s)
14418 (setq s (replace-match "%20" t t s)))
14419 (while (string-match "\n" s)
14420 (setq s (replace-match "%0A" t t s)))
14423 (defun org-entry-restore-space (s)
14424 "Restore spaces and newline in string S."
14425 (while (string-match "%20" s)
14426 (setq s (replace-match " " t t s)))
14427 (while (string-match "%0A" s)
14428 (setq s (replace-match "\n" t t s)))
14431 (defvar org-entry-property-inherited-from (make-marker)
14432 "Marker pointing to the entry from where a property was inherited.
14433 Each call to `org-entry-get-with-inheritance' will set this marker to the
14434 location of the entry where the inheritance search matched. If there was
14435 no match, the marker will point nowhere.
14436 Note that also `org-entry-get' calls this function, if the INHERIT flag
14437 is set.")
14439 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14440 "Get entry property, and search higher levels if not present.
14441 The search will stop at the first ancestor which has the property defined.
14442 If the value found is \"nil\", return nil to show that the property
14443 should be considered as undefined (this is the meaning of nil here).
14444 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14445 (move-marker org-entry-property-inherited-from nil)
14446 (let (tmp)
14447 (unless (org-before-first-heading-p)
14448 (save-excursion
14449 (save-restriction
14450 (widen)
14451 (catch 'ex
14452 (while t
14453 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14454 (org-back-to-heading t)
14455 (move-marker org-entry-property-inherited-from (point))
14456 (throw 'ex tmp))
14457 (or (org-up-heading-safe) (throw 'ex nil)))))))
14458 (setq tmp (or tmp
14459 (cdr (assoc property org-file-properties))
14460 (cdr (assoc property org-global-properties))
14461 (cdr (assoc property org-global-properties-fixed))))
14462 (if literal-nil tmp (org-not-nil tmp))))
14464 (defvar org-property-changed-functions nil
14465 "Hook called when the value of a property has changed.
14466 Each hook function should accept two arguments, the name of the property
14467 and the new value.")
14469 (defun org-entry-put (pom property value)
14470 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14471 (org-with-point-at pom
14472 (org-back-to-heading t)
14473 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14474 range)
14475 (cond
14476 ((equal property "TODO")
14477 (when (and (stringp value) (string-match "\\S-" value)
14478 (not (member value org-todo-keywords-1)))
14479 (error "\"%s\" is not a valid TODO state" value))
14480 (if (or (not value)
14481 (not (string-match "\\S-" value)))
14482 (setq value 'none))
14483 (org-todo value)
14484 (org-set-tags nil 'align))
14485 ((equal property "PRIORITY")
14486 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14487 (string-to-char value) ?\ ))
14488 (org-set-tags nil 'align))
14489 ((equal property "SCHEDULED")
14490 (if (re-search-forward org-scheduled-time-regexp end t)
14491 (cond
14492 ((eq value 'earlier) (org-timestamp-change -1 'day))
14493 ((eq value 'later) (org-timestamp-change 1 'day))
14494 (t (call-interactively 'org-schedule)))
14495 (call-interactively 'org-schedule)))
14496 ((equal property "DEADLINE")
14497 (if (re-search-forward org-deadline-time-regexp end t)
14498 (cond
14499 ((eq value 'earlier) (org-timestamp-change -1 'day))
14500 ((eq value 'later) (org-timestamp-change 1 'day))
14501 (t (call-interactively 'org-deadline)))
14502 (call-interactively 'org-deadline)))
14503 ((member property org-special-properties)
14504 (error "The %s property can not yet be set with `org-entry-put'"
14505 property))
14506 (t ; a non-special property
14507 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14508 (setq range (org-get-property-block beg end 'force))
14509 (goto-char (car range))
14510 (if (re-search-forward
14511 (org-re-property property) (cdr range) t)
14512 (progn
14513 (delete-region (match-beginning 0) (match-end 0))
14514 (goto-char (match-beginning 0)))
14515 (goto-char (cdr range))
14516 (insert "\n")
14517 (backward-char 1)
14518 (org-indent-line-function))
14519 (insert ":" property ":")
14520 (and value (insert " " value))
14521 (org-indent-line-function)))))
14522 (run-hook-with-args 'org-property-changed-functions property value)))
14524 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14525 "Get all property keys in the current buffer.
14526 With INCLUDE-SPECIALS, also list the special properties that reflect things
14527 like tags and TODO state.
14528 With INCLUDE-DEFAULTS, also include properties that has special meaning
14529 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14530 and others.
14531 With INCLUDE-COLUMNS, also include property names given in COLUMN
14532 formats in the current buffer."
14533 (let (rtn range cfmt s p)
14534 (save-excursion
14535 (save-restriction
14536 (widen)
14537 (goto-char (point-min))
14538 (while (re-search-forward org-property-start-re nil t)
14539 (setq range (org-get-property-block))
14540 (goto-char (car range))
14541 (while (re-search-forward
14542 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14543 (cdr range) t)
14544 (add-to-list 'rtn (org-match-string-no-properties 1)))
14545 (outline-next-heading))))
14547 (when include-specials
14548 (setq rtn (append org-special-properties rtn)))
14550 (when include-defaults
14551 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14552 (add-to-list 'rtn org-effort-property))
14554 (when include-columns
14555 (save-excursion
14556 (save-restriction
14557 (widen)
14558 (goto-char (point-min))
14559 (while (re-search-forward
14560 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14561 nil t)
14562 (setq cfmt (match-string 2) s 0)
14563 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14564 cfmt s)
14565 (setq s (match-end 0)
14566 p (match-string 1 cfmt))
14567 (unless (or (equal p "ITEM")
14568 (member p org-special-properties))
14569 (add-to-list 'rtn (match-string 1 cfmt))))))))
14571 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14573 (defun org-property-values (key)
14574 "Return a list of all values of property KEY in the current buffer."
14575 (save-excursion
14576 (save-restriction
14577 (widen)
14578 (goto-char (point-min))
14579 (let ((re (org-re-property key))
14580 values)
14581 (while (re-search-forward re nil t)
14582 (add-to-list 'values (org-trim (match-string 1))))
14583 (delete "" values)))))
14585 (defun org-insert-property-drawer ()
14586 "Insert a property drawer into the current entry."
14587 (org-back-to-heading t)
14588 (looking-at org-outline-regexp)
14589 (let ((indent (if org-adapt-indentation
14590 (- (match-end 0) (match-beginning 0))
14592 (beg (point))
14593 (re (concat "^[ \t]*" org-keyword-time-regexp))
14594 end hiddenp)
14595 (outline-next-heading)
14596 (setq end (point))
14597 (goto-char beg)
14598 (while (re-search-forward re end t))
14599 (setq hiddenp (outline-invisible-p))
14600 (end-of-line 1)
14601 (and (equal (char-after) ?\n) (forward-char 1))
14602 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14603 (if (member (match-string 1) '("CLOCK:" ":END:"))
14604 ;; just skip this line
14605 (beginning-of-line 2)
14606 ;; Drawer start, find the end
14607 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14608 (beginning-of-line 1)))
14609 (org-skip-over-state-notes)
14610 (skip-chars-backward " \t\n\r")
14611 (if (eq (char-before) ?*) (forward-char 1))
14612 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14613 (beginning-of-line 0)
14614 (org-indent-to-column indent)
14615 (beginning-of-line 2)
14616 (org-indent-to-column indent)
14617 (beginning-of-line 0)
14618 (if hiddenp
14619 (save-excursion
14620 (org-back-to-heading t)
14621 (hide-entry))
14622 (org-flag-drawer t))))
14624 (defun org-insert-drawer (&optional arg drawer)
14625 "Insert a drawer at point.
14627 Optional argument DRAWER, when non-nil, is a string representing
14628 drawer's name. Otherwise, the user is prompted for a name.
14630 If a region is active, insert the drawer around that region
14631 instead.
14633 Point is left between drawer's boundaries."
14634 (interactive "P")
14635 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14636 "LOGBOOK"))
14637 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14638 ;; internally by Org. They are meant to be inserted
14639 ;; automatically.
14640 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14641 ;; Remove system drawers from list. Note: For some reason,
14642 ;; `org-completing-read' ignores the predicate while
14643 ;; `completing-read' handles it fine.
14644 (drawer (if arg "PROPERTIES"
14645 (or drawer
14646 (completing-read
14647 "Drawer: " org-drawers
14648 (lambda (d) (not (member d system-drawers))))))))
14649 (cond
14650 ;; With C-u, fall back on `org-insert-property-drawer'
14651 (arg (org-insert-property-drawer))
14652 ;; With an active region, insert a drawer at point.
14653 ((not (org-region-active-p))
14654 (progn
14655 (unless (bolp) (insert "\n"))
14656 (insert (format ":%s:\n\n:END:\n" drawer))
14657 (forward-line -2)))
14658 ;; Otherwise, insert the drawer at point
14660 (let ((rbeg (region-beginning))
14661 (rend (copy-marker (region-end))))
14662 (unwind-protect
14663 (progn
14664 (goto-char rbeg)
14665 (beginning-of-line)
14666 (when (save-excursion
14667 (re-search-forward org-outline-regexp-bol rend t))
14668 (error "Drawers cannot contain headlines"))
14669 ;; Position point at the beginning of the first
14670 ;; non-blank line in region. Insert drawer's opening
14671 ;; there, then indent it.
14672 (org-skip-whitespace)
14673 (beginning-of-line)
14674 (insert ":" drawer ":\n")
14675 (forward-line -1)
14676 (indent-for-tab-command)
14677 ;; Move point to the beginning of the first blank line
14678 ;; after the last non-blank line in region. Insert
14679 ;; drawer's closing, then indent it.
14680 (goto-char rend)
14681 (skip-chars-backward " \r\t\n")
14682 (insert "\n:END:")
14683 (indent-for-tab-command)
14684 (unless (eolp) (insert "\n")))
14685 ;; Clear marker, whatever the outcome of insertion is.
14686 (set-marker rend nil)))))))
14688 (defvar org-property-set-functions-alist nil
14689 "Property set function alist.
14690 Each entry should have the following format:
14692 (PROPERTY . READ-FUNCTION)
14694 The read function will be called with the same argument as
14695 `org-completing-read'.")
14697 (defun org-set-property-function (property)
14698 "Get the function that should be used to set PROPERTY.
14699 This is computed according to `org-property-set-functions-alist'."
14700 (or (cdr (assoc property org-property-set-functions-alist))
14701 'org-completing-read))
14703 (defun org-read-property-value (property)
14704 "Read PROPERTY value from user."
14705 (let* ((completion-ignore-case t)
14706 (allowed (org-property-get-allowed-values nil property 'table))
14707 (cur (org-entry-get nil property))
14708 (prompt (concat property " value"
14709 (if (and cur (string-match "\\S-" cur))
14710 (concat " [" cur "]") "") ": "))
14711 (set-function (org-set-property-function property))
14712 (val (if allowed
14713 (funcall set-function prompt allowed nil
14714 (not (get-text-property 0 'org-unrestricted
14715 (caar allowed))))
14716 (let (org-completion-use-ido org-completion-use-iswitchb)
14717 (funcall set-function prompt
14718 (mapcar 'list (org-property-values property))
14719 nil nil "" nil cur)))))
14720 (if (equal val "")
14722 val)))
14724 (defvar org-last-set-property nil)
14725 (defun org-read-property-name ()
14726 "Read a property name."
14727 (let* ((completion-ignore-case t)
14728 (keys (org-buffer-property-keys nil t t))
14729 (default-prop (or (save-excursion
14730 (save-match-data
14731 (beginning-of-line)
14732 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14733 (null (string= (match-string 1) "END"))
14734 (match-string 1))))
14735 org-last-set-property))
14736 (property (org-icompleting-read
14737 (concat "Property"
14738 (if default-prop (concat " [" default-prop "]") "")
14739 ": ")
14740 (mapcar 'list keys)
14741 nil nil nil nil
14742 default-prop
14744 (if (member property keys)
14745 property
14746 (or (cdr (assoc (downcase property)
14747 (mapcar (lambda (x) (cons (downcase x) x))
14748 keys)))
14749 property))))
14751 (defun org-set-property (property value)
14752 "In the current entry, set PROPERTY to VALUE.
14753 When called interactively, this will prompt for a property name, offering
14754 completion on existing and default properties. And then it will prompt
14755 for a value, offering completion either on allowed values (via an inherited
14756 xxx_ALL property) or on existing values in other instances of this property
14757 in the current file."
14758 (interactive (list nil nil))
14759 (let* ((property (or property (org-read-property-name)))
14760 (value (or value (org-read-property-value property)))
14761 (fn (cdr (assoc property org-properties-postprocess-alist))))
14762 (setq org-last-set-property property)
14763 ;; Possibly postprocess the inserted value:
14764 (when fn (setq value (funcall fn value)))
14765 (unless (equal (org-entry-get nil property) value)
14766 (org-entry-put nil property value))))
14768 (defun org-delete-property (property)
14769 "In the current entry, delete PROPERTY."
14770 (interactive
14771 (let* ((completion-ignore-case t)
14772 (prop (org-icompleting-read "Property: "
14773 (org-entry-properties nil 'standard))))
14774 (list prop)))
14775 (message "Property %s %s" property
14776 (if (org-entry-delete nil property)
14777 "deleted"
14778 "was not present in the entry")))
14780 (defun org-delete-property-globally (property)
14781 "Remove PROPERTY globally, from all entries."
14782 (interactive
14783 (let* ((completion-ignore-case t)
14784 (prop (org-icompleting-read
14785 "Globally remove property: "
14786 (mapcar 'list (org-buffer-property-keys)))))
14787 (list prop)))
14788 (save-excursion
14789 (save-restriction
14790 (widen)
14791 (goto-char (point-min))
14792 (let ((cnt 0))
14793 (while (re-search-forward
14794 (org-re-property property)
14795 nil t)
14796 (setq cnt (1+ cnt))
14797 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14798 (message "Property \"%s\" removed from %d entries" property cnt)))))
14800 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14802 (defun org-compute-property-at-point ()
14803 "Compute the property at point.
14804 This looks for an enclosing column format, extracts the operator and
14805 then applies it to the property in the column format's scope."
14806 (interactive)
14807 (unless (org-at-property-p)
14808 (error "Not at a property"))
14809 (let ((prop (org-match-string-no-properties 2)))
14810 (org-columns-get-format-and-top-level)
14811 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14812 (error "No operator defined for property %s" prop))
14813 (org-columns-compute prop)))
14815 (defvar org-property-allowed-value-functions nil
14816 "Hook for functions supplying allowed values for a specific property.
14817 The functions must take a single argument, the name of the property, and
14818 return a flat list of allowed values. If \":ETC\" is one of
14819 the values, this means that these values are intended as defaults for
14820 completion, but that other values should be allowed too.
14821 The functions must return nil if they are not responsible for this
14822 property.")
14824 (defun org-property-get-allowed-values (pom property &optional table)
14825 "Get allowed values for the property PROPERTY.
14826 When TABLE is non-nil, return an alist that can directly be used for
14827 completion."
14828 (let (vals)
14829 (cond
14830 ((equal property "TODO")
14831 (setq vals (org-with-point-at pom
14832 (append org-todo-keywords-1 '("")))))
14833 ((equal property "PRIORITY")
14834 (let ((n org-lowest-priority))
14835 (while (>= n org-highest-priority)
14836 (push (char-to-string n) vals)
14837 (setq n (1- n)))))
14838 ((member property org-special-properties))
14839 ((setq vals (run-hook-with-args-until-success
14840 'org-property-allowed-value-functions property)))
14842 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14843 (when (and vals (string-match "\\S-" vals))
14844 (setq vals (car (read-from-string (concat "(" vals ")"))))
14845 (setq vals (mapcar (lambda (x)
14846 (cond ((stringp x) x)
14847 ((numberp x) (number-to-string x))
14848 ((symbolp x) (symbol-name x))
14849 (t "???")))
14850 vals)))))
14851 (when (member ":ETC" vals)
14852 (setq vals (remove ":ETC" vals))
14853 (org-add-props (car vals) '(org-unrestricted t)))
14854 (if table (mapcar 'list vals) vals)))
14856 (defun org-property-previous-allowed-value (&optional previous)
14857 "Switch to the next allowed value for this property."
14858 (interactive)
14859 (org-property-next-allowed-value t))
14861 (defun org-property-next-allowed-value (&optional previous)
14862 "Switch to the next allowed value for this property."
14863 (interactive)
14864 (unless (org-at-property-p)
14865 (error "Not at a property"))
14866 (let* ((key (match-string 2))
14867 (value (match-string 3))
14868 (allowed (or (org-property-get-allowed-values (point) key)
14869 (and (member value '("[ ]" "[-]" "[X]"))
14870 '("[ ]" "[X]"))))
14871 nval)
14872 (unless allowed
14873 (error "Allowed values for this property have not been defined"))
14874 (if previous (setq allowed (reverse allowed)))
14875 (if (member value allowed)
14876 (setq nval (car (cdr (member value allowed)))))
14877 (setq nval (or nval (car allowed)))
14878 (if (equal nval value)
14879 (error "Only one allowed value for this property"))
14880 (org-at-property-p)
14881 (replace-match (concat " :" key ": " nval) t t)
14882 (org-indent-line-function)
14883 (beginning-of-line 1)
14884 (skip-chars-forward " \t")
14885 (run-hook-with-args 'org-property-changed-functions key nval)))
14887 (defun org-find-olp (path &optional this-buffer)
14888 "Return a marker pointing to the entry at outline path OLP.
14889 If anything goes wrong, throw an error.
14890 You can wrap this call to catch the error like this:
14892 (condition-case msg
14893 (org-mobile-locate-entry (match-string 4))
14894 (error (nth 1 msg)))
14896 The return value will then be either a string with the error message,
14897 or a marker if everything is OK.
14899 If THIS-BUFFER is set, the outline path does not contain a file,
14900 only headings."
14901 (let* ((file (if this-buffer buffer-file-name (pop path)))
14902 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14903 (level 1)
14904 (lmin 1)
14905 (lmax 1)
14906 limit re end found pos heading cnt flevel)
14907 (unless buffer (error "File not found :%s" file))
14908 (with-current-buffer buffer
14909 (save-excursion
14910 (save-restriction
14911 (widen)
14912 (setq limit (point-max))
14913 (goto-char (point-min))
14914 (while (setq heading (pop path))
14915 (setq re (format org-complex-heading-regexp-format
14916 (regexp-quote heading)))
14917 (setq cnt 0 pos (point))
14918 (while (re-search-forward re end t)
14919 (setq level (- (match-end 1) (match-beginning 1)))
14920 (if (and (>= level lmin) (<= level lmax))
14921 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14922 (when (= cnt 0) (error "Heading not found on level %d: %s"
14923 lmax heading))
14924 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14925 lmax heading))
14926 (goto-char found)
14927 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14928 (setq end (save-excursion (org-end-of-subtree t t))))
14929 (when (org-at-heading-p)
14930 (move-marker (make-marker) (point))))))))
14932 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14933 "Find node HEADING in BUFFER.
14934 Return a marker to the heading if it was found, or nil if not.
14935 If POS-ONLY is set, return just the position instead of a marker.
14937 The heading text must match exact, but it may have a TODO keyword,
14938 a priority cookie and tags in the standard locations."
14939 (with-current-buffer (or buffer (current-buffer))
14940 (save-excursion
14941 (save-restriction
14942 (widen)
14943 (goto-char (point-min))
14944 (let (case-fold-search)
14945 (if (re-search-forward
14946 (format org-complex-heading-regexp-format
14947 (regexp-quote heading)) nil t)
14948 (if pos-only
14949 (match-beginning 0)
14950 (move-marker (make-marker) (match-beginning 0)))))))))
14952 (defun org-find-exact-heading-in-directory (heading &optional dir)
14953 "Find Org node headline HEADING in all .org files in directory DIR.
14954 When the target headline is found, return a marker to this location."
14955 (let ((files (directory-files (or dir default-directory)
14956 nil "\\`[^.#].*\\.org\\'"))
14957 file visiting m buffer)
14958 (catch 'found
14959 (while (setq file (pop files))
14960 (message "trying %s" file)
14961 (setq visiting (org-find-base-buffer-visiting file))
14962 (setq buffer (or visiting (find-file-noselect file)))
14963 (setq m (org-find-exact-headline-in-buffer
14964 heading buffer))
14965 (when (and (not m) (not visiting)) (kill-buffer buffer))
14966 (and m (throw 'found m))))))
14968 (defun org-find-entry-with-id (ident)
14969 "Locate the entry that contains the ID property with exact value IDENT.
14970 IDENT can be a string, a symbol or a number, this function will search for
14971 the string representation of it.
14972 Return the position where this entry starts, or nil if there is no such entry."
14973 (interactive "sID: ")
14974 (let ((id (cond
14975 ((stringp ident) ident)
14976 ((symbol-name ident) (symbol-name ident))
14977 ((numberp ident) (number-to-string ident))
14978 (t (error "IDENT %s must be a string, symbol or number" ident))))
14979 (case-fold-search nil))
14980 (save-excursion
14981 (save-restriction
14982 (widen)
14983 (goto-char (point-min))
14984 (when (re-search-forward
14985 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14986 nil t)
14987 (org-back-to-heading t)
14988 (point))))))
14990 ;;;; Timestamps
14992 (defvar org-last-changed-timestamp nil)
14993 (defvar org-last-inserted-timestamp nil
14994 "The last time stamp inserted with `org-insert-time-stamp'.")
14995 (defvar org-time-was-given) ; dynamically scoped parameter
14996 (defvar org-end-time-was-given) ; dynamically scoped parameter
14997 (defvar org-ts-what) ; dynamically scoped parameter
14999 (defun org-time-stamp (arg &optional inactive)
15000 "Prompt for a date/time and insert a time stamp.
15001 If the user specifies a time like HH:MM, or if this command is called
15002 with a prefix argument, the time stamp will contain date and time.
15003 Otherwise, only the date will be included. All parts of a date not
15004 specified by the user will be filled in from the current date/time.
15005 So if you press just return without typing anything, the time stamp
15006 will represent the current date/time. If there is already a timestamp
15007 at the cursor, it will be modified."
15008 (interactive "P")
15009 (let* ((ts nil)
15010 (default-time
15011 ;; Default time is either today, or, when entering a range,
15012 ;; the range start.
15013 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15014 (save-excursion
15015 (re-search-backward
15016 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15017 (- (point) 20) t)))
15018 (apply 'encode-time (org-parse-time-string (match-string 1)))
15019 (current-time)))
15020 (default-input (and ts (org-get-compact-tod ts)))
15021 (repeater (save-excursion
15022 (save-match-data
15023 (beginning-of-line)
15024 (when (re-search-forward
15025 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15026 (save-excursion (progn (end-of-line) (point))) t)
15027 (match-string 0)))))
15028 org-time-was-given org-end-time-was-given time)
15029 (cond
15030 ((and (org-at-timestamp-p t)
15031 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15032 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15033 (insert "--")
15034 (setq time (let ((this-command this-command))
15035 (org-read-date arg 'totime nil nil
15036 default-time default-input inactive)))
15037 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15038 ((org-at-timestamp-p t)
15039 (setq time (let ((this-command this-command))
15040 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15041 (when (org-at-timestamp-p t) ; just to get the match data
15042 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15043 (replace-match "")
15044 (setq org-last-changed-timestamp
15045 (org-insert-time-stamp
15046 time (or org-time-was-given arg)
15047 inactive nil nil (list org-end-time-was-given)))
15048 (when repeater (goto-char (1- (point))) (insert " " repeater)
15049 (setq org-last-changed-timestamp
15050 (concat (substring org-last-inserted-timestamp 0 -1)
15051 " " repeater ">"))))
15052 (message "Timestamp updated"))
15054 (setq time (let ((this-command this-command))
15055 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15056 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15057 nil nil (list org-end-time-was-given))))))
15059 ;; FIXME: can we use this for something else, like computing time differences?
15060 (defun org-get-compact-tod (s)
15061 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15062 (let* ((t1 (match-string 1 s))
15063 (h1 (string-to-number (match-string 2 s)))
15064 (m1 (string-to-number (match-string 3 s)))
15065 (t2 (and (match-end 4) (match-string 5 s)))
15066 (h2 (and t2 (string-to-number (match-string 6 s))))
15067 (m2 (and t2 (string-to-number (match-string 7 s))))
15068 dh dm)
15069 (if (not t2)
15071 (setq dh (- h2 h1) dm (- m2 m1))
15072 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15073 (concat t1 "+" (number-to-string dh)
15074 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15076 (defun org-time-stamp-inactive (&optional arg)
15077 "Insert an inactive time stamp.
15078 An inactive time stamp is enclosed in square brackets instead of angle
15079 brackets. It is inactive in the sense that it does not trigger agenda entries,
15080 does not link to the calendar and cannot be changed with the S-cursor keys.
15081 So these are more for recording a certain time/date."
15082 (interactive "P")
15083 (org-time-stamp arg 'inactive))
15085 (defvar org-date-ovl (make-overlay 1 1))
15086 (overlay-put org-date-ovl 'face 'org-date-selected)
15087 (org-detach-overlay org-date-ovl)
15089 (defvar org-ans1) ; dynamically scoped parameter
15090 (defvar org-ans2) ; dynamically scoped parameter
15092 (defvar org-plain-time-of-day-regexp) ; defined below
15094 (defvar org-overriding-default-time nil) ; dynamically scoped
15095 (defvar org-read-date-overlay nil)
15096 (defvar org-dcst nil) ; dynamically scoped
15097 (defvar org-read-date-history nil)
15098 (defvar org-read-date-final-answer nil)
15099 (defvar org-read-date-analyze-futurep nil)
15100 (defvar org-read-date-analyze-forced-year nil)
15101 (defvar org-read-date-inactive)
15103 (defun org-read-date (&optional org-with-time to-time from-string prompt
15104 default-time default-input inactive)
15105 "Read a date, possibly a time, and make things smooth for the user.
15106 The prompt will suggest to enter an ISO date, but you can also enter anything
15107 which will at least partially be understood by `parse-time-string'.
15108 Unrecognized parts of the date will default to the current day, month, year,
15109 hour and minute. If this command is called to replace a timestamp at point,
15110 or to enter the second timestamp of a range, the default time is taken
15111 from the existing stamp. Furthermore, the command prefers the future,
15112 so if you are giving a date where the year is not given, and the day-month
15113 combination is already past in the current year, it will assume you
15114 mean next year. For details, see the manual. A few examples:
15116 3-2-5 --> 2003-02-05
15117 feb 15 --> currentyear-02-15
15118 2/15 --> currentyear-02-15
15119 sep 12 9 --> 2009-09-12
15120 12:45 --> today 12:45
15121 22 sept 0:34 --> currentyear-09-22 0:34
15122 12 --> currentyear-currentmonth-12
15123 Fri --> nearest Friday (today or later)
15124 etc.
15126 Furthermore you can specify a relative date by giving, as the *first* thing
15127 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15128 change in days weeks, months, years.
15129 With a single plus or minus, the date is relative to today. With a double
15130 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15131 +4d --> four days from today
15132 +4 --> same as above
15133 +2w --> two weeks from today
15134 ++5 --> five days from default date
15136 The function understands only English month and weekday abbreviations.
15138 While prompting, a calendar is popped up - you can also select the
15139 date with the mouse (button 1). The calendar shows a period of three
15140 months. To scroll it to other months, use the keys `>' and `<'.
15141 If you don't like the calendar, turn it off with
15142 \(setq org-read-date-popup-calendar nil)
15144 With optional argument TO-TIME, the date will immediately be converted
15145 to an internal time.
15146 With an optional argument WITH-TIME, the prompt will suggest to also
15147 insert a time. Note that when WITH-TIME is not set, you can still
15148 enter a time, and this function will inform the calling routine about
15149 this change. The calling routine may then choose to change the format
15150 used to insert the time stamp into the buffer to include the time.
15151 With optional argument FROM-STRING, read from this string instead from
15152 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15153 the time/date that is used for everything that is not specified by the
15154 user."
15155 (require 'parse-time)
15156 (let* ((org-time-stamp-rounding-minutes
15157 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15158 (org-dcst org-display-custom-times)
15159 (ct (org-current-time))
15160 (org-def (or org-overriding-default-time default-time ct))
15161 (org-defdecode (decode-time org-def))
15162 (dummy (progn
15163 (when (< (nth 2 org-defdecode) org-extend-today-until)
15164 (setcar (nthcdr 2 org-defdecode) -1)
15165 (setcar (nthcdr 1 org-defdecode) 59)
15166 (setq org-def (apply 'encode-time org-defdecode)
15167 org-defdecode (decode-time org-def)))))
15168 (calendar-frame-setup nil)
15169 (calendar-setup nil)
15170 (calendar-move-hook nil)
15171 (calendar-view-diary-initially-flag nil)
15172 (calendar-view-holidays-initially-flag nil)
15173 (timestr (format-time-string
15174 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15175 (prompt (concat (if prompt (concat prompt " ") "")
15176 (format "Date+time [%s]: " timestr)))
15177 ans (org-ans0 "") org-ans1 org-ans2 final)
15179 (cond
15180 (from-string (setq ans from-string))
15181 (org-read-date-popup-calendar
15182 (save-excursion
15183 (save-window-excursion
15184 (calendar)
15185 (org-eval-in-calendar '(setq cursor-type nil) t)
15186 (unwind-protect
15187 (progn
15188 (calendar-forward-day (- (time-to-days org-def)
15189 (calendar-absolute-from-gregorian
15190 (calendar-current-date))))
15191 (org-eval-in-calendar nil t)
15192 (let* ((old-map (current-local-map))
15193 (map (copy-keymap calendar-mode-map))
15194 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15195 (org-defkey map (kbd "RET") 'org-calendar-select)
15196 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15197 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15198 (org-defkey minibuffer-local-map [(meta shift left)]
15199 (lambda () (interactive)
15200 (org-eval-in-calendar '(calendar-backward-month 1))))
15201 (org-defkey minibuffer-local-map [(meta shift right)]
15202 (lambda () (interactive)
15203 (org-eval-in-calendar '(calendar-forward-month 1))))
15204 (org-defkey minibuffer-local-map [(meta shift up)]
15205 (lambda () (interactive)
15206 (org-eval-in-calendar '(calendar-backward-year 1))))
15207 (org-defkey minibuffer-local-map [(meta shift down)]
15208 (lambda () (interactive)
15209 (org-eval-in-calendar '(calendar-forward-year 1))))
15210 (org-defkey minibuffer-local-map [?\e (shift left)]
15211 (lambda () (interactive)
15212 (org-eval-in-calendar '(calendar-backward-month 1))))
15213 (org-defkey minibuffer-local-map [?\e (shift right)]
15214 (lambda () (interactive)
15215 (org-eval-in-calendar '(calendar-forward-month 1))))
15216 (org-defkey minibuffer-local-map [?\e (shift up)]
15217 (lambda () (interactive)
15218 (org-eval-in-calendar '(calendar-backward-year 1))))
15219 (org-defkey minibuffer-local-map [?\e (shift down)]
15220 (lambda () (interactive)
15221 (org-eval-in-calendar '(calendar-forward-year 1))))
15222 (org-defkey minibuffer-local-map [(shift up)]
15223 (lambda () (interactive)
15224 (org-eval-in-calendar '(calendar-backward-week 1))))
15225 (org-defkey minibuffer-local-map [(shift down)]
15226 (lambda () (interactive)
15227 (org-eval-in-calendar '(calendar-forward-week 1))))
15228 (org-defkey minibuffer-local-map [(shift left)]
15229 (lambda () (interactive)
15230 (org-eval-in-calendar '(calendar-backward-day 1))))
15231 (org-defkey minibuffer-local-map [(shift right)]
15232 (lambda () (interactive)
15233 (org-eval-in-calendar '(calendar-forward-day 1))))
15234 (org-defkey minibuffer-local-map ">"
15235 (lambda () (interactive)
15236 (org-eval-in-calendar '(scroll-calendar-left 1))))
15237 (org-defkey minibuffer-local-map "<"
15238 (lambda () (interactive)
15239 (org-eval-in-calendar '(scroll-calendar-right 1))))
15240 (org-defkey minibuffer-local-map "\C-v"
15241 (lambda () (interactive)
15242 (org-eval-in-calendar
15243 '(calendar-scroll-left-three-months 1))))
15244 (org-defkey minibuffer-local-map "\M-v"
15245 (lambda () (interactive)
15246 (org-eval-in-calendar
15247 '(calendar-scroll-right-three-months 1))))
15248 (run-hooks 'org-read-date-minibuffer-setup-hook)
15249 (unwind-protect
15250 (progn
15251 (use-local-map map)
15252 (setq org-read-date-inactive inactive)
15253 (add-hook 'post-command-hook 'org-read-date-display)
15254 (setq org-ans0 (read-string prompt default-input
15255 'org-read-date-history nil))
15256 ;; org-ans0: from prompt
15257 ;; org-ans1: from mouse click
15258 ;; org-ans2: from calendar motion
15259 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15260 (remove-hook 'post-command-hook 'org-read-date-display)
15261 (use-local-map old-map)
15262 (when org-read-date-overlay
15263 (delete-overlay org-read-date-overlay)
15264 (setq org-read-date-overlay nil)))))
15265 (bury-buffer "*Calendar*")))))
15267 (t ; Naked prompt only
15268 (unwind-protect
15269 (setq ans (read-string prompt default-input
15270 'org-read-date-history timestr))
15271 (when org-read-date-overlay
15272 (delete-overlay org-read-date-overlay)
15273 (setq org-read-date-overlay nil)))))
15275 (setq final (org-read-date-analyze ans org-def org-defdecode))
15277 (when org-read-date-analyze-forced-year
15278 (message "Year was forced into %s"
15279 (if org-read-date-force-compatible-dates
15280 "compatible range (1970-2037)"
15281 "range representable on this machine"))
15282 (ding))
15284 ;; One round trip to get rid of 34th of August and stuff like that....
15285 (setq final (decode-time (apply 'encode-time final)))
15287 (setq org-read-date-final-answer ans)
15289 (if to-time
15290 (apply 'encode-time final)
15291 (if (and (boundp 'org-time-was-given) org-time-was-given)
15292 (format "%04d-%02d-%02d %02d:%02d"
15293 (nth 5 final) (nth 4 final) (nth 3 final)
15294 (nth 2 final) (nth 1 final))
15295 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15297 (defvar org-def)
15298 (defvar org-defdecode)
15299 (defvar org-with-time)
15300 (defun org-read-date-display ()
15301 "Display the current date prompt interpretation in the minibuffer."
15302 (when org-read-date-display-live
15303 (when org-read-date-overlay
15304 (delete-overlay org-read-date-overlay))
15305 (when (minibufferp (current-buffer))
15306 (save-excursion
15307 (end-of-line 1)
15308 (while (not (equal (buffer-substring
15309 (max (point-min) (- (point) 4)) (point))
15310 " "))
15311 (insert " ")))
15312 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15313 " " (or org-ans1 org-ans2)))
15314 (org-end-time-was-given nil)
15315 (f (org-read-date-analyze ans org-def org-defdecode))
15316 (fmts (if org-dcst
15317 org-time-stamp-custom-formats
15318 org-time-stamp-formats))
15319 (fmt (if (or org-with-time
15320 (and (boundp 'org-time-was-given) org-time-was-given))
15321 (cdr fmts)
15322 (car fmts)))
15323 (txt (format-time-string fmt (apply 'encode-time f)))
15324 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15325 (txt (concat "=> " txt)))
15326 (when (and org-end-time-was-given
15327 (string-match org-plain-time-of-day-regexp txt))
15328 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15329 org-end-time-was-given
15330 (substring txt (match-end 0)))))
15331 (when org-read-date-analyze-futurep
15332 (setq txt (concat txt " (=>F)")))
15333 (setq org-read-date-overlay
15334 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15335 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15337 (defun org-read-date-analyze (ans org-def org-defdecode)
15338 "Analyze the combined answer of the date prompt."
15339 ;; FIXME: cleanup and comment
15340 (let ((nowdecode (decode-time (current-time)))
15341 delta deltan deltaw deltadef year month day
15342 hour minute second wday pm h2 m2 tl wday1
15343 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15344 (setq org-read-date-analyze-futurep nil
15345 org-read-date-analyze-forced-year nil)
15346 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15347 (setq ans "+0"))
15349 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15350 (setq ans (replace-match "" t t ans)
15351 deltan (car delta)
15352 deltaw (nth 1 delta)
15353 deltadef (nth 2 delta)))
15355 ;; Check if there is an iso week date in there
15356 ;; If yes, store the info and postpone interpreting it until the rest
15357 ;; of the parsing is done
15358 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15359 (setq iso-year (if (match-end 1)
15360 (org-small-year-to-year
15361 (string-to-number (match-string 1 ans))))
15362 iso-weekday (if (match-end 3)
15363 (string-to-number (match-string 3 ans)))
15364 iso-week (string-to-number (match-string 2 ans)))
15365 (setq ans (replace-match "" t t ans)))
15367 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15368 (when (string-match
15369 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15370 (setq year (if (match-end 2)
15371 (string-to-number (match-string 2 ans))
15372 (progn (setq kill-year t)
15373 (string-to-number (format-time-string "%Y"))))
15374 month (string-to-number (match-string 3 ans))
15375 day (string-to-number (match-string 4 ans)))
15376 (if (< year 100) (setq year (+ 2000 year)))
15377 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15378 t nil ans)))
15380 ;; Help matching dotted european dates
15381 (when (string-match
15382 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15383 (setq year (if (match-end 3)
15384 (string-to-number (match-string 3 ans))
15385 (progn (setq kill-year t)
15386 (string-to-number (format-time-string "%Y"))))
15387 day (string-to-number (match-string 1 ans))
15388 month (string-to-number (match-string 2 ans))
15389 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15390 t nil ans)))
15392 ;; Help matching american dates, like 5/30 or 5/30/7
15393 (when (string-match
15394 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15395 (setq year (if (match-end 4)
15396 (string-to-number (match-string 4 ans))
15397 (progn (setq kill-year t)
15398 (string-to-number (format-time-string "%Y"))))
15399 month (string-to-number (match-string 1 ans))
15400 day (string-to-number (match-string 2 ans)))
15401 (if (< year 100) (setq year (+ 2000 year)))
15402 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15403 t nil ans)))
15404 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15405 ;; If there is a time with am/pm, and *no* time without it, we convert
15406 ;; so that matching will be successful.
15407 (loop for i from 1 to 2 do ; twice, for end time as well
15408 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15409 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15410 (setq hour (string-to-number (match-string 1 ans))
15411 minute (if (match-end 3)
15412 (string-to-number (match-string 3 ans))
15414 pm (equal ?p
15415 (string-to-char (downcase (match-string 4 ans)))))
15416 (if (and (= hour 12) (not pm))
15417 (setq hour 0)
15418 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15419 (setq ans (replace-match (format "%02d:%02d" hour minute)
15420 t t ans))))
15422 ;; Check if a time range is given as a duration
15423 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15424 (setq hour (string-to-number (match-string 1 ans))
15425 h2 (+ hour (string-to-number (match-string 3 ans)))
15426 minute (string-to-number (match-string 2 ans))
15427 m2 (+ minute (if (match-end 5) (string-to-number
15428 (match-string 5 ans))0)))
15429 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15430 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15431 t t ans)))
15433 ;; Check if there is a time range
15434 (when (boundp 'org-end-time-was-given)
15435 (setq org-time-was-given nil)
15436 (when (and (string-match org-plain-time-of-day-regexp ans)
15437 (match-end 8))
15438 (setq org-end-time-was-given (match-string 8 ans))
15439 (setq ans (concat (substring ans 0 (match-beginning 7))
15440 (substring ans (match-end 7))))))
15442 (setq tl (parse-time-string ans)
15443 day (or (nth 3 tl) (nth 3 org-defdecode))
15444 month (or (nth 4 tl)
15445 (if (and org-read-date-prefer-future
15446 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15447 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15448 (nth 4 org-defdecode)))
15449 year (or (and (not kill-year) (nth 5 tl))
15450 (if (and org-read-date-prefer-future
15451 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15452 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15453 (nth 5 org-defdecode)))
15454 hour (or (nth 2 tl) (nth 2 org-defdecode))
15455 minute (or (nth 1 tl) (nth 1 org-defdecode))
15456 second (or (nth 0 tl) 0)
15457 wday (nth 6 tl))
15459 (when (and (eq org-read-date-prefer-future 'time)
15460 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15461 (equal day (nth 3 nowdecode))
15462 (equal month (nth 4 nowdecode))
15463 (equal year (nth 5 nowdecode))
15464 (nth 2 tl)
15465 (or (< (nth 2 tl) (nth 2 nowdecode))
15466 (and (= (nth 2 tl) (nth 2 nowdecode))
15467 (nth 1 tl)
15468 (< (nth 1 tl) (nth 1 nowdecode)))))
15469 (setq day (1+ day)
15470 futurep t))
15472 ;; Special date definitions below
15473 (cond
15474 (iso-week
15475 ;; There was an iso week
15476 (require 'cal-iso)
15477 (setq futurep nil)
15478 (setq year (or iso-year year)
15479 day (or iso-weekday wday 1)
15480 wday nil ; to make sure that the trigger below does not match
15481 iso-date (calendar-gregorian-from-absolute
15482 (calendar-absolute-from-iso
15483 (list iso-week day year))))
15484 ; FIXME: Should we also push ISO weeks into the future?
15485 ; (when (and org-read-date-prefer-future
15486 ; (not iso-year)
15487 ; (< (calendar-absolute-from-gregorian iso-date)
15488 ; (time-to-days (current-time))))
15489 ; (setq year (1+ year)
15490 ; iso-date (calendar-gregorian-from-absolute
15491 ; (calendar-absolute-from-iso
15492 ; (list iso-week day year)))))
15493 (setq month (car iso-date)
15494 year (nth 2 iso-date)
15495 day (nth 1 iso-date)))
15496 (deltan
15497 (setq futurep nil)
15498 (unless deltadef
15499 (let ((now (decode-time (current-time))))
15500 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15501 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15502 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15503 ((equal deltaw "m") (setq month (+ month deltan)))
15504 ((equal deltaw "y") (setq year (+ year deltan)))))
15505 ((and wday (not (nth 3 tl)))
15506 (setq futurep nil)
15507 ;; Weekday was given, but no day, so pick that day in the week
15508 ;; on or after the derived date.
15509 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15510 (unless (equal wday wday1)
15511 (setq day (+ day (% (- wday wday1 -7) 7))))))
15512 (if (and (boundp 'org-time-was-given)
15513 (nth 2 tl))
15514 (setq org-time-was-given t))
15515 (if (< year 100) (setq year (+ 2000 year)))
15516 ;; Check of the date is representable
15517 (if org-read-date-force-compatible-dates
15518 (progn
15519 (if (< year 1970)
15520 (setq year 1970 org-read-date-analyze-forced-year t))
15521 (if (> year 2037)
15522 (setq year 2037 org-read-date-analyze-forced-year t)))
15523 (condition-case nil
15524 (ignore (encode-time second minute hour day month year))
15525 (error
15526 (setq year (nth 5 org-defdecode))
15527 (setq org-read-date-analyze-forced-year t))))
15528 (setq org-read-date-analyze-futurep futurep)
15529 (list second minute hour day month year)))
15531 (defvar parse-time-weekdays)
15532 (defun org-read-date-get-relative (s today default)
15533 "Check string S for special relative date string.
15534 TODAY and DEFAULT are internal times, for today and for a default.
15535 Return shift list (N what def-flag)
15536 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15537 N is the number of WHATs to shift.
15538 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15539 the DEFAULT date rather than TODAY."
15540 (require 'parse-time)
15541 (when (and
15542 (string-match
15543 (concat
15544 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15545 "\\([0-9]+\\)?"
15546 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15547 "\\([ \t]\\|$\\)") s)
15548 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15549 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15550 (string-to-char (substring (match-string 1 s) -1))
15551 ?+))
15552 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15553 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15554 (what (if (match-end 3) (match-string 3 s) "d"))
15555 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15556 (date (if rel default today))
15557 (wday (nth 6 (decode-time date)))
15558 delta)
15559 (if wday1
15560 (progn
15561 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15562 (if (= dir ?-) (setq delta (- delta 7)))
15563 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15564 (list delta "d" rel))
15565 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15567 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15568 "Turn a user-specified date into the internal representation.
15569 The internal representation needed by the calendar is (month day year).
15570 This is a wrapper to handle the brain-dead convention in calendar that
15571 user function argument order change dependent on argument order."
15572 (if (boundp 'calendar-date-style)
15573 (cond
15574 ((eq calendar-date-style 'american)
15575 (list arg1 arg2 arg3))
15576 ((eq calendar-date-style 'european)
15577 (list arg2 arg1 arg3))
15578 ((eq calendar-date-style 'iso)
15579 (list arg2 arg3 arg1)))
15580 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15581 (if (org-bound-and-true-p european-calendar-style)
15582 (list arg2 arg1 arg3)
15583 (list arg1 arg2 arg3)))))
15585 (defun org-eval-in-calendar (form &optional keepdate)
15586 "Eval FORM in the calendar window and return to current window.
15587 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15588 otherwise stick to the current value of `org-ans2'."
15589 (let ((sf (selected-frame))
15590 (sw (selected-window)))
15591 (select-window (get-buffer-window "*Calendar*" t))
15592 (eval form)
15593 (when (and (not keepdate) (calendar-cursor-to-date))
15594 (let* ((date (calendar-cursor-to-date))
15595 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15596 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15597 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15598 (select-window sw)
15599 (org-select-frame-set-input-focus sf)))
15601 (defun org-calendar-select ()
15602 "Return to `org-read-date' with the date currently selected.
15603 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15604 (interactive)
15605 (when (calendar-cursor-to-date)
15606 (let* ((date (calendar-cursor-to-date))
15607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15608 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15609 (if (active-minibuffer-window) (exit-minibuffer))))
15611 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15612 "Insert a date stamp for the date given by the internal TIME.
15613 WITH-HM means use the stamp format that includes the time of the day.
15614 INACTIVE means use square brackets instead of angular ones, so that the
15615 stamp will not contribute to the agenda.
15616 PRE and POST are optional strings to be inserted before and after the
15617 stamp.
15618 The command returns the inserted time stamp."
15619 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15620 stamp)
15621 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15622 (insert-before-markers (or pre ""))
15623 (when (listp extra)
15624 (setq extra (car extra))
15625 (if (and (stringp extra)
15626 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15627 (setq extra (format "-%02d:%02d"
15628 (string-to-number (match-string 1 extra))
15629 (string-to-number (match-string 2 extra))))
15630 (setq extra nil)))
15631 (when extra
15632 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15633 (insert-before-markers (setq stamp (format-time-string fmt time)))
15634 (insert-before-markers (or post ""))
15635 (setq org-last-inserted-timestamp stamp)))
15637 (defun org-toggle-time-stamp-overlays ()
15638 "Toggle the use of custom time stamp formats."
15639 (interactive)
15640 (setq org-display-custom-times (not org-display-custom-times))
15641 (unless org-display-custom-times
15642 (let ((p (point-min)) (bmp (buffer-modified-p)))
15643 (while (setq p (next-single-property-change p 'display))
15644 (if (and (get-text-property p 'display)
15645 (eq (get-text-property p 'face) 'org-date))
15646 (remove-text-properties
15647 p (setq p (next-single-property-change p 'display))
15648 '(display t))))
15649 (set-buffer-modified-p bmp)))
15650 (if (featurep 'xemacs)
15651 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15652 (org-restart-font-lock)
15653 (setq org-table-may-need-update t)
15654 (if org-display-custom-times
15655 (message "Time stamps are overlaid with custom format")
15656 (message "Time stamp overlays removed")))
15658 (defun org-display-custom-time (beg end)
15659 "Overlay modified time stamp format over timestamp between BEG and END."
15660 (let* ((ts (buffer-substring beg end))
15661 t1 w1 with-hm tf time str w2 (off 0))
15662 (save-match-data
15663 (setq t1 (org-parse-time-string ts t))
15664 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15665 (setq off (- (match-end 0) (match-beginning 0)))))
15666 (setq end (- end off))
15667 (setq w1 (- end beg)
15668 with-hm (and (nth 1 t1) (nth 2 t1))
15669 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15670 time (org-fix-decoded-time t1)
15671 str (org-add-props
15672 (format-time-string
15673 (substring tf 1 -1) (apply 'encode-time time))
15674 nil 'mouse-face 'highlight)
15675 w2 (length str))
15676 (if (not (= w2 w1))
15677 (add-text-properties (1+ beg) (+ 2 beg)
15678 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15679 (if (featurep 'xemacs)
15680 (progn
15681 (put-text-property beg end 'invisible t)
15682 (put-text-property beg end 'end-glyph (make-glyph str)))
15683 (put-text-property beg end 'display str))))
15685 (defun org-translate-time (string)
15686 "Translate all timestamps in STRING to custom format.
15687 But do this only if the variable `org-display-custom-times' is set."
15688 (when org-display-custom-times
15689 (save-match-data
15690 (let* ((start 0)
15691 (re org-ts-regexp-both)
15692 t1 with-hm inactive tf time str beg end)
15693 (while (setq start (string-match re string start))
15694 (setq beg (match-beginning 0)
15695 end (match-end 0)
15696 t1 (save-match-data
15697 (org-parse-time-string (substring string beg end) t))
15698 with-hm (and (nth 1 t1) (nth 2 t1))
15699 inactive (equal (substring string beg (1+ beg)) "[")
15700 tf (funcall (if with-hm 'cdr 'car)
15701 org-time-stamp-custom-formats)
15702 time (org-fix-decoded-time t1)
15703 str (format-time-string
15704 (concat
15705 (if inactive "[" "<") (substring tf 1 -1)
15706 (if inactive "]" ">"))
15707 (apply 'encode-time time))
15708 string (replace-match str t t string)
15709 start (+ start (length str)))))))
15710 string)
15712 (defun org-fix-decoded-time (time)
15713 "Set 0 instead of nil for the first 6 elements of time.
15714 Don't touch the rest."
15715 (let ((n 0))
15716 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15718 (defun org-days-to-time (timestamp-string)
15719 "Difference between TIMESTAMP-STRING and now in days."
15720 (- (time-to-days (org-time-string-to-time timestamp-string))
15721 (time-to-days (current-time))))
15723 (defun org-deadline-close (timestamp-string &optional ndays)
15724 "Is the time in TIMESTAMP-STRING close to the current date?"
15725 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15726 (and (< (org-days-to-time timestamp-string) ndays)
15727 (not (org-entry-is-done-p))))
15729 (defun org-get-wdays (ts)
15730 "Get the deadline lead time appropriate for timestring TS."
15731 (cond
15732 ((<= org-deadline-warning-days 0)
15733 ;; 0 or negative, enforce this value no matter what
15734 (- org-deadline-warning-days))
15735 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15736 ;; lead time is specified.
15737 (floor (* (string-to-number (match-string 1 ts))
15738 (cdr (assoc (match-string 2 ts)
15739 '(("d" . 1) ("w" . 7)
15740 ("m" . 30.4) ("y" . 365.25)))))))
15741 ;; go for the default.
15742 (t org-deadline-warning-days)))
15744 (defun org-calendar-select-mouse (ev)
15745 "Return to `org-read-date' with the date currently selected.
15746 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15747 (interactive "e")
15748 (mouse-set-point ev)
15749 (when (calendar-cursor-to-date)
15750 (let* ((date (calendar-cursor-to-date))
15751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15752 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15753 (if (active-minibuffer-window) (exit-minibuffer))))
15755 (defun org-check-deadlines (ndays)
15756 "Check if there are any deadlines due or past due.
15757 A deadline is considered due if it happens within `org-deadline-warning-days'
15758 days from today's date. If the deadline appears in an entry marked DONE,
15759 it is not shown. The prefix arg NDAYS can be used to test that many
15760 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15761 (interactive "P")
15762 (let* ((org-warn-days
15763 (cond
15764 ((equal ndays '(4)) 100000)
15765 (ndays (prefix-numeric-value ndays))
15766 (t (abs org-deadline-warning-days))))
15767 (case-fold-search nil)
15768 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15769 (callback
15770 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15772 (message "%d deadlines past-due or due within %d days"
15773 (org-occur regexp nil callback)
15774 org-warn-days)))
15776 (defun org-check-before-date (date)
15777 "Check if there are deadlines or scheduled entries before DATE."
15778 (interactive (list (org-read-date)))
15779 (let ((case-fold-search nil)
15780 (regexp (concat "\\<\\(" org-deadline-string
15781 "\\|" org-scheduled-string
15782 "\\) *<\\([^>]+\\)>"))
15783 (callback
15784 (lambda () (time-less-p
15785 (org-time-string-to-time (match-string 2))
15786 (org-time-string-to-time date)))))
15787 (message "%d entries before %s"
15788 (org-occur regexp nil callback) date)))
15790 (defun org-check-after-date (date)
15791 "Check if there are deadlines or scheduled entries after DATE."
15792 (interactive (list (org-read-date)))
15793 (let ((case-fold-search nil)
15794 (regexp (concat "\\<\\(" org-deadline-string
15795 "\\|" org-scheduled-string
15796 "\\) *<\\([^>]+\\)>"))
15797 (callback
15798 (lambda () (not
15799 (time-less-p
15800 (org-time-string-to-time (match-string 2))
15801 (org-time-string-to-time date))))))
15802 (message "%d entries after %s"
15803 (org-occur regexp nil callback) date)))
15805 (defun org-check-dates-range (start-date end-date)
15806 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15807 (interactive (list (org-read-date nil nil nil "Range starts")
15808 (org-read-date nil nil nil "Range end")))
15809 (let ((case-fold-search nil)
15810 (regexp (concat "\\<\\(" org-deadline-string
15811 "\\|" org-scheduled-string
15812 "\\) *<\\([^>]+\\)>"))
15813 (callback
15814 (lambda ()
15815 (let ((match (match-string 2)))
15816 (and
15817 (not (time-less-p
15818 (org-time-string-to-time match)
15819 (org-time-string-to-time start-date)))
15820 (time-less-p
15821 (org-time-string-to-time match)
15822 (org-time-string-to-time end-date)))))))
15823 (message "%d entries between %s and %s"
15824 (org-occur regexp nil callback) start-date end-date)))
15826 (defun org-evaluate-time-range (&optional to-buffer)
15827 "Evaluate a time range by computing the difference between start and end.
15828 Normally the result is just printed in the echo area, but with prefix arg
15829 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15830 If the time range is actually in a table, the result is inserted into the
15831 next column.
15832 For time difference computation, a year is assumed to be exactly 365
15833 days in order to avoid rounding problems."
15834 (interactive "P")
15836 (org-clock-update-time-maybe)
15837 (save-excursion
15838 (unless (org-at-date-range-p t)
15839 (goto-char (point-at-bol))
15840 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15841 (if (not (org-at-date-range-p t))
15842 (error "Not at a time-stamp range, and none found in current line")))
15843 (let* ((ts1 (match-string 1))
15844 (ts2 (match-string 2))
15845 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15846 (match-end (match-end 0))
15847 (time1 (org-time-string-to-time ts1))
15848 (time2 (org-time-string-to-time ts2))
15849 (t1 (org-float-time time1))
15850 (t2 (org-float-time time2))
15851 (diff (abs (- t2 t1)))
15852 (negative (< (- t2 t1) 0))
15853 ;; (ys (floor (* 365 24 60 60)))
15854 (ds (* 24 60 60))
15855 (hs (* 60 60))
15856 (fy "%dy %dd %02d:%02d")
15857 (fy1 "%dy %dd")
15858 (fd "%dd %02d:%02d")
15859 (fd1 "%dd")
15860 (fh "%02d:%02d")
15861 y d h m align)
15862 (if havetime
15863 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15865 d (floor (/ diff ds)) diff (mod diff ds)
15866 h (floor (/ diff hs)) diff (mod diff hs)
15867 m (floor (/ diff 60)))
15868 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15870 d (floor (+ (/ diff ds) 0.5))
15871 h 0 m 0))
15872 (if (not to-buffer)
15873 (message "%s" (org-make-tdiff-string y d h m))
15874 (if (org-at-table-p)
15875 (progn
15876 (goto-char match-end)
15877 (setq align t)
15878 (and (looking-at " *|") (goto-char (match-end 0))))
15879 (goto-char match-end))
15880 (if (looking-at
15881 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15882 (replace-match ""))
15883 (if negative (insert " -"))
15884 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15885 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15886 (insert " " (format fh h m))))
15887 (if align (org-table-align))
15888 (message "Time difference inserted")))))
15890 (defun org-make-tdiff-string (y d h m)
15891 (let ((fmt "")
15892 (l nil))
15893 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15894 l (push y l)))
15895 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15896 l (push d l)))
15897 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15898 l (push h l)))
15899 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15900 l (push m l)))
15901 (apply 'format fmt (nreverse l))))
15903 (defun org-time-string-to-time (s &optional buffer pos)
15904 (condition-case errdata
15905 (apply 'encode-time (org-parse-time-string s))
15906 (error (error "Bad timestamp `%s'%s\nError was: %s"
15907 s (if (not (and buffer pos))
15909 (format " at %d in buffer `%s'" pos buffer))
15910 (cdr errdata)))))
15912 (defun org-time-string-to-seconds (s)
15913 (org-float-time (org-time-string-to-time s)))
15915 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15916 "Convert a time stamp to an absolute day number.
15917 If there is a specifier for a cyclic time stamp, get the closest date to
15918 DAYNR.
15919 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15920 The variable date is bound by the calendar when this is called."
15921 (cond
15922 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15923 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15924 daynr
15925 (+ daynr 1000)))
15926 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15927 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15928 (time-to-days (current-time))) (match-string 0 s)
15929 prefer show-all))
15930 (t (time-to-days
15931 (condition-case errdata
15932 (apply 'encode-time (org-parse-time-string s))
15933 (error (error "Bad timestamp `%s'%s\nError was: %s"
15934 s (if (not (and buffer pos))
15936 (format " at %d in buffer `%s'" pos buffer))
15937 (cdr errdata))))))))
15939 (defun org-days-to-iso-week (days)
15940 "Return the iso week number."
15941 (require 'cal-iso)
15942 (car (calendar-iso-from-absolute days)))
15944 (defun org-small-year-to-year (year)
15945 "Convert 2-digit years into 4-digit years.
15946 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15947 The year 2000 cannot be abbreviated. Any year larger than 99
15948 is returned unchanged."
15949 (if (< year 38)
15950 (setq year (+ 2000 year))
15951 (if (< year 100)
15952 (setq year (+ 1900 year))))
15953 year)
15955 (defun org-time-from-absolute (d)
15956 "Return the time corresponding to date D.
15957 D may be an absolute day number, or a calendar-type list (month day year)."
15958 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15959 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15961 (defun org-calendar-holiday ()
15962 "List of holidays, for Diary display in Org-mode."
15963 (require 'holidays)
15964 (let ((hl (funcall
15965 (if (fboundp 'calendar-check-holidays)
15966 'calendar-check-holidays 'check-calendar-holidays) date)))
15967 (if hl (mapconcat 'identity hl "; "))))
15969 (defun org-diary-sexp-entry (sexp entry date)
15970 "Process a SEXP diary ENTRY for DATE."
15971 (require 'diary-lib)
15972 (let ((result (if calendar-debug-sexp
15973 (let ((stack-trace-on-error t))
15974 (eval (car (read-from-string sexp))))
15975 (condition-case nil
15976 (eval (car (read-from-string sexp)))
15977 (error
15978 (beep)
15979 (message "Bad sexp at line %d in %s: %s"
15980 (org-current-line)
15981 (buffer-file-name) sexp)
15982 (sleep-for 2))))))
15983 (cond ((stringp result) (split-string result "; "))
15984 ((and (consp result)
15985 (not (consp (cdr result)))
15986 (stringp (cdr result))) (cdr result))
15987 ((and (consp result)
15988 (stringp (car result))) result)
15989 (result entry)
15990 (t nil))))
15992 (defun org-diary-to-ical-string (frombuf)
15993 "Get iCalendar entries from diary entries in buffer FROMBUF.
15994 This uses the icalendar.el library."
15995 (let* ((tmpdir (if (featurep 'xemacs)
15996 (temp-directory)
15997 temporary-file-directory))
15998 (tmpfile (make-temp-name
15999 (expand-file-name "orgics" tmpdir)))
16000 buf rtn b e)
16001 (with-current-buffer frombuf
16002 (icalendar-export-region (point-min) (point-max) tmpfile)
16003 (setq buf (find-buffer-visiting tmpfile))
16004 (set-buffer buf)
16005 (goto-char (point-min))
16006 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16007 (setq b (match-beginning 0)))
16008 (goto-char (point-max))
16009 (if (re-search-backward "^END:VEVENT" nil t)
16010 (setq e (match-end 0)))
16011 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16012 (kill-buffer buf)
16013 (delete-file tmpfile)
16014 rtn))
16016 (defun org-closest-date (start current change prefer show-all)
16017 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16018 When PREFER is `past', return a date that is either CURRENT or past.
16019 When PREFER is `future', return a date that is either CURRENT or future.
16020 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16021 ;; Make the proper lists from the dates
16022 (catch 'exit
16023 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16024 dn dw sday cday n1 n2 n0
16025 d m y y1 y2 date1 date2 nmonths nm ny m2)
16027 (setq start (org-date-to-gregorian start)
16028 current (org-date-to-gregorian
16029 (if show-all
16030 current
16031 (time-to-days (current-time))))
16032 sday (calendar-absolute-from-gregorian start)
16033 cday (calendar-absolute-from-gregorian current))
16035 (if (<= cday sday) (throw 'exit sday))
16037 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16038 (setq dn (string-to-number (match-string 1 change))
16039 dw (cdr (assoc (match-string 2 change) a1)))
16040 (error "Invalid change specifier: %s" change))
16041 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16042 (cond
16043 ((eq dw 'day)
16044 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16045 n2 (+ n1 dn)))
16046 ((eq dw 'year)
16047 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16048 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16049 (setq date1 (list m d y1)
16050 n1 (calendar-absolute-from-gregorian date1)
16051 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16052 n2 (calendar-absolute-from-gregorian date2)))
16053 ((eq dw 'month)
16054 ;; approx number of month between the two dates
16055 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16056 ;; How often does dn fit in there?
16057 (setq d (nth 1 start) m (car start) y (nth 2 start)
16058 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16059 m (+ m nm)
16060 ny (floor (/ m 12))
16061 y (+ y ny)
16062 m (- m (* ny 12)))
16063 (while (> m 12) (setq m (- m 12) y (1+ y)))
16064 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16065 (setq m2 (+ m dn) y2 y)
16066 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16067 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16068 (while (<= n2 cday)
16069 (setq n1 n2 m m2 y y2)
16070 (setq m2 (+ m dn) y2 y)
16071 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16072 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16073 ;; Make sure n1 is the earlier date
16074 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16075 (if show-all
16076 (cond
16077 ((eq prefer 'past) (if (= cday n2) n2 n1))
16078 ((eq prefer 'future) (if (= cday n1) n1 n2))
16079 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16080 (cond
16081 ((eq prefer 'past) (if (= cday n2) n2 n1))
16082 ((eq prefer 'future) (if (= cday n1) n1 n2))
16083 (t (if (= cday n1) n1 n2)))))))
16085 (defun org-date-to-gregorian (date)
16086 "Turn any specification of DATE into a Gregorian date for the calendar."
16087 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16088 ((and (listp date) (= (length date) 3)) date)
16089 ((stringp date)
16090 (setq date (org-parse-time-string date))
16091 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16092 ((listp date)
16093 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16095 (defun org-parse-time-string (s &optional nodefault)
16096 "Parse the standard Org-mode time string.
16097 This should be a lot faster than the normal `parse-time-string'.
16098 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16099 hour and minute fields will be nil if not given."
16100 (if (string-match org-ts-regexp0 s)
16101 (list 0
16102 (if (or (match-beginning 8) (not nodefault))
16103 (string-to-number (or (match-string 8 s) "0")))
16104 (if (or (match-beginning 7) (not nodefault))
16105 (string-to-number (or (match-string 7 s) "0")))
16106 (string-to-number (match-string 4 s))
16107 (string-to-number (match-string 3 s))
16108 (string-to-number (match-string 2 s))
16109 nil nil nil)
16110 (error "Not a standard Org-mode time string: %s" s)))
16112 (defun org-timestamp-up (&optional arg)
16113 "Increase the date item at the cursor by one.
16114 If the cursor is on the year, change the year. If it is on the month,
16115 the day or the time, change that.
16116 With prefix ARG, change by that many units."
16117 (interactive "p")
16118 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16120 (defun org-timestamp-down (&optional arg)
16121 "Decrease the date item at the cursor by one.
16122 If the cursor is on the year, change the year. If it is on the month,
16123 the day or the time, change that.
16124 With prefix ARG, change by that many units."
16125 (interactive "p")
16126 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16128 (defun org-timestamp-up-day (&optional arg)
16129 "Increase the date in the time stamp by one day.
16130 With prefix ARG, change that many days."
16131 (interactive "p")
16132 (if (and (not (org-at-timestamp-p t))
16133 (org-at-heading-p))
16134 (org-todo 'up)
16135 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16137 (defun org-timestamp-down-day (&optional arg)
16138 "Decrease the date in the time stamp by one day.
16139 With prefix ARG, change that many days."
16140 (interactive "p")
16141 (if (and (not (org-at-timestamp-p t))
16142 (org-at-heading-p))
16143 (org-todo 'down)
16144 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16146 (defun org-at-timestamp-p (&optional inactive-ok)
16147 "Determine if the cursor is in or at a timestamp."
16148 (interactive)
16149 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16150 (pos (point))
16151 (ans (or (looking-at tsr)
16152 (save-excursion
16153 (skip-chars-backward "^[<\n\r\t")
16154 (if (> (point) (point-min)) (backward-char 1))
16155 (and (looking-at tsr)
16156 (> (- (match-end 0) pos) -1))))))
16157 (and ans
16158 (boundp 'org-ts-what)
16159 (setq org-ts-what
16160 (cond
16161 ((= pos (match-beginning 0)) 'bracket)
16162 ;; Point is considered to be "on the bracket" whether
16163 ;; it's really on it or right after it.
16164 ((or (= pos (1- (match-end 0)))
16165 (= pos (match-end 0))) 'bracket)
16166 ((org-pos-in-match-range pos 2) 'year)
16167 ((org-pos-in-match-range pos 3) 'month)
16168 ((org-pos-in-match-range pos 7) 'hour)
16169 ((org-pos-in-match-range pos 8) 'minute)
16170 ((or (org-pos-in-match-range pos 4)
16171 (org-pos-in-match-range pos 5)) 'day)
16172 ((and (> pos (or (match-end 8) (match-end 5)))
16173 (< pos (match-end 0)))
16174 (- pos (or (match-end 8) (match-end 5))))
16175 (t 'day))))
16176 ans))
16178 (defun org-toggle-timestamp-type ()
16179 "Toggle the type (<active> or [inactive]) of a time stamp."
16180 (interactive)
16181 (when (org-at-timestamp-p t)
16182 (let ((beg (match-beginning 0)) (end (match-end 0))
16183 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16184 (save-excursion
16185 (goto-char beg)
16186 (while (re-search-forward "[][<>]" end t)
16187 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16188 t t)))
16189 (message "Timestamp is now %sactive"
16190 (if (equal (char-after beg) ?<) "" "in")))))
16192 (defun org-timestamp-change (n &optional what updown)
16193 "Change the date in the time stamp at point.
16194 The date will be changed by N times WHAT. WHAT can be `day', `month',
16195 `year', `minute', `second'. If WHAT is not given, the cursor position
16196 in the timestamp determines what will be changed."
16197 (let ((origin (point)) origin-cat
16198 with-hm inactive
16199 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16200 org-ts-what
16201 extra rem
16202 ts time time0)
16203 (if (not (org-at-timestamp-p t))
16204 (error "Not at a timestamp"))
16205 (if (and (not what) (eq org-ts-what 'bracket))
16206 (org-toggle-timestamp-type)
16207 ;; Point isn't on brackets. Remember the part of the time-stamp
16208 ;; the point was in. Indeed, size of time-stamps may change,
16209 ;; but point must be kept in the same category nonetheless.
16210 (setq origin-cat org-ts-what)
16211 (if (and (not what) (not (eq org-ts-what 'day))
16212 org-display-custom-times
16213 (get-text-property (point) 'display)
16214 (not (get-text-property (1- (point)) 'display)))
16215 (setq org-ts-what 'day))
16216 (setq org-ts-what (or what org-ts-what)
16217 inactive (= (char-after (match-beginning 0)) ?\[)
16218 ts (match-string 0))
16219 (replace-match "")
16220 (if (string-match
16221 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16223 (setq extra (match-string 1 ts)))
16224 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16225 (setq with-hm t))
16226 (setq time0 (org-parse-time-string ts))
16227 (when (and updown
16228 (eq org-ts-what 'minute)
16229 (not current-prefix-arg))
16230 ;; This looks like s-up and s-down. Change by one rounding step.
16231 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16232 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16233 (setcar (cdr time0) (+ (nth 1 time0)
16234 (if (> n 0) (- rem) (- dm rem))))))
16235 (setq time
16236 (encode-time (or (car time0) 0)
16237 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16238 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16239 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16240 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16241 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16242 (nthcdr 6 time0)))
16243 (when (and (member org-ts-what '(hour minute))
16244 extra
16245 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16246 (setq extra (org-modify-ts-extra
16247 extra
16248 (if (eq org-ts-what 'hour) 2 5)
16249 n dm)))
16250 (when (integerp org-ts-what)
16251 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16252 (if (eq what 'calendar)
16253 (let ((cal-date (org-get-date-from-calendar)))
16254 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16255 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16256 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16257 (setcar time0 (or (car time0) 0))
16258 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16259 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16260 (setq time (apply 'encode-time time0))))
16261 ;; Insert the new time-stamp, and ensure point stays in the same
16262 ;; category as before (i.e. not after the last position in that
16263 ;; category).
16264 (let ((pos (point)))
16265 ;; Stay before inserted string. `save-excursion' is of no use.
16266 (setq org-last-changed-timestamp
16267 (org-insert-time-stamp time with-hm inactive nil nil extra))
16268 (goto-char pos))
16269 (save-match-data
16270 (looking-at org-ts-regexp3)
16271 (goto-char (cond
16272 ;; `day' category ends before `hour' if any, or at
16273 ;; the end of the day name.
16274 ((eq origin-cat 'day)
16275 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16276 ((eq origin-cat 'hour) (min (match-end 7) origin))
16277 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16278 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16279 ;; `year' and `month' have both fixed size: point
16280 ;; couldn't have moved into another part.
16281 (t origin))))
16282 ;; Update clock if on a CLOCK line.
16283 (org-clock-update-time-maybe)
16284 ;; Try to recenter the calendar window, if any.
16285 (if (and org-calendar-follow-timestamp-change
16286 (get-buffer-window "*Calendar*" t)
16287 (memq org-ts-what '(day month year)))
16288 (org-recenter-calendar (time-to-days time))))))
16290 (defun org-modify-ts-extra (s pos n dm)
16291 "Change the different parts of the lead-time and repeat fields in timestamp."
16292 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16293 ng h m new rem)
16294 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16295 (cond
16296 ((or (org-pos-in-match-range pos 2)
16297 (org-pos-in-match-range pos 3))
16298 (setq m (string-to-number (match-string 3 s))
16299 h (string-to-number (match-string 2 s)))
16300 (if (org-pos-in-match-range pos 2)
16301 (setq h (+ h n))
16302 (setq n (* dm (org-no-warnings (signum n))))
16303 (when (not (= 0 (setq rem (% m dm))))
16304 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16305 (setq m (+ m n)))
16306 (if (< m 0) (setq m (+ m 60) h (1- h)))
16307 (if (> m 59) (setq m (- m 60) h (1+ h)))
16308 (setq h (min 24 (max 0 h)))
16309 (setq ng 1 new (format "-%02d:%02d" h m)))
16310 ((org-pos-in-match-range pos 6)
16311 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16312 ((org-pos-in-match-range pos 5)
16313 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16315 ((org-pos-in-match-range pos 9)
16316 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16317 ((org-pos-in-match-range pos 8)
16318 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16320 (when ng
16321 (setq s (concat
16322 (substring s 0 (match-beginning ng))
16324 (substring s (match-end ng))))))
16327 (defun org-recenter-calendar (date)
16328 "If the calendar is visible, recenter it to DATE."
16329 (let ((cwin (get-buffer-window "*Calendar*" t)))
16330 (when cwin
16331 (let ((calendar-move-hook nil))
16332 (with-selected-window cwin
16333 (calendar-goto-date (if (listp date) date
16334 (calendar-gregorian-from-absolute date))))))))
16336 (defun org-goto-calendar (&optional arg)
16337 "Go to the Emacs calendar at the current date.
16338 If there is a time stamp in the current line, go to that date.
16339 A prefix ARG can be used to force the current date."
16340 (interactive "P")
16341 (let ((tsr org-ts-regexp) diff
16342 (calendar-move-hook nil)
16343 (calendar-view-holidays-initially-flag nil)
16344 (calendar-view-diary-initially-flag nil))
16345 (if (or (org-at-timestamp-p)
16346 (save-excursion
16347 (beginning-of-line 1)
16348 (looking-at (concat ".*" tsr))))
16349 (let ((d1 (time-to-days (current-time)))
16350 (d2 (time-to-days
16351 (org-time-string-to-time (match-string 1)))))
16352 (setq diff (- d2 d1))))
16353 (calendar)
16354 (calendar-goto-today)
16355 (if (and diff (not arg)) (calendar-forward-day diff))))
16357 (defun org-get-date-from-calendar ()
16358 "Return a list (month day year) of date at point in calendar."
16359 (with-current-buffer "*Calendar*"
16360 (save-match-data
16361 (calendar-cursor-to-date))))
16363 (defun org-date-from-calendar ()
16364 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16365 If there is already a time stamp at the cursor position, update it."
16366 (interactive)
16367 (if (org-at-timestamp-p t)
16368 (org-timestamp-change 0 'calendar)
16369 (let ((cal-date (org-get-date-from-calendar)))
16370 (org-insert-time-stamp
16371 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16373 (defun org-minutes-to-hh:mm-string (m)
16374 "Compute H:MM from a number of minutes."
16375 (let ((h (/ m 60)))
16376 (setq m (- m (* 60 h)))
16377 (format org-time-clocksum-format h m)))
16379 (defun org-hh:mm-string-to-minutes (s)
16380 "Convert a string H:MM to a number of minutes.
16381 If the string is just a number, interpret it as minutes.
16382 In fact, the first hh:mm or number in the string will be taken,
16383 there can be extra stuff in the string.
16384 If no number is found, the return value is 0."
16385 (cond
16386 ((integerp s) s)
16387 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16388 (+ (* (string-to-number (match-string 1 s)) 60)
16389 (string-to-number (match-string 2 s))))
16390 ((string-match "\\([0-9]+\\)" s)
16391 (string-to-number (match-string 1 s)))
16392 (t 0)))
16394 (defcustom org-effort-durations
16395 `(("h" . 60)
16396 ("d" . ,(* 60 8))
16397 ("w" . ,(* 60 8 5))
16398 ("m" . ,(* 60 8 5 4))
16399 ("y" . ,(* 60 8 5 40)))
16400 "Conversion factor to minutes for an effort modifier.
16402 Each entry has the form (MODIFIER . MINUTES).
16404 In an effort string, a number followed by MODIFIER is multiplied
16405 by the specified number of MINUTES to obtain an effort in
16406 minutes.
16408 For example, if the value of this variable is ((\"hours\" . 60)), then an
16409 effort string \"2hours\" is equivalent to 120 minutes."
16410 :group 'org-agenda
16411 :version "24.1"
16412 :type '(alist :key-type (string :tag "Modifier")
16413 :value-type (number :tag "Minutes")))
16415 (defun org-duration-string-to-minutes (s &optional output-to-string)
16416 "Convert a duration string S to minutes.
16418 A bare number is interpreted as minutes, modifiers can be set by
16419 customizing `org-effort-durations' (which see).
16421 Entries containing a colon are interpreted as H:MM by
16422 `org-hh:mm-string-to-minutes'."
16423 (let ((result 0)
16424 (re (concat "\\([0-9.]+\\) *\\("
16425 (regexp-opt (mapcar 'car org-effort-durations))
16426 "\\)")))
16427 (while (string-match re s)
16428 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16429 (string-to-number (match-string 1 s))))
16430 (setq s (replace-match "" nil t s)))
16431 (setq result (floor result))
16432 (incf result (org-hh:mm-string-to-minutes s))
16433 (if output-to-string (number-to-string result) result)))
16435 ;;;; Files
16437 (defun org-save-all-org-buffers ()
16438 "Save all Org-mode buffers without user confirmation."
16439 (interactive)
16440 (message "Saving all Org-mode buffers...")
16441 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16442 (when (featurep 'org-id) (org-id-locations-save))
16443 (message "Saving all Org-mode buffers... done"))
16445 (defun org-revert-all-org-buffers ()
16446 "Revert all Org-mode buffers.
16447 Prompt for confirmation when there are unsaved changes.
16448 Be sure you know what you are doing before letting this function
16449 overwrite your changes.
16451 This function is useful in a setup where one tracks org files
16452 with a version control system, to revert on one machine after pulling
16453 changes from another. I believe the procedure must be like this:
16455 1. M-x org-save-all-org-buffers
16456 2. Pull changes from the other machine, resolve conflicts
16457 3. M-x org-revert-all-org-buffers"
16458 (interactive)
16459 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16460 (error "Abort"))
16461 (save-excursion
16462 (save-window-excursion
16463 (mapc
16464 (lambda (b)
16465 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16466 (with-current-buffer b buffer-file-name))
16467 (org-pop-to-buffer-same-window b)
16468 (revert-buffer t 'no-confirm)))
16469 (buffer-list))
16470 (when (and (featurep 'org-id) org-id-track-globally)
16471 (org-id-locations-load)))))
16473 ;;;; Agenda files
16475 ;;;###autoload
16476 (defun org-switchb (&optional arg)
16477 "Switch between Org buffers.
16478 With one prefix argument, restrict available buffers to files.
16479 With two prefix arguments, restrict available buffers to agenda files.
16481 Defaults to `iswitchb' for buffer name completion.
16482 Set `org-completion-use-ido' to make it use ido instead."
16483 (interactive "P")
16484 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16485 ((equal arg '(16)) (org-buffer-list 'agenda))
16486 (t (org-buffer-list))))
16487 (org-completion-use-iswitchb org-completion-use-iswitchb)
16488 (org-completion-use-ido org-completion-use-ido))
16489 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16490 (setq org-completion-use-iswitchb t))
16491 (org-pop-to-buffer-same-window
16492 (org-icompleting-read "Org buffer: "
16493 (mapcar 'list (mapcar 'buffer-name blist))
16494 nil t))))
16496 ;;; Define some older names previously used for this functionality
16497 ;;;###autoload
16498 (defalias 'org-ido-switchb 'org-switchb)
16499 ;;;###autoload
16500 (defalias 'org-iswitchb 'org-switchb)
16502 (defun org-buffer-list (&optional predicate exclude-tmp)
16503 "Return a list of Org buffers.
16504 PREDICATE can be `export', `files' or `agenda'.
16506 export restrict the list to Export buffers.
16507 files restrict the list to buffers visiting Org files.
16508 agenda restrict the list to buffers visiting agenda files.
16510 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16511 (let* ((bfn nil)
16512 (agenda-files (and (eq predicate 'agenda)
16513 (mapcar 'file-truename (org-agenda-files t))))
16514 (filter
16515 (cond
16516 ((eq predicate 'files)
16517 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16518 ((eq predicate 'export)
16519 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16520 ((eq predicate 'agenda)
16521 (lambda (b)
16522 (with-current-buffer b
16523 (and (derived-mode-p 'org-mode)
16524 (setq bfn (buffer-file-name b))
16525 (member (file-truename bfn) agenda-files)))))
16526 (t (lambda (b) (with-current-buffer b
16527 (or (derived-mode-p 'org-mode)
16528 (string-match "\*Org .*Export"
16529 (buffer-name b)))))))))
16530 (delq nil
16531 (mapcar
16532 (lambda(b)
16533 (if (and (funcall filter b)
16534 (or (not exclude-tmp)
16535 (not (string-match "tmp" (buffer-name b)))))
16537 nil))
16538 (buffer-list)))))
16540 (defun org-agenda-files (&optional unrestricted archives)
16541 "Get the list of agenda files.
16542 Optional UNRESTRICTED means return the full list even if a restriction
16543 is currently in place.
16544 When ARCHIVES is t, include all archive files that are really being
16545 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16546 `org-agenda-archives-mode' is t."
16547 (let ((files
16548 (cond
16549 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16550 ((stringp org-agenda-files) (org-read-agenda-file-list))
16551 ((listp org-agenda-files) org-agenda-files)
16552 (t (error "Invalid value of `org-agenda-files'")))))
16553 (setq files (apply 'append
16554 (mapcar (lambda (f)
16555 (if (file-directory-p f)
16556 (directory-files
16557 f t org-agenda-file-regexp)
16558 (list f)))
16559 files)))
16560 (when org-agenda-skip-unavailable-files
16561 (setq files (delq nil
16562 (mapcar (function
16563 (lambda (file)
16564 (and (file-readable-p file) file)))
16565 files))))
16566 (when (or (eq archives t)
16567 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16568 (setq files (org-add-archive-files files)))
16569 files))
16571 (defun org-agenda-file-p (&optional file)
16572 "Return non-nil, if FILE is an agenda file.
16573 If FILE is omitted, use the file associated with the current
16574 buffer."
16575 (member (or file (buffer-file-name))
16576 (org-agenda-files t)))
16578 (defun org-edit-agenda-file-list ()
16579 "Edit the list of agenda files.
16580 Depending on setup, this either uses customize to edit the variable
16581 `org-agenda-files', or it visits the file that is holding the list. In the
16582 latter case, the buffer is set up in a way that saving it automatically kills
16583 the buffer and restores the previous window configuration."
16584 (interactive)
16585 (if (stringp org-agenda-files)
16586 (let ((cw (current-window-configuration)))
16587 (find-file org-agenda-files)
16588 (org-set-local 'org-window-configuration cw)
16589 (org-add-hook 'after-save-hook
16590 (lambda ()
16591 (set-window-configuration
16592 (prog1 org-window-configuration
16593 (kill-buffer (current-buffer))))
16594 (org-install-agenda-files-menu)
16595 (message "New agenda file list installed"))
16596 nil 'local)
16597 (message "%s" (substitute-command-keys
16598 "Edit list and finish with \\[save-buffer]")))
16599 (customize-variable 'org-agenda-files)))
16601 (defun org-store-new-agenda-file-list (list)
16602 "Set new value for the agenda file list and save it correctly."
16603 (if (stringp org-agenda-files)
16604 (let ((fe (org-read-agenda-file-list t)) b u)
16605 (while (setq b (find-buffer-visiting org-agenda-files))
16606 (kill-buffer b))
16607 (with-temp-file org-agenda-files
16608 (insert
16609 (mapconcat
16610 (lambda (f) ;; Keep un-expanded entries.
16611 (if (setq u (assoc f fe))
16612 (cdr u)
16614 list "\n")
16615 "\n")))
16616 (let ((org-mode-hook nil) (org-inhibit-startup t)
16617 (org-insert-mode-line-in-empty-file nil))
16618 (setq org-agenda-files list)
16619 (customize-save-variable 'org-agenda-files org-agenda-files))))
16621 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16622 "Read the list of agenda files from a file.
16623 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16624 filenames, used by `org-store-new-agenda-file-list' to write back
16625 un-expanded file names."
16626 (when (file-directory-p org-agenda-files)
16627 (error "`org-agenda-files' cannot be a single directory"))
16628 (when (stringp org-agenda-files)
16629 (with-temp-buffer
16630 (insert-file-contents org-agenda-files)
16631 (mapcar
16632 (lambda (f)
16633 (let ((e (expand-file-name (substitute-in-file-name f)
16634 org-directory)))
16635 (if pair-with-expansion
16636 (cons e f)
16637 e)))
16638 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16640 ;;;###autoload
16641 (defun org-cycle-agenda-files ()
16642 "Cycle through the files in `org-agenda-files'.
16643 If the current buffer visits an agenda file, find the next one in the list.
16644 If the current buffer does not, find the first agenda file."
16645 (interactive)
16646 (let* ((fs (org-agenda-files t))
16647 (files (append fs (list (car fs))))
16648 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16649 file)
16650 (unless files (error "No agenda files"))
16651 (catch 'exit
16652 (while (setq file (pop files))
16653 (if (equal (file-truename file) tcf)
16654 (when (car files)
16655 (find-file (car files))
16656 (throw 'exit t))))
16657 (find-file (car fs)))
16658 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16660 (defun org-agenda-file-to-front (&optional to-end)
16661 "Move/add the current file to the top of the agenda file list.
16662 If the file is not present in the list, it is added to the front. If it is
16663 present, it is moved there. With optional argument TO-END, add/move to the
16664 end of the list."
16665 (interactive "P")
16666 (let ((org-agenda-skip-unavailable-files nil)
16667 (file-alist (mapcar (lambda (x)
16668 (cons (file-truename x) x))
16669 (org-agenda-files t)))
16670 (ctf (file-truename buffer-file-name))
16671 x had)
16672 (setq x (assoc ctf file-alist) had x)
16674 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16675 (if to-end
16676 (setq file-alist (append (delq x file-alist) (list x)))
16677 (setq file-alist (cons x (delq x file-alist))))
16678 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16679 (org-install-agenda-files-menu)
16680 (message "File %s to %s of agenda file list"
16681 (if had "moved" "added") (if to-end "end" "front"))))
16683 (defun org-remove-file (&optional file)
16684 "Remove current file from the list of files in variable `org-agenda-files'.
16685 These are the files which are being checked for agenda entries.
16686 Optional argument FILE means use this file instead of the current."
16687 (interactive)
16688 (let* ((org-agenda-skip-unavailable-files nil)
16689 (file (or file buffer-file-name))
16690 (true-file (file-truename file))
16691 (afile (abbreviate-file-name file))
16692 (files (delq nil (mapcar
16693 (lambda (x)
16694 (if (equal true-file
16695 (file-truename x))
16696 nil x))
16697 (org-agenda-files t)))))
16698 (if (not (= (length files) (length (org-agenda-files t))))
16699 (progn
16700 (org-store-new-agenda-file-list files)
16701 (org-install-agenda-files-menu)
16702 (message "Removed file: %s" afile))
16703 (message "File was not in list: %s (not removed)" afile))))
16705 (defun org-file-menu-entry (file)
16706 (vector file (list 'find-file file) t))
16708 (defun org-check-agenda-file (file)
16709 "Make sure FILE exists. If not, ask user what to do."
16710 (when (not (file-exists-p file))
16711 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16712 (abbreviate-file-name file))
16713 (let ((r (downcase (read-char-exclusive))))
16714 (cond
16715 ((equal r ?r)
16716 (org-remove-file file)
16717 (throw 'nextfile t))
16718 (t (error "Abort"))))))
16720 (defun org-get-agenda-file-buffer (file)
16721 "Get a buffer visiting FILE. If the buffer needs to be created, add
16722 it to the list of buffers which might be released later."
16723 (let ((buf (org-find-base-buffer-visiting file)))
16724 (if buf
16725 buf ; just return it
16726 ;; Make a new buffer and remember it
16727 (setq buf (find-file-noselect file))
16728 (if buf (push buf org-agenda-new-buffers))
16729 buf)))
16731 (defun org-release-buffers (blist)
16732 "Release all buffers in list, asking the user for confirmation when needed.
16733 When a buffer is unmodified, it is just killed. When modified, it is saved
16734 \(if the user agrees) and then killed."
16735 (let (buf file)
16736 (while (setq buf (pop blist))
16737 (setq file (buffer-file-name buf))
16738 (when (and (buffer-modified-p buf)
16739 file
16740 (y-or-n-p (format "Save file %s? " file)))
16741 (with-current-buffer buf (save-buffer)))
16742 (kill-buffer buf))))
16744 (defun org-prepare-agenda-buffers (files)
16745 "Create buffers for all agenda files, protect archived trees and comments."
16746 (interactive)
16747 (let ((pa '(:org-archived t))
16748 (pc '(:org-comment t))
16749 (pall '(:org-archived t :org-comment t))
16750 (inhibit-read-only t)
16751 (rea (concat ":" org-archive-tag ":"))
16752 bmp file re)
16753 (save-excursion
16754 (save-restriction
16755 (while (setq file (pop files))
16756 (catch 'nextfile
16757 (if (bufferp file)
16758 (set-buffer file)
16759 (org-check-agenda-file file)
16760 (set-buffer (org-get-agenda-file-buffer file)))
16761 (widen)
16762 (setq bmp (buffer-modified-p))
16763 (org-refresh-category-properties)
16764 (setq org-todo-keywords-for-agenda
16765 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16766 (setq org-done-keywords-for-agenda
16767 (append org-done-keywords-for-agenda org-done-keywords))
16768 (setq org-todo-keyword-alist-for-agenda
16769 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16770 (setq org-drawers-for-agenda
16771 (append org-drawers-for-agenda org-drawers))
16772 (setq org-tag-alist-for-agenda
16773 (append org-tag-alist-for-agenda org-tag-alist))
16775 (save-excursion
16776 (remove-text-properties (point-min) (point-max) pall)
16777 (when org-agenda-skip-archived-trees
16778 (goto-char (point-min))
16779 (while (re-search-forward rea nil t)
16780 (if (org-at-heading-p t)
16781 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16782 (goto-char (point-min))
16783 (setq re (format org-heading-keyword-regexp-format
16784 org-comment-string))
16785 (while (re-search-forward re nil t)
16786 (add-text-properties
16787 (match-beginning 0) (org-end-of-subtree t) pc)))
16788 (set-buffer-modified-p bmp)))))
16789 (setq org-todo-keywords-for-agenda
16790 (org-uniquify org-todo-keywords-for-agenda))
16791 (setq org-todo-keyword-alist-for-agenda
16792 (org-uniquify org-todo-keyword-alist-for-agenda)
16793 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16795 ;;;; Embedded LaTeX
16797 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16798 "Keymap for the minor `org-cdlatex-mode'.")
16800 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16801 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16802 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16803 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16804 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16806 (defvar org-cdlatex-texmathp-advice-is-done nil
16807 "Flag remembering if we have applied the advice to texmathp already.")
16809 (define-minor-mode org-cdlatex-mode
16810 "Toggle the minor `org-cdlatex-mode'.
16811 This mode supports entering LaTeX environment and math in LaTeX fragments
16812 in Org-mode.
16813 \\{org-cdlatex-mode-map}"
16814 nil " OCDL" nil
16815 (when org-cdlatex-mode
16816 (require 'cdlatex)
16817 (run-hooks 'cdlatex-mode-hook)
16818 (cdlatex-compute-tables))
16819 (unless org-cdlatex-texmathp-advice-is-done
16820 (setq org-cdlatex-texmathp-advice-is-done t)
16821 (defadvice texmathp (around org-math-always-on activate)
16822 "Always return t in org-mode buffers.
16823 This is because we want to insert math symbols without dollars even outside
16824 the LaTeX math segments. If Orgmode thinks that point is actually inside
16825 an embedded LaTeX fragment, let texmathp do its job.
16826 \\[org-cdlatex-mode-map]"
16827 (interactive)
16828 (let (p)
16829 (cond
16830 ((not (derived-mode-p 'org-mode)) ad-do-it)
16831 ((eq this-command 'cdlatex-math-symbol)
16832 (setq ad-return-value t
16833 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16835 (let ((p (org-inside-LaTeX-fragment-p)))
16836 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16837 (setq ad-return-value t
16838 texmathp-why '("Org-mode embedded math" . 0))
16839 (if p ad-do-it)))))))))
16841 (defun turn-on-org-cdlatex ()
16842 "Unconditionally turn on `org-cdlatex-mode'."
16843 (org-cdlatex-mode 1))
16845 (defun org-inside-LaTeX-fragment-p ()
16846 "Test if point is inside a LaTeX fragment.
16847 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16848 sequence appearing also before point.
16849 Even though the matchers for math are configurable, this function assumes
16850 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16851 delimiters are skipped when they have been removed by customization.
16852 The return value is nil, or a cons cell with the delimiter and the
16853 position of this delimiter.
16855 This function does a reasonably good job, but can locally be fooled by
16856 for example currency specifications. For example it will assume being in
16857 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16858 fragments that are properly closed, but during editing, we have to live
16859 with the uncertainty caused by missing closing delimiters. This function
16860 looks only before point, not after."
16861 (catch 'exit
16862 (let ((pos (point))
16863 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16864 (lim (progn
16865 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16866 (point)))
16867 dd-on str (start 0) m re)
16868 (goto-char pos)
16869 (when dodollar
16870 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16871 re (nth 1 (assoc "$" org-latex-regexps)))
16872 (while (string-match re str start)
16873 (cond
16874 ((= (match-end 0) (length str))
16875 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16876 ((= (match-end 0) (- (length str) 5))
16877 (throw 'exit nil))
16878 (t (setq start (match-end 0))))))
16879 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16880 (goto-char pos)
16881 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16882 (and (match-beginning 2) (throw 'exit nil))
16883 ;; count $$
16884 (while (re-search-backward "\\$\\$" lim t)
16885 (setq dd-on (not dd-on)))
16886 (goto-char pos)
16887 (if dd-on (cons "$$" m))))))
16889 (defun org-inside-latex-macro-p ()
16890 "Is point inside a LaTeX macro or its arguments?"
16891 (save-match-data
16892 (org-in-regexp
16893 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16895 (defun org-try-cdlatex-tab ()
16896 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16897 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16898 - inside a LaTeX fragment, or
16899 - after the first word in a line, where an abbreviation expansion could
16900 insert a LaTeX environment."
16901 (when org-cdlatex-mode
16902 (cond
16903 ;; Before any word on the line: No expansion possible.
16904 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16905 ;; Just after first word on the line: Expand it. Make sure it
16906 ;; cannot happen on headlines, though.
16907 ((save-excursion
16908 (skip-chars-backward "a-zA-Z0-9*")
16909 (skip-chars-backward " \t")
16910 (and (bolp) (not (org-at-heading-p))))
16911 (cdlatex-tab) t)
16912 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16914 (defun org-cdlatex-underscore-caret (&optional arg)
16915 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16916 Revert to the normal definition outside of these fragments."
16917 (interactive "P")
16918 (if (org-inside-LaTeX-fragment-p)
16919 (call-interactively 'cdlatex-sub-superscript)
16920 (let (org-cdlatex-mode)
16921 (call-interactively (key-binding (vector last-input-event))))))
16923 (defun org-cdlatex-math-modify (&optional arg)
16924 "Execute `cdlatex-math-modify' in LaTeX fragments.
16925 Revert to the normal definition outside of these fragments."
16926 (interactive "P")
16927 (if (org-inside-LaTeX-fragment-p)
16928 (call-interactively 'cdlatex-math-modify)
16929 (let (org-cdlatex-mode)
16930 (call-interactively (key-binding (vector last-input-event))))))
16932 (defvar org-latex-fragment-image-overlays nil
16933 "List of overlays carrying the images of latex fragments.")
16934 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16936 (defun org-remove-latex-fragment-image-overlays ()
16937 "Remove all overlays with LaTeX fragment images in current buffer."
16938 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16939 (setq org-latex-fragment-image-overlays nil))
16941 (defun org-preview-latex-fragment (&optional subtree)
16942 "Preview the LaTeX fragment at point, or all locally or globally.
16943 If the cursor is in a LaTeX fragment, create the image and overlay
16944 it over the source code. If there is no fragment at point, display
16945 all fragments in the current text, from one headline to the next. With
16946 prefix SUBTREE, display all fragments in the current subtree. With a
16947 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16948 the cursor is before the first headline,
16949 display all fragments in the buffer.
16950 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16951 (interactive "P")
16952 (unless buffer-file-name
16953 (error "Can't preview LaTeX fragment in a non-file buffer"))
16954 (org-remove-latex-fragment-image-overlays)
16955 (save-excursion
16956 (save-restriction
16957 (let (beg end at msg)
16958 (cond
16959 ((or (equal subtree '(16))
16960 (not (save-excursion
16961 (re-search-backward org-outline-regexp-bol nil t))))
16962 (setq beg (point-min) end (point-max)
16963 msg "Creating images for buffer...%s"))
16964 ((equal subtree '(4))
16965 (org-back-to-heading)
16966 (setq beg (point) end (org-end-of-subtree t)
16967 msg "Creating images for subtree...%s"))
16969 (if (setq at (org-inside-LaTeX-fragment-p))
16970 (goto-char (max (point-min) (- (cdr at) 2)))
16971 (org-back-to-heading))
16972 (setq beg (point) end (progn (outline-next-heading) (point))
16973 msg (if at "Creating image...%s"
16974 "Creating images for entry...%s"))))
16975 (message msg "")
16976 (narrow-to-region beg end)
16977 (goto-char beg)
16978 (org-format-latex
16979 (concat "ltxpng/" (file-name-sans-extension
16980 (file-name-nondirectory
16981 buffer-file-name)))
16982 default-directory 'overlays msg at 'forbuffer
16983 org-latex-create-formula-image-program)
16984 (message msg "done. Use `C-c C-c' to remove images.")))))
16986 (defvar org-latex-regexps
16987 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16988 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16989 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16990 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16991 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16992 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16993 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16994 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16995 "Regular expressions for matching embedded LaTeX.")
16997 (defvar org-export-have-math nil) ;; dynamic scoping
16998 (defun org-format-latex (prefix &optional dir overlays msg at
16999 forbuffer processing-type)
17000 "Replace LaTeX fragments with links to an image, and produce images.
17001 Some of the options can be changed using the variable
17002 `org-format-latex-options'."
17003 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17004 (let* ((prefixnodir (file-name-nondirectory prefix))
17005 (absprefix (expand-file-name prefix dir))
17006 (todir (file-name-directory absprefix))
17007 (opt org-format-latex-options)
17008 (matchers (plist-get opt :matchers))
17009 (re-list org-latex-regexps)
17010 (org-format-latex-header-extra
17011 (plist-get (org-infile-export-plist) :latex-header-extra))
17012 (cnt 0) txt hash link beg end re e checkdir
17013 executables-checked string
17014 m n block-type block linkfile movefile ov)
17015 ;; Check the different regular expressions
17016 (while (setq e (pop re-list))
17017 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17018 block (if block-type "\n\n" ""))
17019 (when (member m matchers)
17020 (goto-char (point-min))
17021 (while (re-search-forward re nil t)
17022 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17023 (not (get-text-property (match-beginning n)
17024 'org-protected))
17025 (or (not overlays)
17026 (not (eq (get-char-property (match-beginning n)
17027 'org-overlay-type)
17028 'org-latex-overlay))))
17029 (setq org-export-have-math t)
17030 (cond
17031 ((eq processing-type 'verbatim)
17032 ;; Leave the text verbatim, just protect it
17033 (add-text-properties (match-beginning n) (match-end n)
17034 '(org-protected t)))
17035 ((eq processing-type 'mathjax)
17036 ;; Prepare for MathJax processing
17037 (setq string (match-string n))
17038 (if (member m '("$" "$1"))
17039 (save-excursion
17040 (delete-region (match-beginning n) (match-end n))
17041 (goto-char (match-beginning n))
17042 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17043 "\\)")
17044 '(org-protected t))))
17045 (add-text-properties (match-beginning n) (match-end n)
17046 '(org-protected t))))
17047 ((or (eq processing-type 'dvipng)
17048 (eq processing-type 'imagemagick))
17049 ;; Process to an image
17050 (setq txt (match-string n)
17051 beg (match-beginning n) end (match-end n)
17052 cnt (1+ cnt))
17053 (let (print-length print-level) ; make sure full list is printed
17054 (setq hash (sha1 (prin1-to-string
17055 (list org-format-latex-header
17056 org-format-latex-header-extra
17057 org-export-latex-default-packages-alist
17058 org-export-latex-packages-alist
17059 org-format-latex-options
17060 forbuffer txt)))
17061 linkfile (format "%s_%s.png" prefix hash)
17062 movefile (format "%s_%s.png" absprefix hash)))
17063 (setq link (concat block "[[file:" linkfile "]]" block))
17064 (if msg (message msg cnt))
17065 (goto-char beg)
17066 (unless checkdir ; make sure the directory exists
17067 (setq checkdir t)
17068 (or (file-directory-p todir) (make-directory todir t)))
17069 (cond
17070 ((eq processing-type 'dvipng)
17071 (unless executables-checked
17072 (org-check-external-command
17073 "latex" "needed to convert LaTeX fragments to images")
17074 (org-check-external-command
17075 "dvipng" "needed to convert LaTeX fragments to images")
17076 (setq executables-checked t))
17077 (unless (file-exists-p movefile)
17078 (org-create-formula-image-with-dvipng
17079 txt movefile opt forbuffer)))
17080 ((eq processing-type 'imagemagick)
17081 (unless executables-checked
17082 (org-check-external-command
17083 "convert" "you need to install imagemagick")
17084 (setq executables-checked t))
17085 (unless (file-exists-p movefile)
17086 (org-create-formula-image-with-imagemagick
17087 txt movefile opt forbuffer))))
17088 (if overlays
17089 (progn
17090 (mapc (lambda (o)
17091 (if (eq (overlay-get o 'org-overlay-type)
17092 'org-latex-overlay)
17093 (delete-overlay o)))
17094 (overlays-in beg end))
17095 (setq ov (make-overlay beg end))
17096 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17097 (if (featurep 'xemacs)
17098 (progn
17099 (overlay-put ov 'invisible t)
17100 (overlay-put
17101 ov 'end-glyph
17102 (make-glyph (vector 'png :file movefile))))
17103 (overlay-put
17104 ov 'display
17105 (list 'image :type 'png :file movefile :ascent 'center)))
17106 (push ov org-latex-fragment-image-overlays)
17107 (goto-char end))
17108 (delete-region beg end)
17109 (insert (org-add-props link
17110 (list 'org-latex-src
17111 (replace-regexp-in-string
17112 "\"" "" txt)
17113 'org-latex-src-embed-type
17114 (if block-type 'paragraph 'character))))))
17115 ((eq processing-type 'mathml)
17116 ;; Process to MathML
17117 (unless executables-checked
17118 (unless (save-match-data (org-format-latex-mathml-available-p))
17119 (error "LaTeX to MathML converter not configured"))
17120 (setq executables-checked t))
17121 (setq txt (match-string n)
17122 beg (match-beginning n) end (match-end n)
17123 cnt (1+ cnt))
17124 (if msg (message msg cnt))
17125 (goto-char beg)
17126 (delete-region beg end)
17127 (insert (org-format-latex-as-mathml
17128 txt block-type prefix dir)))
17130 (error "Unknown conversion type %s for latex fragments"
17131 processing-type)))))))))
17133 (defun org-create-math-formula (latex-frag &optional mathml-file)
17134 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17135 Use `org-latex-to-mathml-convert-command'. If the conversion is
17136 sucessful, return the portion between \"<math...> </math>\"
17137 elements otherwise return nil. When MATHML-FILE is specified,
17138 write the results in to that file. When invoked as an
17139 interactive command, prompt for LATEX-FRAG, with initial value
17140 set to the current active region and echo the results for user
17141 inspection."
17142 (interactive (list (let ((frag (when (region-active-p)
17143 (buffer-substring-no-properties
17144 (region-beginning) (region-end)))))
17145 (read-string "LaTeX Fragment: " frag nil frag))))
17146 (unless latex-frag (error "Invalid latex-frag"))
17147 (let* ((tmp-in-file (file-relative-name
17148 (make-temp-name (expand-file-name "ltxmathml-in"))))
17149 (ignore (write-region latex-frag nil tmp-in-file))
17150 (tmp-out-file (file-relative-name
17151 (make-temp-name (expand-file-name "ltxmathml-out"))))
17152 (cmd (format-spec
17153 org-latex-to-mathml-convert-command
17154 `((?j . ,(shell-quote-argument
17155 (expand-file-name org-latex-to-mathml-jar-file)))
17156 (?I . ,(shell-quote-argument tmp-in-file))
17157 (?o . ,(shell-quote-argument tmp-out-file)))))
17158 mathml shell-command-output)
17159 (when (org-called-interactively-p 'any)
17160 (unless (org-format-latex-mathml-available-p)
17161 (error "LaTeX to MathML converter not configured")))
17162 (message "Running %s" cmd)
17163 (setq shell-command-output (shell-command-to-string cmd))
17164 (setq mathml
17165 (when (file-readable-p tmp-out-file)
17166 (with-current-buffer (find-file-noselect tmp-out-file t)
17167 (goto-char (point-min))
17168 (when (re-search-forward
17169 (concat
17170 (regexp-quote
17171 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17172 "\\(.\\|\n\\)*"
17173 (regexp-quote "</math>")) nil t)
17174 (prog1 (match-string 0) (kill-buffer))))))
17175 (cond
17176 (mathml
17177 (setq mathml
17178 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17179 (when mathml-file
17180 (write-region mathml nil mathml-file))
17181 (when (org-called-interactively-p 'any)
17182 (message mathml)))
17183 ((message "LaTeX to MathML conversion failed")
17184 (message shell-command-output)))
17185 (delete-file tmp-in-file)
17186 (when (file-exists-p tmp-out-file)
17187 (delete-file tmp-out-file))
17188 mathml))
17190 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17191 prefix &optional dir)
17192 "Use `org-create-math-formula' but check local cache first."
17193 (let* ((absprefix (expand-file-name prefix dir))
17194 (print-length nil) (print-level nil)
17195 (formula-id (concat
17196 "formula-"
17197 (sha1
17198 (prin1-to-string
17199 (list latex-frag
17200 org-latex-to-mathml-convert-command)))))
17201 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17202 (formula-cache-dir (file-name-directory formula-cache)))
17204 (unless (file-directory-p formula-cache-dir)
17205 (make-directory formula-cache-dir t))
17207 (unless (file-exists-p formula-cache)
17208 (org-create-math-formula latex-frag formula-cache))
17210 (if (file-exists-p formula-cache)
17211 ;; Successful conversion. Return the link to MathML file.
17212 (org-add-props
17213 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17214 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17215 'org-latex-src-embed-type (if latex-frag-type
17216 'paragraph 'character)))
17217 ;; Failed conversion. Return the LaTeX fragment verbatim
17218 (add-text-properties
17219 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17220 latex-frag)))
17222 ;; This function borrows from Ganesh Swami's latex2png.el
17223 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17224 "This calls dvipng."
17225 (require 'org-latex)
17226 (let* ((tmpdir (if (featurep 'xemacs)
17227 (temp-directory)
17228 temporary-file-directory))
17229 (texfilebase (make-temp-name
17230 (expand-file-name "orgtex" tmpdir)))
17231 (texfile (concat texfilebase ".tex"))
17232 (dvifile (concat texfilebase ".dvi"))
17233 (pngfile (concat texfilebase ".png"))
17234 (fnh (if (featurep 'xemacs)
17235 (font-height (face-font 'default))
17236 (face-attribute 'default :height nil)))
17237 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17238 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17239 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17240 "Black"))
17241 (bg (or (plist-get options (if buffer :background :html-background))
17242 "Transparent")))
17243 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17244 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17245 (with-temp-file texfile
17246 (insert (org-splice-latex-header
17247 org-format-latex-header
17248 org-export-latex-default-packages-alist
17249 org-export-latex-packages-alist t
17250 org-format-latex-header-extra))
17251 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17252 (require 'org-latex)
17253 (org-export-latex-fix-inputenc))
17254 (let ((dir default-directory))
17255 (condition-case nil
17256 (progn
17257 (cd tmpdir)
17258 (call-process "latex" nil nil nil texfile))
17259 (error nil))
17260 (cd dir))
17261 (if (not (file-exists-p dvifile))
17262 (progn (message "Failed to create dvi file from %s" texfile) nil)
17263 (condition-case nil
17264 (if (featurep 'xemacs)
17265 (call-process "dvipng" nil nil nil
17266 "-fg" fg "-bg" bg
17267 "-T" "tight"
17268 "-o" pngfile
17269 dvifile)
17270 (call-process "dvipng" nil nil nil
17271 "-fg" fg "-bg" bg
17272 "-D" dpi
17273 ;;"-x" scale "-y" scale
17274 "-T" "tight"
17275 "-o" pngfile
17276 dvifile))
17277 (error nil))
17278 (if (not (file-exists-p pngfile))
17279 (if org-format-latex-signal-error
17280 (error "Failed to create png file from %s" texfile)
17281 (message "Failed to create png file from %s" texfile)
17282 nil)
17283 ;; Use the requested file name and clean up
17284 (copy-file pngfile tofile 'replace)
17285 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17286 (if (file-exists-p (concat texfilebase e))
17287 (delete-file (concat texfilebase e))))
17288 pngfile))))
17290 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17291 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17292 "This calls convert, which is included into imagemagick."
17293 (require 'org-latex)
17294 (let* ((tmpdir (if (featurep 'xemacs)
17295 (temp-directory)
17296 temporary-file-directory))
17297 (texfilebase (make-temp-name
17298 (expand-file-name "orgtex" tmpdir)))
17299 (texfile (concat texfilebase ".tex"))
17300 (pdffile (concat texfilebase ".pdf"))
17301 (pngfile (concat texfilebase ".png"))
17302 (fnh (if (featurep 'xemacs)
17303 (font-height (face-font 'default))
17304 (face-attribute 'default :height nil)))
17305 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17306 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17307 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17308 "black"))
17309 (bg (or (plist-get options (if buffer :background :html-background))
17310 "white")))
17311 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17312 (setq fg (org-latex-color-format fg)))
17313 (if (eq bg 'default) (setq bg (org-latex-color :background))
17314 (setq bg (org-latex-color-format
17315 (if (string= bg "Transparent")(setq bg "white")))))
17316 (with-temp-file texfile
17317 (insert (org-splice-latex-header
17318 org-format-latex-header
17319 org-export-latex-default-packages-alist
17320 org-export-latex-packages-alist t
17321 org-format-latex-header-extra))
17322 (insert "\n\\begin{document}\n"
17323 "\\definecolor{fg}{rgb}{" fg "}\n"
17324 "\\definecolor{bg}{rgb}{" bg "}\n"
17325 "\n\\pagecolor{bg}\n"
17326 "\n{\\color{fg}\n"
17327 string
17328 "\n}\n"
17329 "\n\\end{document}\n" )
17330 (require 'org-latex)
17331 (org-export-latex-fix-inputenc))
17332 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17333 (condition-case nil
17334 (progn
17335 (cd tmpdir)
17336 (setq cmds org-latex-to-pdf-process)
17337 (while cmds
17338 (setq latex-frags-cmds (pop cmds))
17339 (if (listp latex-frags-cmds)
17340 (setq cmds nil)
17341 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17342 (while latex-frags-cmds
17343 (setq cmd (pop latex-frags-cmds))
17344 (while (string-match "%b" cmd)
17345 (setq cmd (replace-match
17346 (save-match-data
17347 (shell-quote-argument texfile))
17348 t t cmd)))
17349 (while (string-match "%f" cmd)
17350 (setq cmd (replace-match
17351 (save-match-data
17352 (shell-quote-argument (file-name-nondirectory texfile)))
17353 t t cmd)))
17354 (while (string-match "%o" cmd)
17355 (setq cmd (replace-match
17356 (save-match-data
17357 (shell-quote-argument (file-name-directory texfile)))
17358 t t cmd)))
17359 (setq cmd (split-string cmd))
17360 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17361 (error nil))
17362 (cd dir))
17363 (if (not (file-exists-p pdffile))
17364 (progn (message "Failed to create pdf file from %s" texfile) nil)
17365 (condition-case nil
17366 (if (featurep 'xemacs)
17367 (call-process "convert" nil nil nil
17368 "-density" "96"
17369 "-trim"
17370 "-antialias"
17371 pdffile
17372 "-quality" "100"
17373 ;; "-sharpen" "0x1.0"
17374 pngfile)
17375 (call-process "convert" nil nil nil
17376 "-density" dpi
17377 "-trim"
17378 "-antialias"
17379 pdffile
17380 "-quality" "100"
17381 ; "-sharpen" "0x1.0"
17382 pngfile))
17383 (error nil))
17384 (if (not (file-exists-p pngfile))
17385 (if org-format-latex-signal-error
17386 (error "Failed to create png file from %s" texfile)
17387 (message "Failed to create png file from %s" texfile)
17388 nil)
17389 ;; Use the requested file name and clean up
17390 (copy-file pngfile tofile 'replace)
17391 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17392 (if (file-exists-p (concat texfilebase e))
17393 (delete-file (concat texfilebase e))))
17394 pngfile))))
17396 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17397 "Fill a LaTeX header template TPL.
17398 In the template, the following place holders will be recognized:
17400 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17401 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17402 [PACKAGES] \\usepackage statements for PKG
17403 [NO-PACKAGES] do not include PKG
17404 [EXTRA] the string EXTRA
17405 [NO-EXTRA] do not include EXTRA
17407 For backward compatibility, if both the positive and the negative place
17408 holder is missing, the positive one (without the \"NO-\") will be
17409 assumed to be present at the end of the template.
17410 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17411 EXTRA is a string.
17412 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17413 (let (rpl (end ""))
17414 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17415 (setq rpl (if (or (match-end 1) (not def-pkg))
17416 "" (org-latex-packages-to-string def-pkg snippets-p t))
17417 tpl (replace-match rpl t t tpl))
17418 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17420 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17421 (setq rpl (if (or (match-end 1) (not pkg))
17422 "" (org-latex-packages-to-string pkg snippets-p t))
17423 tpl (replace-match rpl t t tpl))
17424 (if pkg (setq end
17425 (concat end "\n"
17426 (org-latex-packages-to-string pkg snippets-p)))))
17428 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17429 (setq rpl (if (or (match-end 1) (not extra))
17430 "" (concat extra "\n"))
17431 tpl (replace-match rpl t t tpl))
17432 (if (and extra (string-match "\\S-" extra))
17433 (setq end (concat end "\n" extra))))
17435 (if (string-match "\\S-" end)
17436 (concat tpl "\n" end)
17437 tpl)))
17439 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17440 "Turn an alist of packages into a string with the \\usepackage macros."
17441 (setq pkg (mapconcat (lambda(p)
17442 (cond
17443 ((stringp p) p)
17444 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17445 (format "%% Package %s omitted" (cadr p)))
17446 ((equal "" (car p))
17447 (format "\\usepackage{%s}" (cadr p)))
17449 (format "\\usepackage[%s]{%s}"
17450 (car p) (cadr p)))))
17452 "\n"))
17453 (if newline (concat pkg "\n") pkg))
17455 (defun org-dvipng-color (attr)
17456 "Return a RGB color specification for dvipng."
17457 (apply 'format "rgb %s %s %s"
17458 (mapcar 'org-normalize-color
17459 (if (featurep 'xemacs)
17460 (color-rgb-components
17461 (face-property 'default
17462 (cond ((eq attr :foreground) 'foreground)
17463 ((eq attr :background) 'background))))
17464 (color-values (face-attribute 'default attr nil))))))
17466 (defun org-latex-color (attr)
17467 "Return a RGB color for the LaTeX color package."
17468 (apply 'format "%s,%s,%s"
17469 (mapcar 'org-normalize-color
17470 (if (featurep 'xemacs)
17471 (color-rgb-components
17472 (face-property 'default
17473 (cond ((eq attr :foreground) 'foreground)
17474 ((eq attr :background) 'background))))
17475 (color-values (face-attribute 'default attr nil))))))
17477 (defun org-latex-color-format (color-name)
17478 "Convert COLOR-NAME to a RGB color value."
17479 (apply 'format "%s,%s,%s"
17480 (mapcar 'org-normalize-color
17481 (color-values color-name))))
17483 (defun org-normalize-color (value)
17484 "Return string to be used as color value for an RGB component."
17485 (format "%g" (/ value 65535.0)))
17487 ;; Image display
17490 (defvar org-inline-image-overlays nil)
17491 (make-variable-buffer-local 'org-inline-image-overlays)
17493 (defun org-toggle-inline-images (&optional include-linked)
17494 "Toggle the display of inline images.
17495 INCLUDE-LINKED is passed to `org-display-inline-images'."
17496 (interactive "P")
17497 (if org-inline-image-overlays
17498 (progn
17499 (org-remove-inline-images)
17500 (message "Inline image display turned off"))
17501 (org-display-inline-images include-linked)
17502 (if org-inline-image-overlays
17503 (message "%d images displayed inline"
17504 (length org-inline-image-overlays))
17505 (message "No images to display inline"))))
17507 (defun org-display-inline-images (&optional include-linked refresh beg end)
17508 "Display inline images.
17509 Normally only links without a description part are inlined, because this
17510 is how it will work for export. When INCLUDE-LINKED is set, also links
17511 with a description part will be inlined. This can be nice for a quick
17512 look at those images, but it does not reflect what exported files will look
17513 like.
17514 When REFRESH is set, refresh existing images between BEG and END.
17515 This will create new image displays only if necessary.
17516 BEG and END default to the buffer boundaries."
17517 (interactive "P")
17518 (unless refresh
17519 (org-remove-inline-images)
17520 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17521 (save-excursion
17522 (save-restriction
17523 (widen)
17524 (setq beg (or beg (point-min)) end (or end (point-max)))
17525 (goto-char beg)
17526 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17527 (substring (org-image-file-name-regexp) 0 -2)
17528 "\\)\\]" (if include-linked "" "\\]")))
17529 old file ov img)
17530 (while (re-search-forward re end t)
17531 (setq old (get-char-property-and-overlay (match-beginning 1)
17532 'org-image-overlay))
17533 (setq file (expand-file-name
17534 (concat (or (match-string 3) "") (match-string 4))))
17535 (when (file-exists-p file)
17536 (if (and (car-safe old) refresh)
17537 (image-refresh (overlay-get (cdr old) 'display))
17538 (setq img (save-match-data (create-image file)))
17539 (when img
17540 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17541 (overlay-put ov 'display img)
17542 (overlay-put ov 'face 'default)
17543 (overlay-put ov 'org-image-overlay t)
17544 (overlay-put ov 'modification-hooks
17545 (list 'org-display-inline-modification-hook))
17546 (push ov org-inline-image-overlays)))))))))
17548 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17549 "Remove inline-display overlay if a corresponding region is modified."
17550 (let ((inhibit-modification-hooks t))
17551 (when (and ov after)
17552 (delete ov org-inline-image-overlays)
17553 (delete-overlay ov))))
17555 (defun org-remove-inline-images ()
17556 "Remove inline display of images."
17557 (interactive)
17558 (mapc 'delete-overlay org-inline-image-overlays)
17559 (setq org-inline-image-overlays nil))
17561 ;;;; Key bindings
17563 ;; Outline functions from `outline-mode-prefix-map'
17564 ;; that can be remapped in Org:
17565 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17566 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17567 (define-key org-mode-map [remap outline-forward-same-level]
17568 'org-forward-same-level)
17569 (define-key org-mode-map [remap outline-backward-same-level]
17570 'org-backward-same-level)
17571 (define-key org-mode-map [remap show-branches]
17572 'org-kill-note-or-show-branches)
17573 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17574 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17575 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17577 ;; Outline functions from `outline-mode-prefix-map'
17578 ;; that can not be remapped in Org:
17579 ;; - the column "key binding" shows whether the Outline function is still
17580 ;; available in Org mode on the same key that it has been bound to in
17581 ;; Outline mode:
17582 ;; - "overridden": key used for a different functionality in Org mode
17583 ;; - else: key still bound to the same Outline function in Org mode
17584 ;; | Outline function | key binding | Org replacement |
17585 ;; |------------------------------------+-------------+-----------------------|
17586 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17587 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17588 ;; | `show-children' | `C-c C-i' | visibility cycling |
17589 ;; | `hide-subtree' | overridden | visibility cycling |
17590 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17591 ;; | `hide-body' | overridden | no replacement |
17592 ;; | `show-all' | overridden | no replacement |
17593 ;; | `hide-entry' | overridden | visibility cycling |
17594 ;; | `show-entry' | overridden | no replacement |
17595 ;; | `hide-leaves' | overridden | no replacement |
17596 ;; | `hide-sublevels' | overridden | no replacement |
17597 ;; | `hide-other' | overridden | no replacement |
17598 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17599 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17601 ;; Make `C-c C-x' a prefix key
17602 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17604 ;; TAB key with modifiers
17605 (org-defkey org-mode-map "\C-i" 'org-cycle)
17606 (org-defkey org-mode-map [(tab)] 'org-cycle)
17607 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17608 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17609 ;; The following line is necessary under Suse GNU/Linux
17610 (unless (featurep 'xemacs)
17611 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17612 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17613 (define-key org-mode-map [backtab] 'org-shifttab)
17615 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17616 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17617 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17619 ;; Cursor keys with modifiers
17620 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17621 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17622 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17623 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17625 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17626 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17627 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17628 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17630 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17631 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17632 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17633 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17635 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17636 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17637 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17638 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17640 ;; Babel keys
17641 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17642 (mapc (lambda (pair)
17643 (define-key org-babel-map (car pair) (cdr pair)))
17644 org-babel-key-bindings)
17646 ;;; Extra keys for tty access.
17647 ;; We only set them when really needed because otherwise the
17648 ;; menus don't show the simple keys
17650 (when (or org-use-extra-keys
17651 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17652 (not window-system))
17653 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17654 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17655 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17656 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17657 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17658 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17659 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17660 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17661 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17662 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17663 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17664 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17665 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17666 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17667 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17668 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17669 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17670 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17671 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17672 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17673 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17674 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17675 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17676 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17677 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17678 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17679 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17680 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17682 ;; All the other keys
17684 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17685 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17686 (if (boundp 'narrow-map)
17687 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17688 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17689 (if (boundp 'narrow-map)
17690 (org-defkey narrow-map "b" 'org-narrow-to-block)
17691 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17692 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17693 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17694 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17695 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17696 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17697 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17698 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17699 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17700 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17701 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17702 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17703 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17704 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17705 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17706 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17707 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17708 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17709 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17710 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17711 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17712 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17713 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17714 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17715 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17716 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17717 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17718 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17719 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17720 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17721 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17722 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17723 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17724 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17725 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17726 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17727 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17728 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17729 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17730 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17731 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17732 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17733 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17734 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17735 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17736 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17737 (org-defkey org-mode-map "\C-c^" 'org-sort)
17738 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17739 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17740 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17741 (org-defkey org-mode-map "\C-m" 'org-return)
17742 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17743 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17744 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17745 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17746 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17747 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17748 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17749 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17750 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17751 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17752 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17753 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17754 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17755 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17756 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17757 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17758 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17759 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17760 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17761 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17762 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17763 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17764 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17766 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17767 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17768 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17769 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17771 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17772 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17773 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17774 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17775 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17776 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17777 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17778 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17779 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17780 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17781 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17782 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17783 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17784 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17785 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17786 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17787 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17788 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17790 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17791 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17792 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17793 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17794 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17796 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17798 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17800 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17801 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17803 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17806 (when (featurep 'xemacs)
17807 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17810 (defconst org-speed-commands-default
17812 ("Outline Navigation")
17813 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17814 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17815 ("f" . (org-speed-move-safe 'org-forward-same-level))
17816 ("b" . (org-speed-move-safe 'org-backward-same-level))
17817 ("u" . (org-speed-move-safe 'outline-up-heading))
17818 ("j" . org-goto)
17819 ("g" . (org-refile t))
17820 ("Outline Visibility")
17821 ("c" . org-cycle)
17822 ("C" . org-shifttab)
17823 (" " . org-display-outline-path)
17824 ("Outline Structure Editing")
17825 ("U" . org-shiftmetaup)
17826 ("D" . org-shiftmetadown)
17827 ("r" . org-metaright)
17828 ("l" . org-metaleft)
17829 ("R" . org-shiftmetaright)
17830 ("L" . org-shiftmetaleft)
17831 ("i" . (progn (forward-char 1) (call-interactively
17832 'org-insert-heading-respect-content)))
17833 ("^" . org-sort)
17834 ("w" . org-refile)
17835 ("a" . org-archive-subtree-default-with-confirmation)
17836 ("." . org-mark-subtree)
17837 ("Clock Commands")
17838 ("I" . org-clock-in)
17839 ("O" . org-clock-out)
17840 ("Meta Data Editing")
17841 ("t" . org-todo)
17842 ("0" . (org-priority ?\ ))
17843 ("1" . (org-priority ?A))
17844 ("2" . (org-priority ?B))
17845 ("3" . (org-priority ?C))
17846 (";" . org-set-tags-command)
17847 ("e" . org-set-effort)
17848 ("Agenda Views etc")
17849 ("v" . org-agenda)
17850 ("/" . org-sparse-tree)
17851 ("Misc")
17852 ("o" . org-open-at-point)
17853 ("?" . org-speed-command-help)
17854 ("<" . (org-agenda-set-restriction-lock 'subtree))
17855 (">" . (org-agenda-remove-restriction-lock))
17857 "The default speed commands.")
17859 (defun org-print-speed-command (e)
17860 (if (> (length (car e)) 1)
17861 (progn
17862 (princ "\n")
17863 (princ (car e))
17864 (princ "\n")
17865 (princ (make-string (length (car e)) ?-))
17866 (princ "\n"))
17867 (princ (car e))
17868 (princ " ")
17869 (if (symbolp (cdr e))
17870 (princ (symbol-name (cdr e)))
17871 (prin1 (cdr e)))
17872 (princ "\n")))
17874 (defun org-speed-command-help ()
17875 "Show the available speed commands."
17876 (interactive)
17877 (if (not org-use-speed-commands)
17878 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17879 (with-output-to-temp-buffer "*Help*"
17880 (princ "User-defined Speed commands\n===========================\n")
17881 (mapc 'org-print-speed-command org-speed-commands-user)
17882 (princ "\n")
17883 (princ "Built-in Speed commands\n=======================\n")
17884 (mapc 'org-print-speed-command org-speed-commands-default))
17885 (with-current-buffer "*Help*"
17886 (setq truncate-lines t))))
17888 (defun org-speed-move-safe (cmd)
17889 "Execute CMD, but make sure that the cursor always ends up in a headline.
17890 If not, return to the original position and throw an error."
17891 (interactive)
17892 (let ((pos (point)))
17893 (call-interactively cmd)
17894 (unless (and (bolp) (org-at-heading-p))
17895 (goto-char pos)
17896 (error "Boundary reached while executing %s" cmd))))
17898 (defvar org-self-insert-command-undo-counter 0)
17900 (defvar org-table-auto-blank-field) ; defined in org-table.el
17901 (defvar org-speed-command nil)
17903 (defun org-speed-command-default-hook (keys)
17904 "Hook for activating single-letter speed commands.
17905 `org-speed-commands-default' specifies a minimal command set.
17906 Use `org-speed-commands-user' for further customization."
17907 (when (or (and (bolp) (looking-at org-outline-regexp))
17908 (and (functionp org-use-speed-commands)
17909 (funcall org-use-speed-commands)))
17910 (cdr (assoc keys (append org-speed-commands-user
17911 org-speed-commands-default)))))
17913 (defun org-babel-speed-command-hook (keys)
17914 "Hook for activating single-letter code block commands."
17915 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17916 (cdr (assoc keys org-babel-key-bindings))))
17918 (defcustom org-speed-command-hook
17919 '(org-speed-command-default-hook org-babel-speed-command-hook)
17920 "Hook for activating speed commands at strategic locations.
17921 Hook functions are called in sequence until a valid handler is
17922 found.
17924 Each hook takes a single argument, a user-pressed command key
17925 which is also a `self-insert-command' from the global map.
17927 Within the hook, examine the cursor position and the command key
17928 and return nil or a valid handler as appropriate. Handler could
17929 be one of an interactive command, a function, or a form.
17931 Set `org-use-speed-commands' to non-nil value to enable this
17932 hook. The default setting is `org-speed-command-default-hook'."
17933 :group 'org-structure
17934 :version "24.1"
17935 :type 'hook)
17937 (defun org-self-insert-command (N)
17938 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17939 If the cursor is in a table looking at whitespace, the whitespace is
17940 overwritten, and the table is not marked as requiring realignment."
17941 (interactive "p")
17942 (org-check-before-invisible-edit 'insert)
17943 (cond
17944 ((and org-use-speed-commands
17945 (setq org-speed-command
17946 (run-hook-with-args-until-success
17947 'org-speed-command-hook (this-command-keys))))
17948 (cond
17949 ((commandp org-speed-command)
17950 (setq this-command org-speed-command)
17951 (call-interactively org-speed-command))
17952 ((functionp org-speed-command)
17953 (funcall org-speed-command))
17954 ((and org-speed-command (listp org-speed-command))
17955 (eval org-speed-command))
17956 (t (let (org-use-speed-commands)
17957 (call-interactively 'org-self-insert-command)))))
17958 ((and
17959 (org-table-p)
17960 (progn
17961 ;; check if we blank the field, and if that triggers align
17962 (and (featurep 'org-table) org-table-auto-blank-field
17963 (member last-command
17964 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17965 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17966 ;; got extra space, this field does not determine column width
17967 (let (org-table-may-need-update) (org-table-blank-field))
17968 ;; no extra space, this field may determine column width
17969 (org-table-blank-field)))
17971 (eq N 1)
17972 (looking-at "[^|\n]* |"))
17973 (let (org-table-may-need-update)
17974 (goto-char (1- (match-end 0)))
17975 (backward-delete-char 1)
17976 (goto-char (match-beginning 0))
17977 (self-insert-command N)))
17979 (setq org-table-may-need-update t)
17980 (self-insert-command N)
17981 (org-fix-tags-on-the-fly)
17982 (if org-self-insert-cluster-for-undo
17983 (if (not (eq last-command 'org-self-insert-command))
17984 (setq org-self-insert-command-undo-counter 1)
17985 (if (>= org-self-insert-command-undo-counter 20)
17986 (setq org-self-insert-command-undo-counter 1)
17987 (and (> org-self-insert-command-undo-counter 0)
17988 buffer-undo-list (listp buffer-undo-list)
17989 (not (cadr buffer-undo-list)) ; remove nil entry
17990 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17991 (setq org-self-insert-command-undo-counter
17992 (1+ org-self-insert-command-undo-counter))))))))
17994 (defun org-check-before-invisible-edit (kind)
17995 "Check is editing if kind KIND would be dangerous with invisible text around.
17996 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17997 ;; First, try to get out of here as quickly as possible, to reduce overhead
17998 (if (and org-catch-invisible-edits
17999 (or (not (boundp 'visible-mode)) (not visible-mode))
18000 (or (get-char-property (point) 'invisible)
18001 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18002 ;; OK, we need to take a closer look
18003 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18004 (invisible-before-point (if (bobp) nil (get-char-property
18005 (1- (point)) 'invisible)))
18006 (border-and-ok-direction
18008 ;; Check if we are acting predictably before invisible text
18009 (and invisible-at-point (not invisible-before-point)
18010 (memq kind '(insert delete-backward)))
18011 ;; Check if we are acting predictably after invisible text
18012 ;; This works not well, and I have turned it off. It seems
18013 ;; better to always show and stop after invisible text.
18014 ;; (and (not invisible-at-point) invisible-before-point
18015 ;; (memq kind '(insert delete)))
18018 (when (or (memq invisible-at-point '(outline org-hide-block))
18019 (memq invisible-before-point '(outline org-hide-block)))
18020 (if (eq org-catch-invisible-edits 'error)
18021 (error "Editing in invisible areas is prohibited - make visible first"))
18022 ;; Make the area visible
18023 (save-excursion
18024 (if invisible-before-point
18025 (goto-char (previous-single-char-property-change
18026 (point) 'invisible)))
18027 (org-cycle))
18028 (cond
18029 ((eq org-catch-invisible-edits 'show)
18030 ;; That's it, we do the edit after showing
18031 (message
18032 "Unfolding invisible region around point before editing")
18033 (sit-for 1))
18034 ((and (eq org-catch-invisible-edits 'smart)
18035 border-and-ok-direction)
18036 (message "Unfolding invisible region around point before editing"))
18038 ;; Don't do the edit, make the user repeat it in full visibility
18039 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18041 (defun org-fix-tags-on-the-fly ()
18042 (when (and (equal (char-after (point-at-bol)) ?*)
18043 (org-at-heading-p))
18044 (org-align-tags-here org-tags-column)))
18046 (defun org-delete-backward-char (N)
18047 "Like `delete-backward-char', insert whitespace at field end in tables.
18048 When deleting backwards, in tables this function will insert whitespace in
18049 front of the next \"|\" separator, to keep the table aligned. The table will
18050 still be marked for re-alignment if the field did fill the entire column,
18051 because, in this case the deletion might narrow the column."
18052 (interactive "p")
18053 (org-check-before-invisible-edit 'delete-backward)
18054 (if (and (org-table-p)
18055 (eq N 1)
18056 (string-match "|" (buffer-substring (point-at-bol) (point)))
18057 (looking-at ".*?|"))
18058 (let ((pos (point))
18059 (noalign (looking-at "[^|\n\r]* |"))
18060 (c org-table-may-need-update))
18061 (backward-delete-char N)
18062 (if (not overwrite-mode)
18063 (progn
18064 (skip-chars-forward "^|")
18065 (insert " ")
18066 (goto-char (1- pos))))
18067 ;; noalign: if there were two spaces at the end, this field
18068 ;; does not determine the width of the column.
18069 (if noalign (setq org-table-may-need-update c)))
18070 (backward-delete-char N)
18071 (org-fix-tags-on-the-fly)))
18073 (defun org-delete-char (N)
18074 "Like `delete-char', but insert whitespace at field end in tables.
18075 When deleting characters, in tables this function will insert whitespace in
18076 front of the next \"|\" separator, to keep the table aligned. The table will
18077 still be marked for re-alignment if the field did fill the entire column,
18078 because, in this case the deletion might narrow the column."
18079 (interactive "p")
18080 (org-check-before-invisible-edit 'delete)
18081 (if (and (org-table-p)
18082 (not (bolp))
18083 (not (= (char-after) ?|))
18084 (eq N 1))
18085 (if (looking-at ".*?|")
18086 (let ((pos (point))
18087 (noalign (looking-at "[^|\n\r]* |"))
18088 (c org-table-may-need-update))
18089 (replace-match (concat
18090 (substring (match-string 0) 1 -1)
18091 " |"))
18092 (goto-char pos)
18093 ;; noalign: if there were two spaces at the end, this field
18094 ;; does not determine the width of the column.
18095 (if noalign (setq org-table-may-need-update c)))
18096 (delete-char N))
18097 (delete-char N)
18098 (org-fix-tags-on-the-fly)))
18100 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18101 (put 'org-self-insert-command 'delete-selection t)
18102 (put 'orgtbl-self-insert-command 'delete-selection t)
18103 (put 'org-delete-char 'delete-selection 'supersede)
18104 (put 'org-delete-backward-char 'delete-selection 'supersede)
18105 (put 'org-yank 'delete-selection 'yank)
18107 ;; Make `flyspell-mode' delay after some commands
18108 (put 'org-self-insert-command 'flyspell-delayed t)
18109 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18110 (put 'org-delete-char 'flyspell-delayed t)
18111 (put 'org-delete-backward-char 'flyspell-delayed t)
18113 ;; Make pabbrev-mode expand after org-mode commands
18114 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18115 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18117 ;; How to do this: Measure non-white length of current string
18118 ;; If equal to column width, we should realign.
18120 (defun org-remap (map &rest commands)
18121 "In MAP, remap the functions given in COMMANDS.
18122 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18123 (let (new old)
18124 (while commands
18125 (setq old (pop commands) new (pop commands))
18126 (if (fboundp 'command-remapping)
18127 (org-defkey map (vector 'remap old) new)
18128 (substitute-key-definition old new map global-map)))))
18130 (when (eq org-enable-table-editor 'optimized)
18131 ;; If the user wants maximum table support, we need to hijack
18132 ;; some standard editing functions
18133 (org-remap org-mode-map
18134 'self-insert-command 'org-self-insert-command
18135 'delete-char 'org-delete-char
18136 'delete-backward-char 'org-delete-backward-char)
18137 (org-defkey org-mode-map "|" 'org-force-self-insert))
18139 (defvar org-ctrl-c-ctrl-c-hook nil
18140 "Hook for functions attaching themselves to `C-c C-c'.
18142 This can be used to add additional functionality to the C-c C-c
18143 key which executes context-dependent commands. This hook is run
18144 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18145 run after the last test.
18147 Each function will be called with no arguments. The function
18148 must check if the context is appropriate for it to act. If yes,
18149 it should do its thing and then return a non-nil value. If the
18150 context is wrong, just do nothing and return nil.")
18152 (defvar org-ctrl-c-ctrl-c-final-hook nil
18153 "Hook for functions attaching themselves to `C-c C-c'.
18155 This can be used to add additional functionality to the C-c C-c
18156 key which executes context-dependent commands. This hook is run
18157 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18158 before the first test.
18160 Each function will be called with no arguments. The function
18161 must check if the context is appropriate for it to act. If yes,
18162 it should do its thing and then return a non-nil value. If the
18163 context is wrong, just do nothing and return nil.")
18165 (defvar org-tab-first-hook nil
18166 "Hook for functions to attach themselves to TAB.
18167 See `org-ctrl-c-ctrl-c-hook' for more information.
18168 This hook runs as the first action when TAB is pressed, even before
18169 `org-cycle' messes around with the `outline-regexp' to cater for
18170 inline tasks and plain list item folding.
18171 If any function in this hook returns t, any other actions that
18172 would have been caused by TAB (such as table field motion or visibility
18173 cycling) will not occur.")
18175 (defvar org-tab-after-check-for-table-hook nil
18176 "Hook for functions to attach themselves to TAB.
18177 See `org-ctrl-c-ctrl-c-hook' for more information.
18178 This hook runs after it has been established that the cursor is not in a
18179 table, but before checking if the cursor is in a headline or if global cycling
18180 should be done.
18181 If any function in this hook returns t, not other actions like visibility
18182 cycling will be done.")
18184 (defvar org-tab-after-check-for-cycling-hook nil
18185 "Hook for functions to attach themselves to TAB.
18186 See `org-ctrl-c-ctrl-c-hook' for more information.
18187 This hook runs after it has been established that not table field motion and
18188 not visibility should be done because of current context. This is probably
18189 the place where a package like yasnippets can hook in.")
18191 (defvar org-tab-before-tab-emulation-hook nil
18192 "Hook for functions to attach themselves to TAB.
18193 See `org-ctrl-c-ctrl-c-hook' for more information.
18194 This hook runs after every other options for TAB have been exhausted, but
18195 before indentation and \t insertion takes place.")
18197 (defvar org-metaleft-hook nil
18198 "Hook for functions attaching themselves to `M-left'.
18199 See `org-ctrl-c-ctrl-c-hook' for more information.")
18200 (defvar org-metaright-hook nil
18201 "Hook for functions attaching themselves to `M-right'.
18202 See `org-ctrl-c-ctrl-c-hook' for more information.")
18203 (defvar org-metaup-hook nil
18204 "Hook for functions attaching themselves to `M-up'.
18205 See `org-ctrl-c-ctrl-c-hook' for more information.")
18206 (defvar org-metadown-hook nil
18207 "Hook for functions attaching themselves to `M-down'.
18208 See `org-ctrl-c-ctrl-c-hook' for more information.")
18209 (defvar org-shiftmetaleft-hook nil
18210 "Hook for functions attaching themselves to `M-S-left'.
18211 See `org-ctrl-c-ctrl-c-hook' for more information.")
18212 (defvar org-shiftmetaright-hook nil
18213 "Hook for functions attaching themselves to `M-S-right'.
18214 See `org-ctrl-c-ctrl-c-hook' for more information.")
18215 (defvar org-shiftmetaup-hook nil
18216 "Hook for functions attaching themselves to `M-S-up'.
18217 See `org-ctrl-c-ctrl-c-hook' for more information.")
18218 (defvar org-shiftmetadown-hook nil
18219 "Hook for functions attaching themselves to `M-S-down'.
18220 See `org-ctrl-c-ctrl-c-hook' for more information.")
18221 (defvar org-metareturn-hook nil
18222 "Hook for functions attaching themselves to `M-RET'.
18223 See `org-ctrl-c-ctrl-c-hook' for more information.")
18224 (defvar org-shiftup-hook nil
18225 "Hook for functions attaching themselves to `S-up'.
18226 See `org-ctrl-c-ctrl-c-hook' for more information.")
18227 (defvar org-shiftup-final-hook nil
18228 "Hook for functions attaching themselves to `S-up'.
18229 This one runs after all other options except shift-select have been excluded.
18230 See `org-ctrl-c-ctrl-c-hook' for more information.")
18231 (defvar org-shiftdown-hook nil
18232 "Hook for functions attaching themselves to `S-down'.
18233 See `org-ctrl-c-ctrl-c-hook' for more information.")
18234 (defvar org-shiftdown-final-hook nil
18235 "Hook for functions attaching themselves to `S-down'.
18236 This one runs after all other options except shift-select have been excluded.
18237 See `org-ctrl-c-ctrl-c-hook' for more information.")
18238 (defvar org-shiftleft-hook nil
18239 "Hook for functions attaching themselves to `S-left'.
18240 See `org-ctrl-c-ctrl-c-hook' for more information.")
18241 (defvar org-shiftleft-final-hook nil
18242 "Hook for functions attaching themselves to `S-left'.
18243 This one runs after all other options except shift-select have been excluded.
18244 See `org-ctrl-c-ctrl-c-hook' for more information.")
18245 (defvar org-shiftright-hook nil
18246 "Hook for functions attaching themselves to `S-right'.
18247 See `org-ctrl-c-ctrl-c-hook' for more information.")
18248 (defvar org-shiftright-final-hook nil
18249 "Hook for functions attaching themselves to `S-right'.
18250 This one runs after all other options except shift-select have been excluded.
18251 See `org-ctrl-c-ctrl-c-hook' for more information.")
18253 (defun org-modifier-cursor-error ()
18254 "Throw an error, a modified cursor command was applied in wrong context."
18255 (error "This command is active in special context like tables, headlines or items"))
18257 (defun org-shiftselect-error ()
18258 "Throw an error because Shift-Cursor command was applied in wrong context."
18259 (if (and (boundp 'shift-select-mode) shift-select-mode)
18260 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18261 (error "This command works only in special context like headlines or timestamps")))
18263 (defun org-call-for-shift-select (cmd)
18264 (let ((this-command-keys-shift-translated t))
18265 (call-interactively cmd)))
18267 (defun org-shifttab (&optional arg)
18268 "Global visibility cycling or move to previous table field.
18269 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18270 on context.
18271 See the individual commands for more information."
18272 (interactive "P")
18273 (cond
18274 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18275 ((integerp arg)
18276 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18277 (message "Content view to level: %d" arg)
18278 (org-content (prefix-numeric-value arg2))
18279 (setq org-cycle-global-status 'overview)))
18280 (t (call-interactively 'org-global-cycle))))
18282 (defun org-shiftmetaleft ()
18283 "Promote subtree or delete table column.
18284 Calls `org-promote-subtree', `org-outdent-item-tree', or
18285 `org-table-delete-column', depending on context. See the
18286 individual commands for more information."
18287 (interactive)
18288 (cond
18289 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18290 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18291 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18292 ((if (not (org-region-active-p)) (org-at-item-p)
18293 (save-excursion (goto-char (region-beginning))
18294 (org-at-item-p)))
18295 (call-interactively 'org-outdent-item-tree))
18296 (t (org-modifier-cursor-error))))
18298 (defun org-shiftmetaright ()
18299 "Demote subtree or insert table column.
18300 Calls `org-demote-subtree', `org-indent-item-tree', or
18301 `org-table-insert-column', depending on context. See the
18302 individual commands for more information."
18303 (interactive)
18304 (cond
18305 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18306 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18307 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18308 ((if (not (org-region-active-p)) (org-at-item-p)
18309 (save-excursion (goto-char (region-beginning))
18310 (org-at-item-p)))
18311 (call-interactively 'org-indent-item-tree))
18312 (t (org-modifier-cursor-error))))
18314 (defun org-shiftmetaup (&optional arg)
18315 "Move subtree up or kill table row.
18316 Calls `org-move-subtree-up' or `org-table-kill-row' or
18317 `org-move-item-up' depending on context. See the individual commands
18318 for more information."
18319 (interactive "P")
18320 (cond
18321 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18322 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18323 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18324 ((org-at-item-p) (call-interactively 'org-move-item-up))
18325 (t (org-modifier-cursor-error))))
18327 (defun org-shiftmetadown (&optional arg)
18328 "Move subtree down or insert table row.
18329 Calls `org-move-subtree-down' or `org-table-insert-row' or
18330 `org-move-item-down', depending on context. See the individual
18331 commands for more information."
18332 (interactive "P")
18333 (cond
18334 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18335 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18336 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18337 ((org-at-item-p) (call-interactively 'org-move-item-down))
18338 (t (org-modifier-cursor-error))))
18340 (defsubst org-hidden-tree-error ()
18341 (error
18342 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18344 (defun org-metaleft (&optional arg)
18345 "Promote heading or move table column to left.
18346 Calls `org-do-promote' or `org-table-move-column', depending on context.
18347 With no specific context, calls the Emacs default `backward-word'.
18348 See the individual commands for more information."
18349 (interactive "P")
18350 (cond
18351 ((run-hook-with-args-until-success 'org-metaleft-hook))
18352 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18353 ((org-with-limited-levels
18354 (or (org-at-heading-p)
18355 (and (org-region-active-p)
18356 (save-excursion
18357 (goto-char (region-beginning))
18358 (org-at-heading-p)))))
18359 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18360 (call-interactively 'org-do-promote))
18361 ;; At an inline task.
18362 ((org-at-heading-p)
18363 (call-interactively 'org-inlinetask-promote))
18364 ((or (org-at-item-p)
18365 (and (org-region-active-p)
18366 (save-excursion
18367 (goto-char (region-beginning))
18368 (org-at-item-p))))
18369 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18370 (call-interactively 'org-outdent-item))
18371 (t (call-interactively 'backward-word))))
18373 (defun org-metaright (&optional arg)
18374 "Demote a subtree, a list item or move table column to right.
18375 In front of a drawer or a block keyword, indent it correctly.
18376 With no specific context, calls the Emacs default `forward-word'.
18377 See the individual commands for more information."
18378 (interactive "P")
18379 (cond
18380 ((run-hook-with-args-until-success 'org-metaright-hook))
18381 ((org-at-table-p) (call-interactively 'org-table-move-column))
18382 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18383 ((org-at-block-p) (call-interactively 'org-indent-block))
18384 ((org-with-limited-levels
18385 (or (org-at-heading-p)
18386 (and (org-region-active-p)
18387 (save-excursion
18388 (goto-char (region-beginning))
18389 (org-at-heading-p)))))
18390 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18391 (call-interactively 'org-do-demote))
18392 ;; At an inline task.
18393 ((org-at-heading-p)
18394 (call-interactively 'org-inlinetask-demote))
18395 ((or (org-at-item-p)
18396 (and (org-region-active-p)
18397 (save-excursion
18398 (goto-char (region-beginning))
18399 (org-at-item-p))))
18400 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18401 (call-interactively 'org-indent-item))
18402 (t (call-interactively 'forward-word))))
18404 (defun org-check-for-hidden (what)
18405 "Check if there are hidden headlines/items in the current visual line.
18406 WHAT can be either `headlines' or `items'. If the current line is
18407 an outline or item heading and it has a folded subtree below it,
18408 this function returns t, nil otherwise."
18409 (let ((re (cond
18410 ((eq what 'headlines) org-outline-regexp-bol)
18411 ((eq what 'items) (org-item-beginning-re))
18412 (t (error "This should not happen"))))
18413 beg end)
18414 (save-excursion
18415 (catch 'exit
18416 (unless (org-region-active-p)
18417 (setq beg (point-at-bol))
18418 (beginning-of-line 2)
18419 (while (and (not (eobp)) ;; this is like `next-line'
18420 (get-char-property (1- (point)) 'invisible))
18421 (beginning-of-line 2))
18422 (setq end (point))
18423 (goto-char beg)
18424 (goto-char (point-at-eol))
18425 (setq end (max end (point)))
18426 (while (re-search-forward re end t)
18427 (if (get-char-property (match-beginning 0) 'invisible)
18428 (throw 'exit t))))
18429 nil))))
18431 (defun org-metaup (&optional arg)
18432 "Move subtree up or move table row up.
18433 Calls `org-move-subtree-up' or `org-table-move-row' or
18434 `org-move-item-up', depending on context. See the individual commands
18435 for more information."
18436 (interactive "P")
18437 (cond
18438 ((run-hook-with-args-until-success 'org-metaup-hook))
18439 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18440 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18441 ((org-at-item-p) (call-interactively 'org-move-item-up))
18442 (t (transpose-lines 1) (beginning-of-line -1))))
18444 (defun org-metadown (&optional arg)
18445 "Move subtree down or move table row down.
18446 Calls `org-move-subtree-down' or `org-table-move-row' or
18447 `org-move-item-down', depending on context. See the individual
18448 commands for more information."
18449 (interactive "P")
18450 (cond
18451 ((run-hook-with-args-until-success 'org-metadown-hook))
18452 ((org-at-table-p) (call-interactively 'org-table-move-row))
18453 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18454 ((org-at-item-p) (call-interactively 'org-move-item-down))
18455 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18457 (defun org-shiftup (&optional arg)
18458 "Increase item in timestamp or increase priority of current headline.
18459 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18460 depending on context. See the individual commands for more information."
18461 (interactive "P")
18462 (cond
18463 ((run-hook-with-args-until-success 'org-shiftup-hook))
18464 ((and org-support-shift-select (org-region-active-p))
18465 (org-call-for-shift-select 'previous-line))
18466 ((org-at-timestamp-p t)
18467 (call-interactively (if org-edit-timestamp-down-means-later
18468 'org-timestamp-down 'org-timestamp-up)))
18469 ((and (not (eq org-support-shift-select 'always))
18470 org-enable-priority-commands
18471 (org-at-heading-p))
18472 (call-interactively 'org-priority-up))
18473 ((and (not org-support-shift-select) (org-at-item-p))
18474 (call-interactively 'org-previous-item))
18475 ((org-clocktable-try-shift 'up arg))
18476 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18477 (org-support-shift-select
18478 (org-call-for-shift-select 'previous-line))
18479 (t (org-shiftselect-error))))
18481 (defun org-shiftdown (&optional arg)
18482 "Decrease item in timestamp or decrease priority of current headline.
18483 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18484 depending on context. See the individual commands for more information."
18485 (interactive "P")
18486 (cond
18487 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18488 ((and org-support-shift-select (org-region-active-p))
18489 (org-call-for-shift-select 'next-line))
18490 ((org-at-timestamp-p t)
18491 (call-interactively (if org-edit-timestamp-down-means-later
18492 'org-timestamp-up 'org-timestamp-down)))
18493 ((and (not (eq org-support-shift-select 'always))
18494 org-enable-priority-commands
18495 (org-at-heading-p))
18496 (call-interactively 'org-priority-down))
18497 ((and (not org-support-shift-select) (org-at-item-p))
18498 (call-interactively 'org-next-item))
18499 ((org-clocktable-try-shift 'down arg))
18500 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18501 (org-support-shift-select
18502 (org-call-for-shift-select 'next-line))
18503 (t (org-shiftselect-error))))
18505 (defun org-shiftright (&optional arg)
18506 "Cycle the thing at point or in the current line, depending on context.
18507 Depending on context, this does one of the following:
18509 - switch a timestamp at point one day into the future
18510 - on a headline, switch to the next TODO keyword.
18511 - on an item, switch entire list to the next bullet type
18512 - on a property line, switch to the next allowed value
18513 - on a clocktable definition line, move time block into the future"
18514 (interactive "P")
18515 (cond
18516 ((run-hook-with-args-until-success 'org-shiftright-hook))
18517 ((and org-support-shift-select (org-region-active-p))
18518 (org-call-for-shift-select 'forward-char))
18519 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18520 ((and (not (eq org-support-shift-select 'always))
18521 (org-at-heading-p))
18522 (let ((org-inhibit-logging
18523 (not org-treat-S-cursor-todo-selection-as-state-change))
18524 (org-inhibit-blocking
18525 (not org-treat-S-cursor-todo-selection-as-state-change)))
18526 (org-call-with-arg 'org-todo 'right)))
18527 ((or (and org-support-shift-select
18528 (not (eq org-support-shift-select 'always))
18529 (org-at-item-bullet-p))
18530 (and (not org-support-shift-select) (org-at-item-p)))
18531 (org-call-with-arg 'org-cycle-list-bullet nil))
18532 ((and (not (eq org-support-shift-select 'always))
18533 (org-at-property-p))
18534 (call-interactively 'org-property-next-allowed-value))
18535 ((org-clocktable-try-shift 'right arg))
18536 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18537 (org-support-shift-select
18538 (org-call-for-shift-select 'forward-char))
18539 (t (org-shiftselect-error))))
18541 (defun org-shiftleft (&optional arg)
18542 "Cycle the thing at point or in the current line, depending on context.
18543 Depending on context, this does one of the following:
18545 - switch a timestamp at point one day into the past
18546 - on a headline, switch to the previous TODO keyword.
18547 - on an item, switch entire list to the previous bullet type
18548 - on a property line, switch to the previous allowed value
18549 - on a clocktable definition line, move time block into the past"
18550 (interactive "P")
18551 (cond
18552 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18553 ((and org-support-shift-select (org-region-active-p))
18554 (org-call-for-shift-select 'backward-char))
18555 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18556 ((and (not (eq org-support-shift-select 'always))
18557 (org-at-heading-p))
18558 (let ((org-inhibit-logging
18559 (not org-treat-S-cursor-todo-selection-as-state-change))
18560 (org-inhibit-blocking
18561 (not org-treat-S-cursor-todo-selection-as-state-change)))
18562 (org-call-with-arg 'org-todo 'left)))
18563 ((or (and org-support-shift-select
18564 (not (eq org-support-shift-select 'always))
18565 (org-at-item-bullet-p))
18566 (and (not org-support-shift-select) (org-at-item-p)))
18567 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18568 ((and (not (eq org-support-shift-select 'always))
18569 (org-at-property-p))
18570 (call-interactively 'org-property-previous-allowed-value))
18571 ((org-clocktable-try-shift 'left arg))
18572 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18573 (org-support-shift-select
18574 (org-call-for-shift-select 'backward-char))
18575 (t (org-shiftselect-error))))
18577 (defun org-shiftcontrolright ()
18578 "Switch to next TODO set."
18579 (interactive)
18580 (cond
18581 ((and org-support-shift-select (org-region-active-p))
18582 (org-call-for-shift-select 'forward-word))
18583 ((and (not (eq org-support-shift-select 'always))
18584 (org-at-heading-p))
18585 (org-call-with-arg 'org-todo 'nextset))
18586 (org-support-shift-select
18587 (org-call-for-shift-select 'forward-word))
18588 (t (org-shiftselect-error))))
18590 (defun org-shiftcontrolleft ()
18591 "Switch to previous TODO set."
18592 (interactive)
18593 (cond
18594 ((and org-support-shift-select (org-region-active-p))
18595 (org-call-for-shift-select 'backward-word))
18596 ((and (not (eq org-support-shift-select 'always))
18597 (org-at-heading-p))
18598 (org-call-with-arg 'org-todo 'previousset))
18599 (org-support-shift-select
18600 (org-call-for-shift-select 'backward-word))
18601 (t (org-shiftselect-error))))
18603 (defun org-shiftcontrolup ()
18604 "Change timestamps synchronously up in CLOCK log lines."
18605 (interactive)
18606 (cond ((and (not org-support-shift-select)
18607 (org-at-clock-log-p)
18608 (org-at-timestamp-p t))
18609 (org-clock-timestamps-up))
18610 (t (org-shiftselect-error))))
18612 (defun org-shiftcontroldown ()
18613 "Change timestamps synchronously down in CLOCK log lines."
18614 (interactive)
18615 (cond ((and (not org-support-shift-select)
18616 (org-at-clock-log-p)
18617 (org-at-timestamp-p t))
18618 (org-clock-timestamps-down))
18619 (t (org-shiftselect-error))))
18621 (defun org-ctrl-c-ret ()
18622 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18623 (interactive)
18624 (cond
18625 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18626 (t (call-interactively 'org-insert-heading))))
18628 (defun org-find-visible ()
18629 (let ((s (point)))
18630 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18631 (get-char-property s 'invisible)))
18633 (defun org-find-invisible ()
18634 (let ((s (point)))
18635 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18636 (not (get-char-property s 'invisible))))
18639 (defun org-copy-visible (beg end)
18640 "Copy the visible parts of the region."
18641 (interactive "r")
18642 (let (snippets s)
18643 (save-excursion
18644 (save-restriction
18645 (narrow-to-region beg end)
18646 (setq s (goto-char (point-min)))
18647 (while (not (= (point) (point-max)))
18648 (goto-char (org-find-invisible))
18649 (push (buffer-substring s (point)) snippets)
18650 (setq s (goto-char (org-find-visible))))))
18651 (kill-new (apply 'concat (nreverse snippets)))))
18653 (defun org-copy-special ()
18654 "Copy region in table or copy current subtree.
18655 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18656 See the individual commands for more information."
18657 (interactive)
18658 (call-interactively
18659 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18661 (defun org-cut-special ()
18662 "Cut region in table or cut current subtree.
18663 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18664 See the individual commands for more information."
18665 (interactive)
18666 (call-interactively
18667 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18669 (defun org-paste-special (arg)
18670 "Paste rectangular region into table, or past subtree relative to level.
18671 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (if (org-at-table-p)
18675 (org-table-paste-rectangle)
18676 (org-paste-subtree arg)))
18678 (defun org-edit-special (&optional arg)
18679 "Call a special editor for the stuff at point.
18680 When at a table, call the formula editor with `org-table-edit-formulas'.
18681 When at the first line of an src example, call `org-edit-src-code'.
18682 When in an #+include line, visit the include file. Otherwise call
18683 `ffap' to visit the file at point."
18684 (interactive)
18685 ;; possibly prep session before editing source
18686 (when arg
18687 (let* ((info (org-babel-get-src-block-info))
18688 (lang (nth 0 info))
18689 (params (nth 2 info))
18690 (session (cdr (assoc :session params))))
18691 (when (and info session) ;; we are in a source-code block with a session
18692 (funcall
18693 (intern (concat "org-babel-prep-session:" lang)) session params))))
18694 (cond ;; proceed with `org-edit-special'
18695 ((save-excursion
18696 (beginning-of-line 1)
18697 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18698 (find-file (org-trim (match-string 1))))
18699 ((org-edit-src-code))
18700 ((org-edit-fixed-width-region))
18701 ((org-at-table.el-p)
18702 (org-edit-src-code))
18703 ((or (org-at-table-p)
18704 (save-excursion
18705 (beginning-of-line 1)
18706 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18707 (call-interactively 'org-table-edit-formulas))
18708 (t (call-interactively 'ffap))))
18710 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18711 (defun org-ctrl-c-ctrl-c (&optional arg)
18712 "Set tags in headline, or update according to changed information at point.
18714 This command does many different things, depending on context:
18716 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18717 this is what we do.
18719 - If the cursor is on a statistics cookie, update it.
18721 - If the cursor is in a headline, prompt for tags and insert them
18722 into the current line, aligned to `org-tags-column'. When called
18723 with prefix arg, realign all tags in the current buffer.
18725 - If the cursor is in one of the special #+KEYWORD lines, this
18726 triggers scanning the buffer for these lines and updating the
18727 information.
18729 - If the cursor is inside a table, realign the table. This command
18730 works even if the automatic table editor has been turned off.
18732 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18733 the entire table.
18735 - If the cursor is at a footnote reference or definition, jump to
18736 the corresponding definition or references, respectively.
18738 - If the cursor is a the beginning of a dynamic block, update it.
18740 - If the current buffer is a capture buffer, close note and file it.
18742 - If the cursor is on a <<<target>>>, update radio targets and
18743 corresponding links in this buffer.
18745 - If the cursor is on a numbered item in a plain list, renumber the
18746 ordered list.
18748 - If the cursor is on a checkbox, toggle it.
18750 - If the cursor is on a code block, evaluate it. The variable
18751 `org-confirm-babel-evaluate' can be used to control prompting
18752 before code block evaluation, by default every code block
18753 evaluation requires confirmation. Code block evaluation can be
18754 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18755 (interactive "P")
18756 (let ((org-enable-table-editor t))
18757 (cond
18758 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18759 org-occur-highlights
18760 org-latex-fragment-image-overlays)
18761 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18762 (org-remove-occur-highlights)
18763 (org-remove-latex-fragment-image-overlays)
18764 (message "Temporary highlights/overlays removed from current buffer"))
18765 ((and (local-variable-p 'org-finish-function (current-buffer))
18766 (fboundp org-finish-function))
18767 (funcall org-finish-function))
18768 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18769 ((org-in-regexp org-ts-regexp-both)
18770 (org-timestamp-change 0 'day))
18771 ((or (looking-at org-property-start-re)
18772 (org-at-property-p))
18773 (call-interactively 'org-property-action))
18774 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18775 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18776 (or (org-at-heading-p) (org-at-item-p)))
18777 (call-interactively 'org-update-statistics-cookies))
18778 ((org-at-heading-p) (call-interactively 'org-set-tags))
18779 ((org-at-table.el-p)
18780 (message "Use C-c ' to edit table.el tables"))
18781 ((org-at-table-p)
18782 (org-table-maybe-eval-formula)
18783 (if arg
18784 (call-interactively 'org-table-recalculate)
18785 (org-table-maybe-recalculate-line))
18786 (call-interactively 'org-table-align)
18787 (orgtbl-send-table 'maybe))
18788 ((or (org-footnote-at-reference-p)
18789 (org-footnote-at-definition-p))
18790 (call-interactively 'org-footnote-action))
18791 ((org-at-item-checkbox-p)
18792 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18793 ;; list only if at top item.
18794 (let* ((cbox (match-string 1))
18795 (struct (org-list-struct))
18796 (old-struct (copy-tree struct))
18797 (parents (org-list-parents-alist struct))
18798 (orderedp (org-entry-get nil "ORDERED"))
18799 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18800 block-item)
18801 ;; Use a light version of `org-toggle-checkbox' to avoid
18802 ;; computing list structure twice.
18803 (let ((new-box (cond
18804 ((equal arg '(16)) "[-]")
18805 ((equal arg '(4)) nil)
18806 ((equal "[X]" cbox) "[ ]")
18807 (t "[X]"))))
18808 (if (and firstp arg)
18809 ;; If at first item of sub-list, remove check-box from
18810 ;; every item at the same level.
18811 (mapc
18812 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18813 (org-list-get-all-items
18814 (point-at-bol) struct (org-list-prevs-alist struct)))
18815 (org-list-set-checkbox (point-at-bol) struct new-box)))
18816 ;; Replicate `org-list-write-struct', while grabbing a return
18817 ;; value from `org-list-struct-fix-box'.
18818 (org-list-struct-fix-ind struct parents 2)
18819 (org-list-struct-fix-item-end struct)
18820 (let ((prevs (org-list-prevs-alist struct)))
18821 (org-list-struct-fix-bul struct prevs)
18822 (org-list-struct-fix-ind struct parents)
18823 (setq block-item
18824 (org-list-struct-fix-box struct parents prevs orderedp)))
18825 (org-list-struct-apply-struct struct old-struct)
18826 (org-update-checkbox-count-maybe)
18827 (when block-item
18828 (message
18829 "Checkboxes were removed due to unchecked box at line %d"
18830 (org-current-line block-item)))
18831 (when firstp (org-list-send-list 'maybe))))
18832 ((org-at-item-p)
18833 ;; Cursor at an item: repair list. Do checkbox related actions
18834 ;; only if function was called with an argument. Send list only
18835 ;; if at top item.
18836 (let* ((struct (org-list-struct))
18837 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18838 old-struct)
18839 (when arg
18840 (setq old-struct (copy-tree struct))
18841 (if firstp
18842 ;; If at first item of sub-list, add check-box to every
18843 ;; item at the same level.
18844 (mapc
18845 (lambda (pos)
18846 (unless (org-list-get-checkbox pos struct)
18847 (org-list-set-checkbox pos struct "[ ]")))
18848 (org-list-get-all-items
18849 (point-at-bol) struct (org-list-prevs-alist struct)))
18850 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18851 (org-list-write-struct
18852 struct (org-list-parents-alist struct) old-struct)
18853 (when arg (org-update-checkbox-count-maybe))
18854 (when firstp (org-list-send-list 'maybe))))
18855 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18856 ;; Dynamic block
18857 (beginning-of-line 1)
18858 (save-excursion (org-update-dblock)))
18859 ((save-excursion
18860 (let ((case-fold-search t))
18861 (beginning-of-line 1)
18862 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18863 (cond
18864 ((or (equal (match-string 1) "TBLFM")
18865 (equal (match-string 1) "tblfm"))
18866 ;; Recalculate the table before this line
18867 (save-excursion
18868 (beginning-of-line 1)
18869 (skip-chars-backward " \r\n\t")
18870 (if (org-at-table-p)
18871 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18873 (let ((org-inhibit-startup-visibility-stuff t)
18874 (org-startup-align-all-tables nil))
18875 (when (boundp 'org-table-coordinate-overlays)
18876 (mapc 'delete-overlay org-table-coordinate-overlays)
18877 (setq org-table-coordinate-overlays nil))
18878 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18879 (message "Local setup has been refreshed"))))
18880 ((org-clock-update-time-maybe))
18882 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18883 (error "C-c C-c can do nothing useful at this location"))))))
18885 (defun org-mode-restart ()
18886 "Restart Org-mode, to scan again for special lines.
18887 Also updates the keyword regular expressions."
18888 (interactive)
18889 (org-mode)
18890 (message "Org-mode restarted"))
18892 (defun org-kill-note-or-show-branches ()
18893 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18894 (interactive)
18895 (if (not org-finish-function)
18896 (progn
18897 (hide-subtree)
18898 (call-interactively 'show-branches))
18899 (let ((org-note-abort t))
18900 (funcall org-finish-function))))
18902 (defun org-return (&optional indent)
18903 "Goto next table row or insert a newline.
18904 Calls `org-table-next-row' or `newline', depending on context.
18905 See the individual commands for more information."
18906 (interactive)
18907 (cond
18908 ((or (bobp) (org-in-src-block-p))
18909 (if indent (newline-and-indent) (newline)))
18910 ((org-at-table-p)
18911 (org-table-justify-field-maybe)
18912 (call-interactively 'org-table-next-row))
18913 ;; when `newline-and-indent' is called within a list, make sure
18914 ;; text moved stays inside the item.
18915 ((and (org-in-item-p) indent)
18916 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18917 (progn
18918 (save-match-data (newline))
18919 (org-indent-line-to (length (match-string 0))))
18920 (let ((ind (org-get-indentation)))
18921 (newline)
18922 (if (org-looking-back org-list-end-re)
18923 (org-indent-line-function)
18924 (org-indent-line-to ind)))))
18925 ((and org-return-follows-link
18926 (let ((tprop (get-text-property (point) 'face)))
18927 (or (eq tprop 'org-link)
18928 (and (listp tprop) (memq 'org-link tprop)))))
18929 (call-interactively 'org-open-at-point))
18930 ((and (org-at-heading-p)
18931 (looking-at
18932 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18933 (org-show-entry)
18934 (end-of-line 1)
18935 (newline))
18936 (t (if indent (newline-and-indent) (newline)))))
18938 (defun org-return-indent ()
18939 "Goto next table row or insert a newline and indent.
18940 Calls `org-table-next-row' or `newline-and-indent', depending on
18941 context. See the individual commands for more information."
18942 (interactive)
18943 (org-return t))
18945 (defun org-ctrl-c-star ()
18946 "Compute table, or change heading status of lines.
18947 Calls `org-table-recalculate' or `org-toggle-heading',
18948 depending on context."
18949 (interactive)
18950 (cond
18951 ((org-at-table-p)
18952 (call-interactively 'org-table-recalculate))
18954 ;; Convert all lines in region to list items
18955 (call-interactively 'org-toggle-heading))))
18957 (defun org-ctrl-c-minus ()
18958 "Insert separator line in table or modify bullet status of line.
18959 Also turns a plain line or a region of lines into list items.
18960 Calls `org-table-insert-hline', `org-toggle-item', or
18961 `org-cycle-list-bullet', depending on context."
18962 (interactive)
18963 (cond
18964 ((org-at-table-p)
18965 (call-interactively 'org-table-insert-hline))
18966 ((org-region-active-p)
18967 (call-interactively 'org-toggle-item))
18968 ((org-in-item-p)
18969 (call-interactively 'org-cycle-list-bullet))
18971 (call-interactively 'org-toggle-item))))
18973 (defun org-toggle-item (arg)
18974 "Convert headings or normal lines to items, items to normal lines.
18975 If there is no active region, only the current line is considered.
18977 If the first non blank line in the region is an headline, convert
18978 all headlines to items, shifting text accordingly.
18980 If it is an item, convert all items to normal lines.
18982 If it is normal text, change region into an item. With a prefix
18983 argument ARG, change each line in region into an item."
18984 (interactive "P")
18985 (let ((shift-text
18986 (function
18987 ;; Shift text in current section to IND, from point to END.
18988 ;; The function leaves point to END line.
18989 (lambda (ind end)
18990 (let ((min-i 1000) (end (copy-marker end)))
18991 ;; First determine the minimum indentation (MIN-I) of
18992 ;; the text.
18993 (save-excursion
18994 (catch 'exit
18995 (while (< (point) end)
18996 (let ((i (org-get-indentation)))
18997 (cond
18998 ;; Skip blank lines and inline tasks.
18999 ((looking-at "^[ \t]*$"))
19000 ((looking-at org-outline-regexp-bol))
19001 ;; We can't find less than 0 indentation.
19002 ((zerop i) (throw 'exit (setq min-i 0)))
19003 ((< i min-i) (setq min-i i))))
19004 (forward-line))))
19005 ;; Then indent each line so that a line indented to
19006 ;; MIN-I becomes indented to IND. Ignore blank lines
19007 ;; and inline tasks in the process.
19008 (let ((delta (- ind min-i)))
19009 (while (< (point) end)
19010 (unless (or (looking-at "^[ \t]*$")
19011 (looking-at org-outline-regexp-bol))
19012 (org-indent-line-to (+ (org-get-indentation) delta)))
19013 (forward-line)))))))
19014 (skip-blanks
19015 (function
19016 ;; Return beginning of first non-blank line, starting from
19017 ;; line at POS.
19018 (lambda (pos)
19019 (save-excursion
19020 (goto-char pos)
19021 (skip-chars-forward " \r\t\n")
19022 (point-at-bol)))))
19023 beg end)
19024 ;; Determine boundaries of changes.
19025 (if (org-region-active-p)
19026 (setq beg (funcall skip-blanks (region-beginning))
19027 end (copy-marker (region-end)))
19028 (setq beg (funcall skip-blanks (point-at-bol))
19029 end (copy-marker (point-at-eol))))
19030 ;; Depending on the starting line, choose an action on the text
19031 ;; between BEG and END.
19032 (org-with-limited-levels
19033 (save-excursion
19034 (goto-char beg)
19035 (cond
19036 ;; Case 1. Start at an item: de-itemize. Note that it only
19037 ;; happens when a region is active: `org-ctrl-c-minus'
19038 ;; would call `org-cycle-list-bullet' otherwise.
19039 ((org-at-item-p)
19040 (while (< (point) end)
19041 (when (org-at-item-p)
19042 (skip-chars-forward " \t")
19043 (delete-region (point) (match-end 0)))
19044 (forward-line)))
19045 ;; Case 2. Start at an heading: convert to items.
19046 ((org-at-heading-p)
19047 (let* ((bul (org-list-bullet-string "-"))
19048 (bul-len (length bul))
19049 ;; Indentation of the first heading. It should be
19050 ;; relative to the indentation of its parent, if any.
19051 (start-ind (save-excursion
19052 (cond
19053 ((not org-adapt-indentation) 0)
19054 ((not (outline-previous-heading)) 0)
19055 (t (length (match-string 0))))))
19056 ;; Level of first heading. Further headings will be
19057 ;; compared to it to determine hierarchy in the list.
19058 (ref-level (org-reduced-level (org-outline-level))))
19059 (while (< (point) end)
19060 (let* ((level (org-reduced-level (org-outline-level)))
19061 (delta (max 0 (- level ref-level))))
19062 ;; If current headline is less indented than the first
19063 ;; one, set it as reference, in order to preserve
19064 ;; subtrees.
19065 (when (< level ref-level) (setq ref-level level))
19066 (replace-match bul t t)
19067 (org-indent-line-to (+ start-ind (* delta bul-len)))
19068 ;; Ensure all text down to END (or SECTION-END) belongs
19069 ;; to the newly created item.
19070 (let ((section-end (save-excursion
19071 (or (outline-next-heading) (point)))))
19072 (forward-line)
19073 (funcall shift-text
19074 (+ start-ind (* (1+ delta) bul-len))
19075 (min end section-end)))))))
19076 ;; Case 3. Normal line with ARG: turn each non-item line into
19077 ;; an item.
19078 (arg
19079 (while (< (point) end)
19080 (unless (or (org-at-heading-p) (org-at-item-p))
19081 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19082 (replace-match
19083 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19084 (forward-line)))
19085 ;; Case 4. Normal line without ARG: make the first line of
19086 ;; region an item, and shift indentation of others
19087 ;; lines to set them as item's body.
19088 (t (let* ((bul (org-list-bullet-string "-"))
19089 (bul-len (length bul))
19090 (ref-ind (org-get-indentation)))
19091 (skip-chars-forward " \t")
19092 (insert bul)
19093 (forward-line)
19094 (while (< (point) end)
19095 ;; Ensure that lines less indented than first one
19096 ;; still get included in item body.
19097 (funcall shift-text
19098 (+ ref-ind bul-len)
19099 (min end (save-excursion (or (outline-next-heading)
19100 (point)))))
19101 (forward-line)))))))))
19103 (defun org-toggle-heading (&optional nstars)
19104 "Convert headings to normal text, or items or text to headings.
19105 If there is no active region, only the current line is considered.
19107 With a \\[universal-argument] prefix, convert the whole list at
19108 point into heading.
19110 In a region:
19112 - If the first non blank line is an headline, remove the stars
19113 from all headlines in the region.
19115 - If it is a normal line turn each and every normal line (i.e. not an
19116 heading or an item) in the region into a heading.
19118 - If it is a plain list item, turn all plain list items into headings.
19120 When converting a line into a heading, the number of stars is chosen
19121 such that the lines become children of the current entry. However,
19122 when a prefix argument is given, its value determines the number of
19123 stars to add."
19124 (interactive "P")
19125 (let ((skip-blanks
19126 (function
19127 ;; Return beginning of first non-blank line, starting from
19128 ;; line at POS.
19129 (lambda (pos)
19130 (save-excursion
19131 (goto-char pos)
19132 (skip-chars-forward " \r\t\n")
19133 (point-at-bol)))))
19134 beg end)
19135 ;; Determine boundaries of changes. If a universal prefix has
19136 ;; been given, put the list in a region. If region ends at a bol,
19137 ;; do not consider the last line to be in the region.
19139 (when (and current-prefix-arg (org-at-item-p))
19140 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19141 (org-mark-list))
19143 (if (org-region-active-p)
19144 (setq beg (funcall skip-blanks (region-beginning))
19145 end (copy-marker (save-excursion
19146 (goto-char (region-end))
19147 (if (bolp) (point) (point-at-eol)))))
19148 (setq beg (funcall skip-blanks (point-at-bol))
19149 end (copy-marker (point-at-eol))))
19150 ;; Ensure inline tasks don't count as headings.
19151 (org-with-limited-levels
19152 (save-excursion
19153 (goto-char beg)
19154 (cond
19155 ;; Case 1. Started at an heading: de-star headings.
19156 ((org-at-heading-p)
19157 (while (< (point) end)
19158 (when (org-at-heading-p t)
19159 (looking-at org-outline-regexp) (replace-match ""))
19160 (forward-line)))
19161 ;; Case 2. Started at an item: change items into headlines.
19162 ;; One star will be added by `org-list-to-subtree'.
19163 ((org-at-item-p)
19164 (let* ((stars (make-string
19165 (if nstars
19166 ;; subtract the star that will be added again by
19167 ;; `org-list-to-subtree'
19168 (1- (prefix-numeric-value current-prefix-arg))
19169 (or (org-current-level) 0))
19170 ?*))
19171 (add-stars
19172 (cond (nstars "") ; stars from prefix only
19173 ((equal stars "") "") ; before first heading
19174 (org-odd-levels-only "*") ; inside heading, odd
19175 (t "")))) ; inside heading, oddeven
19176 (while (< (point) end)
19177 (when (org-at-item-p)
19178 ;; Pay attention to cases when region ends before list.
19179 (let* ((struct (org-list-struct))
19180 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19181 (save-restriction
19182 (narrow-to-region (point) list-end)
19183 (insert
19184 (org-list-to-subtree
19185 (org-list-parse-list t)
19186 '(:istart (concat stars add-stars (funcall get-stars depth))
19187 :icount (concat stars add-stars (funcall get-stars depth))))))))
19188 (forward-line))))
19189 ;; Case 3. Started at normal text: make every line an heading,
19190 ;; skipping headlines and items.
19191 (t (let* ((stars (make-string
19192 (if nstars
19193 (prefix-numeric-value current-prefix-arg)
19194 (or (org-current-level) 0))
19195 ?*))
19196 (add-stars
19197 (cond (nstars "") ; stars from prefix only
19198 ((equal stars "") "*") ; before first heading
19199 (org-odd-levels-only "**") ; inside heading, odd
19200 (t "*"))) ; inside heading, oddeven
19201 (rpl (concat stars add-stars " ")))
19202 (while (< (point) end)
19203 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19204 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19205 (replace-match (concat rpl (match-string 2))))
19206 (forward-line)))))))))
19208 (defun org-meta-return (&optional arg)
19209 "Insert a new heading or wrap a region in a table.
19210 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19211 See the individual commands for more information."
19212 (interactive "P")
19213 (cond
19214 ((run-hook-with-args-until-success 'org-metareturn-hook))
19215 ((or (org-at-drawer-p) (org-at-property-p))
19216 (newline-and-indent))
19217 ((org-at-table-p)
19218 (call-interactively 'org-table-wrap-region))
19219 (t (call-interactively 'org-insert-heading))))
19221 ;;; Menu entries
19223 ;; Define the Org-mode menus
19224 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19225 '("Tbl"
19226 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19227 ["Next Field" org-cycle (org-at-table-p)]
19228 ["Previous Field" org-shifttab (org-at-table-p)]
19229 ["Next Row" org-return (org-at-table-p)]
19230 "--"
19231 ["Blank Field" org-table-blank-field (org-at-table-p)]
19232 ["Edit Field" org-table-edit-field (org-at-table-p)]
19233 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19234 "--"
19235 ("Column"
19236 ["Move Column Left" org-metaleft (org-at-table-p)]
19237 ["Move Column Right" org-metaright (org-at-table-p)]
19238 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19239 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19240 ("Row"
19241 ["Move Row Up" org-metaup (org-at-table-p)]
19242 ["Move Row Down" org-metadown (org-at-table-p)]
19243 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19244 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19245 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19246 "--"
19247 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19248 ("Rectangle"
19249 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19250 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19251 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19252 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19253 "--"
19254 ("Calculate"
19255 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19256 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19257 ["Edit Formulas" org-edit-special (org-at-table-p)]
19258 "--"
19259 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19260 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19261 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19262 "--"
19263 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19264 "--"
19265 ["Sum Column/Rectangle" org-table-sum
19266 (or (org-at-table-p) (org-region-active-p))]
19267 ["Which Column?" org-table-current-column (org-at-table-p)])
19268 ["Debug Formulas"
19269 org-table-toggle-formula-debugger
19270 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19271 ["Show Col/Row Numbers"
19272 org-table-toggle-coordinate-overlays
19273 :style toggle
19274 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19275 "--"
19276 ["Create" org-table-create (and (not (org-at-table-p))
19277 org-enable-table-editor)]
19278 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19279 ["Import from File" org-table-import (not (org-at-table-p))]
19280 ["Export to File" org-table-export (org-at-table-p)]
19281 "--"
19282 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19284 (easy-menu-define org-org-menu org-mode-map "Org menu"
19285 '("Org"
19286 ("Show/Hide"
19287 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19288 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19289 ["Sparse Tree..." org-sparse-tree t]
19290 ["Reveal Context" org-reveal t]
19291 ["Show All" show-all t]
19292 "--"
19293 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19294 "--"
19295 ["New Heading" org-insert-heading t]
19296 ("Navigate Headings"
19297 ["Up" outline-up-heading t]
19298 ["Next" outline-next-visible-heading t]
19299 ["Previous" outline-previous-visible-heading t]
19300 ["Next Same Level" outline-forward-same-level t]
19301 ["Previous Same Level" outline-backward-same-level t]
19302 "--"
19303 ["Jump" org-goto t])
19304 ("Edit Structure"
19305 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19306 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19307 "--"
19308 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19309 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19310 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19311 "--"
19312 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19313 "--"
19314 ["Copy visible text" org-copy-visible t]
19315 "--"
19316 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19317 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19318 ["Demote Heading" org-metaright (not (org-at-table-p))]
19319 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19320 "--"
19321 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19322 "--"
19323 ["Convert to odd levels" org-convert-to-odd-levels t]
19324 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19325 ("Editing"
19326 ["Emphasis..." org-emphasize t]
19327 ["Edit Source Example" org-edit-special t]
19328 "--"
19329 ["Footnote new/jump" org-footnote-action t]
19330 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19331 ("Archive"
19332 ["Archive (default method)" org-archive-subtree-default t]
19333 "--"
19334 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19335 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19336 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19338 "--"
19339 ("Hyperlinks"
19340 ["Store Link (Global)" org-store-link t]
19341 ["Find existing link to here" org-occur-link-in-agenda-files t]
19342 ["Insert Link" org-insert-link t]
19343 ["Follow Link" org-open-at-point t]
19344 "--"
19345 ["Next link" org-next-link t]
19346 ["Previous link" org-previous-link t]
19347 "--"
19348 ["Descriptive Links"
19349 org-toggle-link-display
19350 :style radio
19351 :selected org-descriptive-links
19353 ["Literal Links"
19354 org-toggle-link-display
19355 :style radio
19356 :selected (not org-descriptive-links)])
19357 "--"
19358 ("TODO Lists"
19359 ["TODO/DONE/-" org-todo t]
19360 ("Select keyword"
19361 ["Next keyword" org-shiftright (org-at-heading-p)]
19362 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19363 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19364 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19365 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19366 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19367 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19368 "--"
19369 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19370 :selected org-enforce-todo-dependencies :style toggle :active t]
19371 "Settings for tree at point"
19372 ["Do Children sequentially" org-toggle-ordered-property :style radio
19373 :selected (org-entry-get nil "ORDERED")
19374 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19375 ["Do Children parallel" org-toggle-ordered-property :style radio
19376 :selected (not (org-entry-get nil "ORDERED"))
19377 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19378 "--"
19379 ["Set Priority" org-priority t]
19380 ["Priority Up" org-shiftup t]
19381 ["Priority Down" org-shiftdown t]
19382 "--"
19383 ["Get news from all feeds" org-feed-update-all t]
19384 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19385 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19386 ("TAGS and Properties"
19387 ["Set Tags" org-set-tags-command t]
19388 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19389 "--"
19390 ["Set property" org-set-property t]
19391 ["Column view of properties" org-columns t]
19392 ["Insert Column View DBlock" org-insert-columns-dblock t])
19393 ("Dates and Scheduling"
19394 ["Timestamp" org-time-stamp t]
19395 ["Timestamp (inactive)" org-time-stamp-inactive t]
19396 ("Change Date"
19397 ["1 Day Later" org-shiftright t]
19398 ["1 Day Earlier" org-shiftleft t]
19399 ["1 ... Later" org-shiftup t]
19400 ["1 ... Earlier" org-shiftdown t])
19401 ["Compute Time Range" org-evaluate-time-range t]
19402 ["Schedule Item" org-schedule t]
19403 ["Deadline" org-deadline t]
19404 "--"
19405 ["Custom time format" org-toggle-time-stamp-overlays
19406 :style radio :selected org-display-custom-times]
19407 "--"
19408 ["Goto Calendar" org-goto-calendar t]
19409 ["Date from Calendar" org-date-from-calendar t]
19410 "--"
19411 ["Start/Restart Timer" org-timer-start t]
19412 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19413 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19414 ["Insert Timer String" org-timer t]
19415 ["Insert Timer Item" org-timer-item t])
19416 ("Logging work"
19417 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19418 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19419 ["Clock out" org-clock-out t]
19420 ["Clock cancel" org-clock-cancel t]
19421 "--"
19422 ["Mark as default task" org-clock-mark-default-task t]
19423 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19424 ["Goto running clock" org-clock-goto t]
19425 "--"
19426 ["Display times" org-clock-display t]
19427 ["Create clock table" org-clock-report t]
19428 "--"
19429 ["Record DONE time"
19430 (progn (setq org-log-done (not org-log-done))
19431 (message "Switching to %s will %s record a timestamp"
19432 (car org-done-keywords)
19433 (if org-log-done "automatically" "not")))
19434 :style toggle :selected org-log-done])
19435 "--"
19436 ["Agenda Command..." org-agenda t]
19437 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19438 ("File List for Agenda")
19439 ("Special views current file"
19440 ["TODO Tree" org-show-todo-tree t]
19441 ["Check Deadlines" org-check-deadlines t]
19442 ["Timeline" org-timeline t]
19443 ["Tags/Property tree" org-match-sparse-tree t])
19444 "--"
19445 ["Export/Publish..." org-export t]
19446 ("LaTeX"
19447 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19448 :selected org-cdlatex-mode]
19449 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19450 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19451 ["Modify math symbol" org-cdlatex-math-modify
19452 (org-inside-LaTeX-fragment-p)]
19453 ["Insert citation" org-reftex-citation t]
19454 "--"
19455 ["Template for BEAMER" (progn (require 'org-beamer)
19456 (org-insert-beamer-options-template)) t])
19457 "--"
19458 ("MobileOrg"
19459 ["Push Files and Views" org-mobile-push t]
19460 ["Get Captured and Flagged" org-mobile-pull t]
19461 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19462 "--"
19463 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19464 "--"
19465 ("Documentation"
19466 ["Show Version" org-version t]
19467 ["Info Documentation" org-info t])
19468 ("Customize"
19469 ["Browse Org Group" org-customize t]
19470 "--"
19471 ["Expand This Menu" org-create-customize-menu
19472 (fboundp 'customize-menu-create)])
19473 ["Send bug report" org-submit-bug-report t]
19474 "--"
19475 ("Refresh/Reload"
19476 ["Refresh setup current buffer" org-mode-restart t]
19477 ["Reload Org (after update)" org-reload t]
19478 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19481 (defun org-info (&optional node)
19482 "Read documentation for Org-mode in the info system.
19483 With optional NODE, go directly to that node."
19484 (interactive)
19485 (info (format "(org)%s" (or node ""))))
19487 ;;;###autoload
19488 (defun org-submit-bug-report ()
19489 "Submit a bug report on Org-mode via mail.
19491 Don't hesitate to report any problems or inaccurate documentation.
19493 If you don't have setup sending mail from (X)Emacs, please copy the
19494 output buffer into your mail program, as it gives us important
19495 information about your Org-mode version and configuration."
19496 (interactive)
19497 (require 'reporter)
19498 (org-load-modules-maybe)
19499 (org-require-autoloaded-modules)
19500 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19501 (reporter-submit-bug-report
19502 "emacs-orgmode@gnu.org"
19503 (org-version nil 'full)
19504 (let (list)
19505 (save-window-excursion
19506 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19507 (delete-other-windows)
19508 (erase-buffer)
19509 (insert "You are about to submit a bug report to the Org-mode mailing list.
19511 We would like to add your full Org-mode and Outline configuration to the
19512 bug report. This greatly simplifies the work of the maintainer and
19513 other experts on the mailing list.
19515 HOWEVER, some variables you have customized may contain private
19516 information. The names of customers, colleagues, or friends, might
19517 appear in the form of file names, tags, todo states, or search strings.
19518 If you answer yes to the prompt, you might want to check and remove
19519 such private information before sending the email.")
19520 (add-text-properties (point-min) (point-max) '(face org-warning))
19521 (when (yes-or-no-p "Include your Org-mode configuration ")
19522 (mapatoms
19523 (lambda (v)
19524 (and (boundp v)
19525 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19526 (or (and (symbol-value v)
19527 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19528 (and
19529 (get v 'custom-type) (get v 'standard-value)
19530 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19531 (push v list)))))
19532 (kill-buffer (get-buffer "*Warn about privacy*"))
19533 list))
19534 nil nil
19535 "Remember to cover the basics, that is, what you expected to happen and
19536 what in fact did happen. You don't know how to make a good report? See
19538 http://orgmode.org/manual/Feedback.html#Feedback
19540 Your bug report will be posted to the Org-mode mailing list.
19541 ------------------------------------------------------------------------")
19542 (save-excursion
19543 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19544 (replace-match "\\1Bug: \\3 [\\2]")))))
19547 (defun org-install-agenda-files-menu ()
19548 (let ((bl (buffer-list)))
19549 (save-excursion
19550 (while bl
19551 (set-buffer (pop bl))
19552 (if (derived-mode-p 'org-mode) (setq bl nil)))
19553 (when (derived-mode-p 'org-mode)
19554 (easy-menu-change
19555 '("Org") "File List for Agenda"
19556 (append
19557 (list
19558 ["Edit File List" (org-edit-agenda-file-list) t]
19559 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19560 ["Remove Current File from List" org-remove-file t]
19561 ["Cycle through agenda files" org-cycle-agenda-files t]
19562 ["Occur in all agenda files" org-occur-in-agenda-files t]
19563 "--")
19564 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19566 ;;;; Documentation
19568 ;;;###autoload
19569 (defun org-require-autoloaded-modules ()
19570 (interactive)
19571 (mapc 'require
19572 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19573 org-docbook org-exp org-html org-icalendar
19574 org-id org-latex
19575 org-publish org-remember org-table
19576 org-timer org-xoxo)))
19578 ;;;###autoload
19579 (defun org-reload (&optional uncompiled)
19580 "Reload all org lisp files.
19581 With prefix arg UNCOMPILED, load the uncompiled versions."
19582 (interactive "P")
19583 (require 'find-func)
19584 (let* ((file-re "^org\\(-.*\\)?\\.el")
19585 (dir-org (file-name-directory (org-find-library-dir "org")))
19586 (dir-org-contrib (ignore-errors
19587 (file-name-directory
19588 (org-find-library-dir "org-contribdir"))))
19589 (babel-files
19590 (mapcar (lambda (el) (concat (concat dir-org "ob") (when el (format "-%s" el)) ".el"))
19591 (append (list nil "comint" "eval" "exp" "keys"
19592 "lob" "ref" "table" "tangle")
19593 (delq nil
19594 (mapcar
19595 (lambda (lang)
19596 (when (cdr lang) (symbol-name (car lang))))
19597 org-babel-load-languages)))))
19598 (files
19599 (append babel-files
19600 (and dir-org-contrib
19601 (directory-files dir-org-contrib t file-re))
19602 (directory-files dir-org t file-re)))
19603 (remove-re (concat (if (featurep 'xemacs)
19604 "org-colview" "org-colview-xemacs")
19605 "\\'")))
19606 (setq files (mapcar 'file-name-sans-extension files))
19607 (setq files (mapcar
19608 (lambda (x) (if (string-match remove-re x) nil x))
19609 files))
19610 (setq files (delq nil files))
19611 (mapc
19612 (lambda (f)
19613 (when (featurep (intern (file-name-nondirectory f)))
19614 (if (and (not uncompiled)
19615 (file-exists-p (concat f ".elc")))
19616 (load (concat f ".elc") nil nil 'nosuffix)
19617 (load (concat f ".el") nil nil 'nosuffix))))
19618 files)
19619 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19620 (org-version nil 'full 'message))
19622 ;;;###autoload
19623 (defun org-customize ()
19624 "Call the customize function with org as argument."
19625 (interactive)
19626 (org-load-modules-maybe)
19627 (org-require-autoloaded-modules)
19628 (customize-browse 'org))
19630 (defun org-create-customize-menu ()
19631 "Create a full customization menu for Org-mode, insert it into the menu."
19632 (interactive)
19633 (org-load-modules-maybe)
19634 (org-require-autoloaded-modules)
19635 (if (fboundp 'customize-menu-create)
19636 (progn
19637 (easy-menu-change
19638 '("Org") "Customize"
19639 `(["Browse Org group" org-customize t]
19640 "--"
19641 ,(customize-menu-create 'org)
19642 ["Set" Custom-set t]
19643 ["Save" Custom-save t]
19644 ["Reset to Current" Custom-reset-current t]
19645 ["Reset to Saved" Custom-reset-saved t]
19646 ["Reset to Standard Settings" Custom-reset-standard t]))
19647 (message "\"Org\"-menu now contains full customization menu"))
19648 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19650 ;;;; Miscellaneous stuff
19652 ;;; Generally useful functions
19654 (defun org-get-at-bol (property)
19655 "Get text property PROPERTY at beginning of line."
19656 (get-text-property (point-at-bol) property))
19658 (defun org-find-text-property-in-string (prop s)
19659 "Return the first non-nil value of property PROP in string S."
19660 (or (get-text-property 0 prop s)
19661 (get-text-property (or (next-single-property-change 0 prop s) 0)
19662 prop s)))
19664 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19665 "Display the given MESSAGE as a warning."
19666 (if (fboundp 'display-warning)
19667 (display-warning 'org message
19668 (if (featurep 'xemacs) 'warning :warning))
19669 (let ((buf (get-buffer-create "*Org warnings*")))
19670 (with-current-buffer buf
19671 (goto-char (point-max))
19672 (insert "Warning (Org): " message)
19673 (unless (bolp)
19674 (newline)))
19675 (display-buffer buf)
19676 (sit-for 0))))
19678 (defun org-eval (form)
19679 "Eval FORM and return result."
19680 (condition-case error
19681 (eval form)
19682 (error (format "%%![Error: %s]" error))))
19684 (defun org-in-clocktable-p ()
19685 "Check if the cursor is in a clocktable."
19686 (let ((pos (point)) start)
19687 (save-excursion
19688 (end-of-line 1)
19689 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19690 (setq start (match-beginning 0))
19691 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19692 (>= (match-end 0) pos)
19693 start))))
19695 (defun org-in-commented-line ()
19696 "Is point in a line starting with `#'?"
19697 (equal (char-after (point-at-bol)) ?#))
19699 (defun org-in-indented-comment-line ()
19700 "Is point in a line starting with `#' after some white space?"
19701 (save-excursion
19702 (save-match-data
19703 (goto-char (point-at-bol))
19704 (looking-at "[ \t]*#"))))
19706 (defun org-in-verbatim-emphasis ()
19707 (save-match-data
19708 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19710 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19711 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19712 (if (and marker (marker-buffer marker)
19713 (buffer-live-p (marker-buffer marker)))
19714 (progn
19715 (org-pop-to-buffer-same-window (marker-buffer marker))
19716 (if (or (> marker (point-max)) (< marker (point-min)))
19717 (widen))
19718 (goto-char marker)
19719 (org-show-context 'org-goto))
19720 (if bookmark
19721 (bookmark-jump bookmark)
19722 (error "Cannot find location"))))
19724 (defun org-quote-csv-field (s)
19725 "Quote field for inclusion in CSV material."
19726 (if (string-match "[\",]" s)
19727 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19730 (defun org-force-self-insert (N)
19731 "Needed to enforce self-insert under remapping."
19732 (interactive "p")
19733 (self-insert-command N))
19735 (defun org-string-width (s)
19736 "Compute width of string, ignoring invisible characters.
19737 This ignores character with invisibility property `org-link', and also
19738 characters with property `org-cwidth', because these will become invisible
19739 upon the next fontification round."
19740 (let (b l)
19741 (when (or (eq t buffer-invisibility-spec)
19742 (assq 'org-link buffer-invisibility-spec))
19743 (while (setq b (text-property-any 0 (length s)
19744 'invisible 'org-link s))
19745 (setq s (concat (substring s 0 b)
19746 (substring s (or (next-single-property-change
19747 b 'invisible s) (length s)))))))
19748 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19749 (setq s (concat (substring s 0 b)
19750 (substring s (or (next-single-property-change
19751 b 'org-cwidth s) (length s))))))
19752 (setq l (string-width s) b -1)
19753 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19754 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19757 (defun org-shorten-string (s maxlength)
19758 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19759 If the string is shorter or has length MAXLENGTH, just return the
19760 original string. If it is longer, the functions finds a space in the
19761 string, breaks this string off at that locations and adds three dots
19762 as ellipsis. Including the ellipsis, the string will not be longer
19763 than MAXLENGTH. If finding a good breaking point in the string does
19764 not work, the string is just chopped off in the middle of a word
19765 if necessary."
19766 (if (<= (length s) maxlength)
19768 (let* ((n (max (- maxlength 4) 1))
19769 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19770 (if (string-match re s)
19771 (concat (match-string 1 s) "...")
19772 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19774 (defun org-get-indentation (&optional line)
19775 "Get the indentation of the current line, interpreting tabs.
19776 When LINE is given, assume it represents a line and compute its indentation."
19777 (if line
19778 (if (string-match "^ *" (org-remove-tabs line))
19779 (match-end 0))
19780 (save-excursion
19781 (beginning-of-line 1)
19782 (skip-chars-forward " \t")
19783 (current-column))))
19785 (defun org-get-string-indentation (s)
19786 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19787 (let ((n -1) (i 0) (w tab-width) c)
19788 (catch 'exit
19789 (while (< (setq n (1+ n)) (length s))
19790 (setq c (aref s n))
19791 (cond ((= c ?\ ) (setq i (1+ i)))
19792 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19793 (t (throw 'exit t)))))
19796 (defun org-remove-tabs (s &optional width)
19797 "Replace tabulators in S with spaces.
19798 Assumes that s is a single line, starting in column 0."
19799 (setq width (or width tab-width))
19800 (while (string-match "\t" s)
19801 (setq s (replace-match
19802 (make-string
19803 (- (* width (/ (+ (match-beginning 0) width) width))
19804 (match-beginning 0)) ?\ )
19805 t t s)))
19808 (defun org-fix-indentation (line ind)
19809 "Fix indentation in LINE.
19810 IND is a cons cell with target and minimum indentation.
19811 If the current indentation in LINE is smaller than the minimum,
19812 leave it alone. If it is larger than ind, set it to the target."
19813 (let* ((l (org-remove-tabs line))
19814 (i (org-get-indentation l))
19815 (i1 (car ind)) (i2 (cdr ind)))
19816 (if (>= i i2) (setq l (substring line i2)))
19817 (if (> i1 0)
19818 (concat (make-string i1 ?\ ) l)
19819 l)))
19821 (defun org-remove-indentation (code &optional n)
19822 "Remove the maximum common indentation from the lines in CODE.
19823 N may optionally be the number of spaces to remove."
19824 (with-temp-buffer
19825 (insert code)
19826 (org-do-remove-indentation n)
19827 (buffer-string)))
19829 (defun org-do-remove-indentation (&optional n)
19830 "Remove the maximum common indentation from the buffer."
19831 (untabify (point-min) (point-max))
19832 (let ((min 10000) re)
19833 (if n
19834 (setq min n)
19835 (goto-char (point-min))
19836 (while (re-search-forward "^ *[^ \n]" nil t)
19837 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19838 (unless (or (= min 0) (= min 10000))
19839 (setq re (format "^ \\{%d\\}" min))
19840 (goto-char (point-min))
19841 (while (re-search-forward re nil t)
19842 (replace-match "")
19843 (end-of-line 1))
19844 min)))
19846 (defun org-fill-template (template alist)
19847 "Find each %key of ALIST in TEMPLATE and replace it."
19848 (let ((case-fold-search nil)
19849 entry key value)
19850 (setq alist (sort (copy-sequence alist)
19851 (lambda (a b) (< (length (car a)) (length (car b))))))
19852 (while (setq entry (pop alist))
19853 (setq template
19854 (replace-regexp-in-string
19855 (concat "%" (regexp-quote (car entry)))
19856 (cdr entry) template t t)))
19857 template))
19859 (defun org-base-buffer (buffer)
19860 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19861 (if (not buffer)
19862 buffer
19863 (or (buffer-base-buffer buffer)
19864 buffer)))
19866 (defun org-trim (s)
19867 "Remove whitespace at beginning and end of string."
19868 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19869 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19872 (defun org-wrap (string &optional width lines)
19873 "Wrap string to either a number of lines, or a width in characters.
19874 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19875 that costs. If there is a word longer than WIDTH, the text is actually
19876 wrapped to the length of that word.
19877 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19878 many lines, whatever width that takes.
19879 The return value is a list of lines, without newlines at the end."
19880 (let* ((words (org-split-string string "[ \t\n]+"))
19881 (maxword (apply 'max (mapcar 'org-string-width words)))
19882 w ll)
19883 (cond (width
19884 (org-do-wrap words (max maxword width)))
19885 (lines
19886 (setq w maxword)
19887 (setq ll (org-do-wrap words maxword))
19888 (if (<= (length ll) lines)
19890 (setq ll words)
19891 (while (> (length ll) lines)
19892 (setq w (1+ w))
19893 (setq ll (org-do-wrap words w)))
19894 ll))
19895 (t (error "Cannot wrap this")))))
19897 (defun org-do-wrap (words width)
19898 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19899 (let (lines line)
19900 (while words
19901 (setq line (pop words))
19902 (while (and words (< (+ (length line) (length (car words))) width))
19903 (setq line (concat line " " (pop words))))
19904 (setq lines (push line lines)))
19905 (nreverse lines)))
19907 (defun org-split-string (string &optional separators)
19908 "Splits STRING into substrings at SEPARATORS.
19909 No empty strings are returned if there are matches at the beginning
19910 and end of string."
19911 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19912 (start 0)
19913 notfirst
19914 (list nil))
19915 (while (and (string-match rexp string
19916 (if (and notfirst
19917 (= start (match-beginning 0))
19918 (< start (length string)))
19919 (1+ start) start))
19920 (< (match-beginning 0) (length string)))
19921 (setq notfirst t)
19922 (or (eq (match-beginning 0) 0)
19923 (and (eq (match-beginning 0) (match-end 0))
19924 (eq (match-beginning 0) start))
19925 (setq list
19926 (cons (substring string start (match-beginning 0))
19927 list)))
19928 (setq start (match-end 0)))
19929 (or (eq start (length string))
19930 (setq list
19931 (cons (substring string start)
19932 list)))
19933 (nreverse list)))
19935 (defun org-quote-vert (s)
19936 "Replace \"|\" with \"\\vert\"."
19937 (while (string-match "|" s)
19938 (setq s (replace-match "\\vert" t t s)))
19941 (defun org-uuidgen-p (s)
19942 "Is S an ID created by UUIDGEN?"
19943 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19945 (defun org-in-src-block-p nil
19946 "Whether point is in a code source block."
19947 (let (ov)
19948 (when (setq ov (overlays-at (point)))
19949 (memq 'org-block-background
19950 (overlay-properties
19951 (car ov))))))
19953 (defun org-context ()
19954 "Return a list of contexts of the current cursor position.
19955 If several contexts apply, all are returned.
19956 Each context entry is a list with a symbol naming the context, and
19957 two positions indicating start and end of the context. Possible
19958 contexts are:
19960 :headline anywhere in a headline
19961 :headline-stars on the leading stars in a headline
19962 :todo-keyword on a TODO keyword (including DONE) in a headline
19963 :tags on the TAGS in a headline
19964 :priority on the priority cookie in a headline
19965 :item on the first line of a plain list item
19966 :item-bullet on the bullet/number of a plain list item
19967 :checkbox on the checkbox in a plain list item
19968 :table in an org-mode table
19969 :table-special on a special filed in a table
19970 :table-table in a table.el table
19971 :clocktable in a clocktable
19972 :src-block in a source block
19973 :link on a hyperlink
19974 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19975 :target on a <<target>>
19976 :radio-target on a <<<radio-target>>>
19977 :latex-fragment on a LaTeX fragment
19978 :latex-preview on a LaTeX fragment with overlaid preview image
19980 This function expects the position to be visible because it uses font-lock
19981 faces as a help to recognize the following contexts: :table-special, :link,
19982 and :keyword."
19983 (let* ((f (get-text-property (point) 'face))
19984 (faces (if (listp f) f (list f)))
19985 (case-fold-search t)
19986 (p (point)) clist o)
19987 ;; First the large context
19988 (cond
19989 ((org-at-heading-p t)
19990 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19991 (when (progn
19992 (beginning-of-line 1)
19993 (looking-at org-todo-line-tags-regexp))
19994 (push (org-point-in-group p 1 :headline-stars) clist)
19995 (push (org-point-in-group p 2 :todo-keyword) clist)
19996 (push (org-point-in-group p 4 :tags) clist))
19997 (goto-char p)
19998 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19999 (if (looking-at "\\[#[A-Z0-9]\\]")
20000 (push (org-point-in-group p 0 :priority) clist)))
20002 ((org-at-item-p)
20003 (push (org-point-in-group p 2 :item-bullet) clist)
20004 (push (list :item (point-at-bol)
20005 (save-excursion (org-end-of-item) (point)))
20006 clist)
20007 (and (org-at-item-checkbox-p)
20008 (push (org-point-in-group p 0 :checkbox) clist)))
20010 ((org-at-table-p)
20011 (push (list :table (org-table-begin) (org-table-end)) clist)
20012 (if (memq 'org-formula faces)
20013 (push (list :table-special
20014 (previous-single-property-change p 'face)
20015 (next-single-property-change p 'face)) clist)))
20016 ((org-at-table-p 'any)
20017 (push (list :table-table) clist)))
20018 (goto-char p)
20020 ;; New the "medium" contexts: clocktables, source blocks
20021 (cond ((org-in-clocktable-p)
20022 (push (list :clocktable
20023 (and (or (looking-at "#\\+BEGIN: clocktable")
20024 (search-backward "#+BEGIN: clocktable" nil t))
20025 (match-beginning 0))
20026 (and (re-search-forward "#\\+END:?" nil t)
20027 (match-end 0))) clist))
20028 ((org-in-src-block-p)
20029 (push (list :src-block
20030 (and (or (looking-at "#\\+BEGIN_SRC")
20031 (search-backward "#+BEGIN_SRC" nil t))
20032 (match-beginning 0))
20033 (and (search-forward "#+END_SRC" nil t)
20034 (match-beginning 0))) clist)))
20035 (goto-char p)
20037 ;; Now the small context
20038 (cond
20039 ((org-at-timestamp-p)
20040 (push (org-point-in-group p 0 :timestamp) clist))
20041 ((memq 'org-link faces)
20042 (push (list :link
20043 (previous-single-property-change p 'face)
20044 (next-single-property-change p 'face)) clist))
20045 ((memq 'org-special-keyword faces)
20046 (push (list :keyword
20047 (previous-single-property-change p 'face)
20048 (next-single-property-change p 'face)) clist))
20049 ((org-at-target-p)
20050 (push (org-point-in-group p 0 :target) clist)
20051 (goto-char (1- (match-beginning 0)))
20052 (if (looking-at org-radio-target-regexp)
20053 (push (org-point-in-group p 0 :radio-target) clist))
20054 (goto-char p))
20055 ((setq o (car (delq nil
20056 (mapcar
20057 (lambda (x)
20058 (if (memq x org-latex-fragment-image-overlays) x))
20059 (overlays-at (point))))))
20060 (push (list :latex-fragment
20061 (overlay-start o) (overlay-end o)) clist)
20062 (push (list :latex-preview
20063 (overlay-start o) (overlay-end o)) clist))
20064 ((org-inside-LaTeX-fragment-p)
20065 ;; FIXME: positions wrong.
20066 (push (list :latex-fragment (point) (point)) clist)))
20068 (setq clist (nreverse (delq nil clist)))
20069 clist))
20071 ;; FIXME: Compare with at-regexp-p Do we need both?
20072 (defun org-in-regexp (re &optional nlines visually)
20073 "Check if point is inside a match of regexp.
20074 Normally only the current line is checked, but you can include NLINES extra
20075 lines both before and after point into the search.
20076 If VISUALLY is set, require that the cursor is not after the match but
20077 really on, so that the block visually is on the match."
20078 (catch 'exit
20079 (let ((pos (point))
20080 (eol (point-at-eol (+ 1 (or nlines 0))))
20081 (inc (if visually 1 0)))
20082 (save-excursion
20083 (beginning-of-line (- 1 (or nlines 0)))
20084 (while (re-search-forward re eol t)
20085 (if (and (<= (match-beginning 0) pos)
20086 (>= (+ inc (match-end 0)) pos))
20087 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20089 (defun org-at-regexp-p (regexp)
20090 "Is point inside a match of REGEXP in the current line?"
20091 (catch 'exit
20092 (save-excursion
20093 (let ((pos (point)) (end (point-at-eol)))
20094 (beginning-of-line 1)
20095 (while (re-search-forward regexp end t)
20096 (if (and (<= (match-beginning 0) pos)
20097 (>= (match-end 0) pos))
20098 (throw 'exit t)))
20099 nil))))
20101 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20102 "Non-nil when point is between matches of START-RE and END-RE.
20104 Also return a non-nil value when point is on one of the matches.
20106 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20107 buffer positions. Default values are the positions of headlines
20108 surrounding the point.
20110 The functions returns a cons cell whose car (resp. cdr) is the
20111 position before START-RE (resp. after END-RE)."
20112 (save-match-data
20113 (let ((pos (point))
20114 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20115 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20116 beg end)
20117 (save-excursion
20118 ;; Point is on a block when on START-RE or if START-RE can be
20119 ;; found before it...
20120 (and (or (org-at-regexp-p start-re)
20121 (re-search-backward start-re limit-up t))
20122 (setq beg (match-beginning 0))
20123 ;; ... and END-RE after it...
20124 (goto-char (match-end 0))
20125 (re-search-forward end-re limit-down t)
20126 (> (setq end (match-end 0)) pos)
20127 ;; ... without another START-RE in-between.
20128 (goto-char (match-beginning 0))
20129 (not (re-search-backward start-re (1+ beg) t))
20130 ;; Return value.
20131 (cons beg end))))))
20133 (defun org-in-block-p (names)
20134 "Non-nil when point belongs to a block whose name belongs to NAMES.
20136 NAMES is a list of strings containing names of blocks.
20138 Return first block name matched, or nil. Beware that in case of
20139 nested blocks, the returned name may not belong to the closest
20140 block from point."
20141 (save-match-data
20142 (catch 'exit
20143 (let ((case-fold-search t)
20144 (lim-up (save-excursion (outline-previous-heading)))
20145 (lim-down (save-excursion (outline-next-heading))))
20146 (mapc (lambda (name)
20147 (let ((n (regexp-quote name)))
20148 (when (org-between-regexps-p
20149 (concat "^[ \t]*#\\+begin_" n)
20150 (concat "^[ \t]*#\\+end_" n)
20151 lim-up lim-down)
20152 (throw 'exit n))))
20153 names))
20154 nil)))
20156 (defun org-occur-in-agenda-files (regexp &optional nlines)
20157 "Call `multi-occur' with buffers for all agenda files."
20158 (interactive "sOrg-files matching: \np")
20159 (let* ((files (org-agenda-files))
20160 (tnames (mapcar 'file-truename files))
20161 (extra org-agenda-text-search-extra-files)
20163 (when (eq (car extra) 'agenda-archives)
20164 (setq extra (cdr extra))
20165 (setq files (org-add-archive-files files)))
20166 (while (setq f (pop extra))
20167 (unless (member (file-truename f) tnames)
20168 (add-to-list 'files f 'append)
20169 (add-to-list 'tnames (file-truename f) 'append)))
20170 (multi-occur
20171 (mapcar (lambda (x)
20172 (with-current-buffer
20173 (or (get-file-buffer x) (find-file-noselect x))
20174 (widen)
20175 (current-buffer)))
20176 files)
20177 regexp)))
20179 (if (boundp 'occur-mode-find-occurrence-hook)
20180 ;; Emacs 23
20181 (add-hook 'occur-mode-find-occurrence-hook
20182 (lambda ()
20183 (when (derived-mode-p 'org-mode)
20184 (org-reveal))))
20185 ;; Emacs 22
20186 (defadvice occur-mode-goto-occurrence
20187 (after org-occur-reveal activate)
20188 (and (derived-mode-p 'org-mode) (org-reveal)))
20189 (defadvice occur-mode-goto-occurrence-other-window
20190 (after org-occur-reveal activate)
20191 (and (derived-mode-p 'org-mode) (org-reveal)))
20192 (defadvice occur-mode-display-occurrence
20193 (after org-occur-reveal activate)
20194 (when (derived-mode-p 'org-mode)
20195 (let ((pos (occur-mode-find-occurrence)))
20196 (with-current-buffer (marker-buffer pos)
20197 (save-excursion
20198 (goto-char pos)
20199 (org-reveal)))))))
20201 (defun org-occur-link-in-agenda-files ()
20202 "Create a link and search for it in the agendas.
20203 The link is not stored in `org-stored-links', it is just created
20204 for the search purpose."
20205 (interactive)
20206 (let ((link (condition-case nil
20207 (org-store-link nil)
20208 (error "Unable to create a link to here"))))
20209 (org-occur-in-agenda-files (regexp-quote link))))
20211 (defun org-uniquify (list)
20212 "Remove duplicate elements from LIST."
20213 (let (res)
20214 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20215 res))
20217 (defun org-delete-all (elts list)
20218 "Remove all elements in ELTS from LIST."
20219 (while elts
20220 (setq list (delete (pop elts) list)))
20221 list)
20223 (defun org-count (cl-item cl-seq)
20224 "Count the number of occurrences of ITEM in SEQ.
20225 Taken from `count' in cl-seq.el with all keyword arguments removed."
20226 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20227 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20228 (while (< cl-start cl-end)
20229 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20230 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20231 (setq cl-start (1+ cl-start)))
20232 cl-count))
20234 (defun org-remove-if (predicate seq)
20235 "Remove everything from SEQ that fulfills PREDICATE."
20236 (let (res e)
20237 (while seq
20238 (setq e (pop seq))
20239 (if (not (funcall predicate e)) (push e res)))
20240 (nreverse res)))
20242 (defun org-remove-if-not (predicate seq)
20243 "Remove everything from SEQ that does not fulfill PREDICATE."
20244 (let (res e)
20245 (while seq
20246 (setq e (pop seq))
20247 (if (funcall predicate e) (push e res)))
20248 (nreverse res)))
20250 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20251 "Reduce two-argument FUNCTION across SEQ.
20252 Taken from `reduce' in cl-seq.el with all keyword arguments but
20253 \":initial-value\" removed."
20254 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20255 (cadr (memq :initial-value cl-keys)))
20256 (cl-seq (pop cl-seq))
20257 (t (funcall cl-func)))))
20258 (while cl-seq
20259 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20260 cl-accum))
20262 (defun org-back-over-empty-lines ()
20263 "Move backwards over whitespace, to the beginning of the first empty line.
20264 Returns the number of empty lines passed."
20265 (let ((pos (point)))
20266 (if (cdr (assoc 'heading org-blank-before-new-entry))
20267 (skip-chars-backward " \t\n\r")
20268 (unless (eobp)
20269 (forward-line -1)))
20270 (beginning-of-line 2)
20271 (goto-char (min (point) pos))
20272 (count-lines (point) pos)))
20274 (defun org-skip-whitespace ()
20275 (skip-chars-forward " \t\n\r"))
20277 (defun org-point-in-group (point group &optional context)
20278 "Check if POINT is in match-group GROUP.
20279 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20280 match. If the match group does not exist or point is not inside it,
20281 return nil."
20282 (and (match-beginning group)
20283 (>= point (match-beginning group))
20284 (<= point (match-end group))
20285 (if context
20286 (list context (match-beginning group) (match-end group))
20287 t)))
20289 (defun org-switch-to-buffer-other-window (&rest args)
20290 "Switch to buffer in a second window on the current frame.
20291 In particular, do not allow pop-up frames.
20292 Returns the newly created buffer."
20293 (let (pop-up-frames special-display-buffer-names special-display-regexps
20294 special-display-function)
20295 (apply 'switch-to-buffer-other-window args)))
20297 (defun org-combine-plists (&rest plists)
20298 "Create a single property list from all plists in PLISTS.
20299 The process starts by copying the first list, and then setting properties
20300 from the other lists. Settings in the last list are the most significant
20301 ones and overrule settings in the other lists."
20302 (let ((rtn (copy-sequence (pop plists)))
20303 p v ls)
20304 (while plists
20305 (setq ls (pop plists))
20306 (while ls
20307 (setq p (pop ls) v (pop ls))
20308 (setq rtn (plist-put rtn p v))))
20309 rtn))
20311 (defun org-move-line-down (arg)
20312 "Move the current line down. With prefix argument, move it past ARG lines."
20313 (interactive "p")
20314 (let ((col (current-column))
20315 beg end pos)
20316 (beginning-of-line 1) (setq beg (point))
20317 (beginning-of-line 2) (setq end (point))
20318 (beginning-of-line (+ 1 arg))
20319 (setq pos (move-marker (make-marker) (point)))
20320 (insert (delete-and-extract-region beg end))
20321 (goto-char pos)
20322 (org-move-to-column col)))
20324 (defun org-move-line-up (arg)
20325 "Move the current line up. With prefix argument, move it past ARG lines."
20326 (interactive "p")
20327 (let ((col (current-column))
20328 beg end pos)
20329 (beginning-of-line 1) (setq beg (point))
20330 (beginning-of-line 2) (setq end (point))
20331 (beginning-of-line (- arg))
20332 (setq pos (move-marker (make-marker) (point)))
20333 (insert (delete-and-extract-region beg end))
20334 (goto-char pos)
20335 (org-move-to-column col)))
20337 (defun org-replace-escapes (string table)
20338 "Replace %-escapes in STRING with values in TABLE.
20339 TABLE is an association list with keys like \"%a\" and string values.
20340 The sequences in STRING may contain normal field width and padding information,
20341 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20342 so values can contain further %-escapes if they are define later in TABLE."
20343 (let ((tbl (copy-alist table))
20344 (case-fold-search nil)
20345 (pchg 0)
20346 e re rpl)
20347 (while (setq e (pop tbl))
20348 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20349 (when (and (cdr e) (string-match re (cdr e)))
20350 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20351 (safe "SREF"))
20352 (add-text-properties 0 3 (list 'sref sref) safe)
20353 (setcdr e (replace-match safe t t (cdr e)))))
20354 (while (string-match re string)
20355 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20356 (cdr e)))
20357 (setq string (replace-match rpl t t string))))
20358 (while (setq pchg (next-property-change pchg string))
20359 (let ((sref (get-text-property pchg 'sref string)))
20360 (when (and sref (string-match "SREF" string pchg))
20361 (setq string (replace-match sref t t string)))))
20362 string))
20364 (defun org-sublist (list start end)
20365 "Return a section of LIST, from START to END.
20366 Counting starts at 1."
20367 (let (rtn (c start))
20368 (setq list (nthcdr (1- start) list))
20369 (while (and list (<= c end))
20370 (push (pop list) rtn)
20371 (setq c (1+ c)))
20372 (nreverse rtn)))
20374 (defun org-find-base-buffer-visiting (file)
20375 "Like `find-buffer-visiting' but always return the base buffer and
20376 not an indirect buffer."
20377 (let ((buf (or (get-file-buffer file)
20378 (find-buffer-visiting file))))
20379 (if buf
20380 (or (buffer-base-buffer buf) buf)
20381 nil)))
20383 (defun org-image-file-name-regexp (&optional extensions)
20384 "Return regexp matching the file names of images.
20385 If EXTENSIONS is given, only match these."
20386 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20387 (image-file-name-regexp)
20388 (let ((image-file-name-extensions
20389 (or extensions
20390 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20391 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20392 (concat "\\."
20393 (regexp-opt (nconc (mapcar 'upcase
20394 image-file-name-extensions)
20395 image-file-name-extensions)
20397 "\\'"))))
20399 (defun org-file-image-p (file &optional extensions)
20400 "Return non-nil if FILE is an image."
20401 (save-match-data
20402 (string-match (org-image-file-name-regexp extensions) file)))
20404 (defun org-get-cursor-date ()
20405 "Return the date at cursor in as a time.
20406 This works in the calendar and in the agenda, anywhere else it just
20407 returns the current time."
20408 (let (date day defd)
20409 (cond
20410 ((eq major-mode 'calendar-mode)
20411 (setq date (calendar-cursor-to-date)
20412 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20413 ((eq major-mode 'org-agenda-mode)
20414 (setq day (get-text-property (point) 'day))
20415 (if day
20416 (setq date (calendar-gregorian-from-absolute day)
20417 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20418 (nth 2 date))))))
20419 (or defd (current-time))))
20421 (defvar org-agenda-action-marker (make-marker)
20422 "Marker pointing to the entry for the next agenda action.")
20424 (defun org-mark-entry-for-agenda-action ()
20425 "Mark the current entry as target of an agenda action.
20426 Agenda actions are actions executed from the agenda with the key `k',
20427 which make use of the date at the cursor."
20428 (interactive)
20429 (move-marker org-agenda-action-marker
20430 (save-excursion (org-back-to-heading t) (point))
20431 (current-buffer))
20432 (message
20433 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20435 (defun org-mark-subtree ()
20436 "Mark the current subtree.
20437 This puts point at the start of the current subtree, and mark at the end.
20439 If point is in an inline task, mark that task instead."
20440 (interactive)
20441 (let ((inline-task-p
20442 (and (featurep 'org-inlinetask)
20443 (org-inlinetask-in-task-p)))
20444 (beg))
20445 ;; Get beginning of subtree
20446 (cond
20447 (inline-task-p (org-inlinetask-goto-beginning))
20448 ((org-at-heading-p) (beginning-of-line))
20449 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20450 (setq beg (point))
20451 ;; Get end of it
20452 (if inline-task-p
20453 (org-inlinetask-goto-end)
20454 (org-end-of-subtree))
20455 ;; Mark zone
20456 (push-mark (point) nil t)
20457 (goto-char beg)))
20459 ;;; Paragraph filling stuff.
20460 ;; We want this to be just right, so use the full arsenal.
20462 (defun org-indent-line-function ()
20463 "Indent line depending on context."
20464 (interactive)
20465 (let* ((pos (point))
20466 (itemp (org-at-item-p))
20467 (case-fold-search t)
20468 (org-drawer-regexp (or org-drawer-regexp "\000"))
20469 (inline-task-p (and (featurep 'org-inlinetask)
20470 (org-inlinetask-in-task-p)))
20471 (inline-re (and inline-task-p
20472 (org-inlinetask-outline-regexp)))
20473 column)
20474 (beginning-of-line 1)
20475 (cond
20476 ;; Comments
20477 ((looking-at "# ") (setq column 0))
20478 ;; Headings
20479 ((looking-at org-outline-regexp) (setq column 0))
20480 ;; Included files
20481 ((looking-at "#\\+include:") (setq column 0))
20482 ;; Footnote definition
20483 ((looking-at org-footnote-definition-re) (setq column 0))
20484 ;; Literal examples
20485 ((looking-at "[ \t]*:\\( \\|$\\)")
20486 (setq column (org-get-indentation))) ; do nothing
20487 ;; Lists
20488 ((ignore-errors (goto-char (org-in-item-p)))
20489 (setq column (if itemp
20490 (org-get-indentation)
20491 (org-list-item-body-column (point))))
20492 (goto-char pos))
20493 ;; Drawers
20494 ((and (looking-at "[ \t]*:END:")
20495 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20496 (save-excursion
20497 (goto-char (1- (match-beginning 1)))
20498 (setq column (current-column))))
20499 ;; Special blocks
20500 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20501 (save-excursion
20502 (re-search-backward
20503 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20504 (setq column (org-get-indentation (match-string 0))))
20505 ((and (not (looking-at "[ \t]*#\\+begin_"))
20506 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20507 (save-excursion
20508 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20509 (setq column
20510 (cond ((equal (downcase (match-string 1)) "src")
20511 ;; src blocks: let `org-edit-src-exit' handle them
20512 (org-get-indentation))
20513 ((equal (downcase (match-string 1)) "example")
20514 (max (org-get-indentation)
20515 (org-get-indentation (match-string 0))))
20517 (org-get-indentation (match-string 0))))))
20518 ;; This line has nothing special, look at the previous relevant
20519 ;; line to compute indentation
20521 (beginning-of-line 0)
20522 (while (and (not (bobp))
20523 (not (looking-at org-drawer-regexp))
20524 ;; When point started in an inline task, do not move
20525 ;; above task starting line.
20526 (not (and inline-task-p (looking-at inline-re)))
20527 ;; Skip drawers, blocks, empty lines, verbatim,
20528 ;; comments, tables, footnotes definitions, lists,
20529 ;; inline tasks.
20530 (or (and (looking-at "[ \t]*:END:")
20531 (re-search-backward org-drawer-regexp nil t))
20532 (and (looking-at "[ \t]*#\\+end_")
20533 (re-search-backward "[ \t]*#\\+begin_"nil t))
20534 (looking-at "[ \t]*[\n:#|]")
20535 (looking-at org-footnote-definition-re)
20536 (and (ignore-errors (goto-char (org-in-item-p)))
20537 (goto-char
20538 (org-list-get-top-point (org-list-struct))))
20539 (and (not inline-task-p)
20540 (featurep 'org-inlinetask)
20541 (org-inlinetask-in-task-p)
20542 (or (org-inlinetask-goto-beginning) t))))
20543 (beginning-of-line 0))
20544 (cond
20545 ;; There was an heading above.
20546 ((looking-at "\\*+[ \t]+")
20547 (if (not org-adapt-indentation)
20548 (setq column 0)
20549 (goto-char (match-end 0))
20550 (setq column (current-column))))
20551 ;; A drawer had started and is unfinished
20552 ((looking-at org-drawer-regexp)
20553 (goto-char (1- (match-beginning 1)))
20554 (setq column (current-column)))
20555 ;; Else, nothing noticeable found: get indentation and go on.
20556 (t (setq column (org-get-indentation))))))
20557 ;; Now apply indentation and move cursor accordingly
20558 (goto-char pos)
20559 (if (<= (current-column) (current-indentation))
20560 (org-indent-line-to column)
20561 (save-excursion (org-indent-line-to column)))
20562 ;; Special polishing for properties, see `org-property-format'
20563 (setq column (current-column))
20564 (beginning-of-line 1)
20565 (if (looking-at
20566 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20567 (replace-match (concat (match-string 1)
20568 (format org-property-format
20569 (match-string 2) (match-string 3)))
20570 t t))
20571 (org-move-to-column column)
20572 (when (and orgstruct-is-++ (eq pos (point)))
20573 (org-let org-fb-vars
20574 '(indent-according-to-mode)))))
20576 (defun org-indent-drawer ()
20577 "Indent the drawer at point."
20578 (interactive)
20579 (let ((p (point))
20580 (e (and (save-excursion (re-search-forward ":END:" nil t))
20581 (match-end 0)))
20582 (folded
20583 (save-excursion
20584 (end-of-line)
20585 (when (overlays-at (point))
20586 (member 'invisible (overlay-properties
20587 (car (overlays-at (point)))))))))
20588 (when folded (org-cycle))
20589 (indent-for-tab-command)
20590 (while (and (move-beginning-of-line 2) (< (point) e))
20591 (indent-for-tab-command))
20592 (goto-char p)
20593 (when folded (org-cycle)))
20594 (message "Drawer at point indented"))
20596 (defun org-indent-block ()
20597 "Indent the block at point."
20598 (interactive)
20599 (let ((p (point))
20600 (case-fold-search t)
20601 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20602 (match-end 0)))
20603 (folded
20604 (save-excursion
20605 (end-of-line)
20606 (when (overlays-at (point))
20607 (member 'invisible (overlay-properties
20608 (car (overlays-at (point)))))))))
20609 (when folded (org-cycle))
20610 (indent-for-tab-command)
20611 (while (and (move-beginning-of-line 2) (< (point) e))
20612 (indent-for-tab-command))
20613 (goto-char p)
20614 (when folded (org-cycle)))
20615 (message "Block at point indented"))
20617 ;; For reference, this is the default value of adaptive-fill-regexp
20618 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20619 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20620 "Variable to store copy of `adaptive-fill-regexp'.
20621 Since `adaptive-fill-regexp' is set to never match, we need to
20622 store a backup of its value before entering `org-mode' so that
20623 the functionality can be provided as a fall-back.")
20625 (defun org-set-autofill-regexps ()
20626 (interactive)
20627 ;; In the paragraph separator we include headlines, because filling
20628 ;; text in a line directly attached to a headline would otherwise
20629 ;; fill the headline as well.
20630 (org-set-local 'comment-start-skip "^#+[ \t]*")
20631 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20632 ;; The paragraph starter includes hand-formatted lists.
20633 (org-set-local
20634 'paragraph-start
20635 (concat
20636 "\f" "\\|"
20637 "[ ]*$" "\\|"
20638 org-outline-regexp "\\|"
20639 "[ \t]*#" "\\|"
20640 (org-item-re) "\\|"
20641 "[ \t]*[:|]" "\\|"
20642 "\\$\\$" "\\|"
20643 "\\\\\\(begin\\|end\\|[][]\\)"))
20644 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20645 ;; But only if the user has not turned off tables or fixed-width regions
20646 (org-set-local
20647 'auto-fill-inhibit-regexp
20648 (concat org-outline-regexp
20649 "\\|#\\+"
20650 "\\|[ \t]*" org-keyword-time-regexp
20651 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20652 (concat
20653 "\\|[ \t]*["
20654 (if org-enable-table-editor "|" "")
20655 (if org-enable-fixed-width-editor ":" "")
20656 "]"))))
20657 ;; We use our own fill-paragraph function, to make sure that tables
20658 ;; and fixed-width regions are not wrapped. That function will pass
20659 ;; through to `fill-paragraph' when appropriate.
20660 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20661 ;; Prevent auto-fill from inserting unwanted new items.
20662 (if (boundp 'fill-nobreak-predicate)
20663 (org-set-local
20664 'fill-nobreak-predicate
20665 (org-uniquify
20666 (append fill-nobreak-predicate
20667 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20668 ;; Adaptive filling: To get full control, first make sure that
20669 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20670 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20671 (org-set-local 'org-adaptive-fill-regexp-backup
20672 adaptive-fill-regexp))
20673 (org-set-local 'adaptive-fill-regexp "\000")
20674 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20675 (org-set-local 'adaptive-fill-function
20676 'org-adaptive-fill-function)
20677 (org-set-local
20678 'align-mode-rules-list
20679 '((org-in-buffer-settings
20680 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20681 (modes . '(org-mode))))))
20683 (defun org-fill-item-nobreak-p ()
20684 "Non-nil when a line break at point would insert a new item."
20685 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20687 (defun org-fill-line-break-nobreak-p ()
20688 "Non-nil when a line break at point would create an Org line break."
20689 (save-excursion
20690 (skip-chars-backward "[ \t]")
20691 (skip-chars-backward "\\\\")
20692 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20694 (defun org-fill-paragraph (&optional justify)
20695 "Re-align a table, pass through to fill-paragraph if no table."
20696 (let ((table-p (org-at-table-p))
20697 (table.el-p (org-at-table.el-p))
20698 (itemp (org-in-item-p)))
20699 (cond ((and (equal (char-after (point-at-bol)) ?*)
20700 (save-excursion (goto-char (point-at-bol))
20701 (looking-at org-outline-regexp)))
20702 t) ; skip headlines
20703 (table.el-p t) ; skip table.el tables
20704 (table-p (org-table-align) t) ; align Org tables
20705 (itemp ; align text in items
20706 (let* ((struct (save-excursion (goto-char itemp)
20707 (org-list-struct)))
20708 (parents (org-list-parents-alist struct))
20709 (children (org-list-get-children itemp struct parents))
20710 beg end prev next prefix)
20711 ;; Determine in which part of item point is: before
20712 ;; first child, after last child, between two
20713 ;; sub-lists, or simply in item if there's no child.
20714 (cond
20715 ((not children)
20716 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20717 beg itemp
20718 end (org-list-get-item-end itemp struct)))
20719 ((< (point) (setq next (car children)))
20720 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20721 beg itemp
20722 end next))
20723 ((> (point) (setq prev (car (last children))))
20724 (setq beg (org-list-get-item-end prev struct)
20725 end (org-list-get-item-end itemp struct)
20726 prefix (save-excursion
20727 (goto-char beg)
20728 (skip-chars-forward " \t")
20729 (make-string (current-column) ?\ ))))
20730 (t (catch 'exit
20731 (while (setq next (pop children))
20732 (if (> (point) next)
20733 (setq prev next)
20734 (setq beg (org-list-get-item-end prev struct)
20735 end next
20736 prefix (save-excursion
20737 (goto-char beg)
20738 (skip-chars-forward " \t")
20739 (make-string (current-column) ?\ )))
20740 (throw 'exit nil))))))
20741 ;; Use `fill-paragraph' with buffer narrowed to item
20742 ;; without any child, and with our computed PREFIX.
20743 (flet ((fill-context-prefix (from to &optional flr) prefix))
20744 (save-restriction
20745 (narrow-to-region beg end)
20746 (save-excursion (fill-paragraph justify)))) t))
20747 ;; Special case where point is not in a list but is on
20748 ;; a paragraph adjacent to a list: make sure this paragraph
20749 ;; doesn't get merged with the end of the list by narrowing
20750 ;; buffer first.
20751 ((and (derived-mode-p 'org-mode)
20752 (save-excursion (forward-paragraph -1)
20753 (setq itemp (org-in-item-p))))
20754 (let ((struct (save-excursion (goto-char itemp)
20755 (org-list-struct))))
20756 (save-restriction
20757 (narrow-to-region (org-list-get-bottom-point struct)
20758 (save-excursion (forward-paragraph 1)
20759 (point)))
20760 (fill-paragraph justify) t)))
20761 ;; Don't fill schedule/deadline line before a paragraph
20762 ;; This only makes sense in real org-mode buffers
20763 ((and (eq major-mode 'org-mode)
20764 (save-excursion (forward-paragraph -1)
20765 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20766 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20767 (save-restriction
20768 (narrow-to-region (1+ (match-end 0))
20769 (save-excursion (forward-paragraph 1) (point)))
20770 (fill-paragraph justify) t))
20771 ;; Else fall back on fill-paragraph-function as possibly
20772 ;; defined in `org-fb-vars'
20773 (orgstruct-is-++
20774 (org-let org-fb-vars
20775 '(fill-paragraph justify)))
20776 (t nil))))
20778 (defun org-adaptive-fill-function ()
20779 "Return a fill prefix for org-mode files."
20780 (let (itemp)
20781 (save-excursion
20782 (cond
20783 ;; Comment line
20784 ((looking-at "#[ \t]+")
20785 (match-string-no-properties 0))
20786 ;; Plain list item
20787 ((org-at-item-p)
20788 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20789 ;; Point is in a list after `backward-paragraph': original
20790 ;; point wasn't in the list, or filling would have been taken
20791 ;; care of by `org-auto-fill-function', but the list and the
20792 ;; real paragraph are not separated by a blank line. Thus, move
20793 ;; point after the list to go back to real paragraph and
20794 ;; determine fill-prefix.
20795 ((setq itemp (org-in-item-p))
20796 (goto-char itemp)
20797 (let* ((struct (org-list-struct))
20798 (bottom (org-list-get-bottom-point struct)))
20799 (goto-char bottom)
20800 (make-string (org-get-indentation) ?\ )))
20801 ;; Other text
20802 ((looking-at org-adaptive-fill-regexp-backup)
20803 (match-string-no-properties 0))))))
20805 (defun org-auto-fill-function ()
20806 "Auto-fill function."
20807 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20808 (let (itemp prefix)
20809 ;; When in a list, compute an appropriate fill-prefix and make
20810 ;; sure it will be used by `do-auto-fill'.
20811 (cond ((setq itemp (org-in-item-p))
20812 (progn
20813 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20814 (flet ((fill-context-prefix (from to &optional flr) prefix))
20815 (do-auto-fill))))
20816 (orgstruct-is-++
20817 (org-let org-fb-vars
20818 '(do-auto-fill)))
20819 (t (do-auto-fill))))))
20821 ;;; Other stuff.
20823 (defun org-toggle-fixed-width-section (arg)
20824 "Toggle the fixed-width export.
20825 If there is no active region, the QUOTE keyword at the current headline is
20826 inserted or removed. When present, it causes the text between this headline
20827 and the next to be exported as fixed-width text, and unmodified.
20828 If there is an active region, this command adds or removes a colon as the
20829 first character of this line. If the first character of a line is a colon,
20830 this line is also exported in fixed-width font."
20831 (interactive "P")
20832 (let* ((cc 0)
20833 (regionp (org-region-active-p))
20834 (beg (if regionp (region-beginning) (point)))
20835 (end (if regionp (region-end)))
20836 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20837 (case-fold-search nil)
20838 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20839 off)
20840 (if regionp
20841 (save-excursion
20842 (goto-char beg)
20843 (setq cc (current-column))
20844 (beginning-of-line 1)
20845 (setq off (looking-at re))
20846 (while (> nlines 0)
20847 (setq nlines (1- nlines))
20848 (beginning-of-line 1)
20849 (cond
20850 (arg
20851 (org-move-to-column cc t)
20852 (insert ": \n")
20853 (forward-line -1))
20854 ((and off (looking-at re))
20855 (replace-match "" t t nil 1))
20856 ((not off) (org-move-to-column cc t) (insert ": ")))
20857 (forward-line 1)))
20858 (save-excursion
20859 (org-back-to-heading)
20860 (cond
20861 ((looking-at (format org-heading-keyword-regexp-format
20862 org-quote-string))
20863 (goto-char (match-end 1))
20864 (looking-at (concat " +" org-quote-string))
20865 (replace-match "" t t)
20866 (when (eolp) (insert " ")))
20867 ((looking-at org-outline-regexp)
20868 (goto-char (match-end 0))
20869 (insert org-quote-string " ")))))))
20871 (defun org-reftex-citation ()
20872 "Use reftex-citation to insert a citation into the buffer.
20873 This looks for a line like
20875 #+BIBLIOGRAPHY: foo plain option:-d
20877 and derives from it that foo.bib is the bibliography file relevant
20878 for this document. It then installs the necessary environment for RefTeX
20879 to work in this buffer and calls `reftex-citation' to insert a citation
20880 into the buffer.
20882 Export of such citations to both LaTeX and HTML is handled by the contributed
20883 package org-exp-bibtex by Taru Karttunen."
20884 (interactive)
20885 (let ((reftex-docstruct-symbol 'rds)
20886 (reftex-cite-format "\\cite{%l}")
20887 rds bib)
20888 (save-excursion
20889 (save-restriction
20890 (widen)
20891 (let ((case-fold-search t)
20892 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20893 (if (not (save-excursion
20894 (or (re-search-forward re nil t)
20895 (re-search-backward re nil t))))
20896 (error "No bibliography defined in file")
20897 (setq bib (concat (match-string 1) ".bib")
20898 rds (list (list 'bib bib)))))))
20899 (call-interactively 'reftex-citation)))
20901 ;;;; Functions extending outline functionality
20903 (defun org-beginning-of-line (&optional arg)
20904 "Go to the beginning of the current line. If that is invisible, continue
20905 to a visible line beginning. This makes the function of C-a more intuitive.
20906 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20907 first attempt, and only move to after the tags when the cursor is already
20908 beyond the end of the headline."
20909 (interactive "P")
20910 (let ((pos (point))
20911 (special (if (consp org-special-ctrl-a/e)
20912 (car org-special-ctrl-a/e)
20913 org-special-ctrl-a/e))
20914 refpos)
20915 (if (org-bound-and-true-p line-move-visual)
20916 (beginning-of-visual-line 1)
20917 (beginning-of-line 1))
20918 (if (and arg (fboundp 'move-beginning-of-line))
20919 (call-interactively 'move-beginning-of-line)
20920 (if (bobp)
20922 (backward-char 1)
20923 (if (org-truely-invisible-p)
20924 (while (and (not (bobp)) (org-truely-invisible-p))
20925 (backward-char 1)
20926 (beginning-of-line 1))
20927 (forward-char 1))))
20928 (when special
20929 (cond
20930 ((and (looking-at org-complex-heading-regexp)
20931 (= (char-after (match-end 1)) ?\ ))
20932 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20933 (point-at-eol)))
20934 (goto-char
20935 (if (eq special t)
20936 (cond ((> pos refpos) refpos)
20937 ((= pos (point)) refpos)
20938 (t (point)))
20939 (cond ((> pos (point)) (point))
20940 ((not (eq last-command this-command)) (point))
20941 (t refpos)))))
20942 ((org-at-item-p)
20943 ;; Being at an item and not looking at an the item means point
20944 ;; was previously moved to beginning of a visual line, which
20945 ;; doesn't contain the item. Therefore, do nothing special,
20946 ;; just stay here.
20947 (when (looking-at org-list-full-item-re)
20948 ;; Set special position at first white space character after
20949 ;; bullet, and check-box, if any.
20950 (let ((after-bullet
20951 (let ((box (match-end 3)))
20952 (if (not box) (match-end 1)
20953 (let ((after (char-after box)))
20954 (if (and after (= after ? )) (1+ box) box))))))
20955 ;; Special case: Move point to special position when
20956 ;; currently after it or at beginning of line.
20957 (if (eq special t)
20958 (when (or (> pos after-bullet) (= (point) pos))
20959 (goto-char after-bullet))
20960 ;; Reversed case: Move point to special position when
20961 ;; point was already at beginning of line and command is
20962 ;; repeated.
20963 (when (and (= (point) pos) (eq last-command this-command))
20964 (goto-char after-bullet))))))))
20965 (org-no-warnings
20966 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20968 (defun org-end-of-line (&optional arg)
20969 "Go to the end of the line.
20970 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20971 first attempt, and only move to after the tags when the cursor is already
20972 beyond the end of the headline."
20973 (interactive "P")
20974 (let ((special (if (consp org-special-ctrl-a/e)
20975 (cdr org-special-ctrl-a/e)
20976 org-special-ctrl-a/e)))
20977 (cond
20978 ((or (not special) arg
20979 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20980 (call-interactively
20981 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20982 ((fboundp 'move-end-of-line) 'move-end-of-line)
20983 (t 'end-of-line))))
20984 ((org-at-heading-p)
20985 (let ((pos (point)))
20986 (beginning-of-line 1)
20987 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20988 (if (eq special t)
20989 (if (or (< pos (match-beginning 1))
20990 (= pos (match-end 0)))
20991 (goto-char (match-beginning 1))
20992 (goto-char (match-end 0)))
20993 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20994 (goto-char (match-end 0))
20995 (goto-char (match-beginning 1))))
20996 (call-interactively (if (fboundp 'move-end-of-line)
20997 'move-end-of-line
20998 'end-of-line)))))
20999 ((org-at-drawer-p)
21000 (move-end-of-line 1)
21001 (when (overlays-at (1- (point))) (backward-char 1)))
21002 ;; At an item: Move before any hidden text.
21003 (t (call-interactively
21004 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21005 ((fboundp 'move-end-of-line) 'move-end-of-line)
21006 (t 'end-of-line)))))
21007 (org-no-warnings
21008 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21010 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21011 (define-key org-mode-map "\C-e" 'org-end-of-line)
21013 (defun org-backward-sentence (&optional arg)
21014 "Go to beginning of sentence, or beginning of table field.
21015 This will call `backward-sentence' or `org-table-beginning-of-field',
21016 depending on context."
21017 (interactive "P")
21018 (cond
21019 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21020 (t (call-interactively 'backward-sentence))))
21022 (defun org-forward-sentence (&optional arg)
21023 "Go to end of sentence, or end of table field.
21024 This will call `forward-sentence' or `org-table-end-of-field',
21025 depending on context."
21026 (interactive "P")
21027 (cond
21028 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21029 (t (call-interactively 'forward-sentence))))
21031 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21032 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21034 (defun org-kill-line (&optional arg)
21035 "Kill line, to tags or end of line."
21036 (interactive "P")
21037 (cond
21038 ((or (not org-special-ctrl-k)
21039 (bolp)
21040 (not (org-at-heading-p)))
21041 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21042 org-ctrl-k-protect-subtree)
21043 (if (or (eq org-ctrl-k-protect-subtree 'error)
21044 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21045 (error "C-k aborted - would kill hidden subtree")))
21046 (call-interactively
21047 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21048 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21049 (kill-region (point) (match-beginning 1))
21050 (org-set-tags nil t))
21051 (t (kill-region (point) (point-at-eol)))))
21053 (define-key org-mode-map "\C-k" 'org-kill-line)
21055 (defun org-yank (&optional arg)
21056 "Yank. If the kill is a subtree, treat it specially.
21057 This command will look at the current kill and check if is a single
21058 subtree, or a series of subtrees[1]. If it passes the test, and if the
21059 cursor is at the beginning of a line or after the stars of a currently
21060 empty headline, then the yank is handled specially. How exactly depends
21061 on the value of the following variables, both set by default.
21063 org-yank-folded-subtrees
21064 When set, the subtree(s) will be folded after insertion, but only
21065 if doing so would now swallow text after the yanked text.
21067 org-yank-adjusted-subtrees
21068 When set, the subtree will be promoted or demoted in order to
21069 fit into the local outline tree structure, which means that the level
21070 will be adjusted so that it becomes the smaller one of the two
21071 *visible* surrounding headings.
21073 Any prefix to this command will cause `yank' to be called directly with
21074 no special treatment. In particular, a simple \\[universal-argument] prefix \
21075 will just
21076 plainly yank the text as it is.
21078 \[1] The test checks if the first non-white line is a heading
21079 and if there are no other headings with fewer stars."
21080 (interactive "P")
21081 (org-yank-generic 'yank arg))
21083 (defun org-yank-generic (command arg)
21084 "Perform some yank-like command.
21086 This function implements the behavior described in the `org-yank'
21087 documentation. However, it has been generalized to work for any
21088 interactive command with similar behavior."
21090 ;; pretend to be command COMMAND
21091 (setq this-command command)
21093 (if arg
21094 (call-interactively command)
21096 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21097 (and (org-kill-is-subtree-p)
21098 (or (bolp)
21099 (and (looking-at "[ \t]*$")
21100 (string-match
21101 "\\`\\*+\\'"
21102 (buffer-substring (point-at-bol) (point)))))))
21103 swallowp)
21104 (cond
21105 ((and subtreep org-yank-folded-subtrees)
21106 (let ((beg (point))
21107 end)
21108 (if (and subtreep org-yank-adjusted-subtrees)
21109 (org-paste-subtree nil nil 'for-yank)
21110 (call-interactively command))
21112 (setq end (point))
21113 (goto-char beg)
21114 (when (and (bolp) subtreep
21115 (not (setq swallowp
21116 (org-yank-folding-would-swallow-text beg end))))
21117 (org-with-limited-levels
21118 (or (looking-at org-outline-regexp)
21119 (re-search-forward org-outline-regexp-bol end t))
21120 (while (and (< (point) end) (looking-at org-outline-regexp))
21121 (hide-subtree)
21122 (org-cycle-show-empty-lines 'folded)
21123 (condition-case nil
21124 (outline-forward-same-level 1)
21125 (error (goto-char end))))))
21126 (when swallowp
21127 (message
21128 "Inserted text not folded because that would swallow text"))
21130 (goto-char end)
21131 (skip-chars-forward " \t\n\r")
21132 (beginning-of-line 1)
21133 (push-mark beg 'nomsg)))
21134 ((and subtreep org-yank-adjusted-subtrees)
21135 (let ((beg (point-at-bol)))
21136 (org-paste-subtree nil nil 'for-yank)
21137 (push-mark beg 'nomsg)))
21139 (call-interactively command))))))
21141 (defun org-yank-folding-would-swallow-text (beg end)
21142 "Would hide-subtree at BEG swallow any text after END?"
21143 (let (level)
21144 (org-with-limited-levels
21145 (save-excursion
21146 (goto-char beg)
21147 (when (or (looking-at org-outline-regexp)
21148 (re-search-forward org-outline-regexp-bol end t))
21149 (setq level (org-outline-level)))
21150 (goto-char end)
21151 (skip-chars-forward " \t\r\n\v\f")
21152 (if (or (eobp)
21153 (and (bolp) (looking-at org-outline-regexp)
21154 (<= (org-outline-level) level)))
21155 nil ; Nothing would be swallowed
21156 t))))) ; something would swallow
21158 (define-key org-mode-map "\C-y" 'org-yank)
21160 (defun org-truely-invisible-p ()
21161 "Check if point is at a character currently not visible.
21162 This version does not only check the character property, but also
21163 `visible-mode'."
21164 ;; Early versions of noutline don't have `outline-invisible-p'.
21165 (if (org-bound-and-true-p visible-mode)
21167 (outline-invisible-p)))
21169 (defun org-invisible-p2 ()
21170 "Check if point is at a character currently not visible."
21171 (save-excursion
21172 (if (and (eolp) (not (bobp))) (backward-char 1))
21173 ;; Early versions of noutline don't have `outline-invisible-p'.
21174 (outline-invisible-p)))
21176 (defun org-back-to-heading (&optional invisible-ok)
21177 "Call `outline-back-to-heading', but provide a better error message."
21178 (condition-case nil
21179 (outline-back-to-heading invisible-ok)
21180 (error (error "Before first headline at position %d in buffer %s"
21181 (point) (current-buffer)))))
21183 (defun org-beginning-of-defun ()
21184 "Go to the beginning of the subtree, i.e. back to the heading."
21185 (org-back-to-heading))
21186 (defun org-end-of-defun ()
21187 "Go to the end of the subtree."
21188 (org-end-of-subtree nil t))
21190 (defun org-before-first-heading-p ()
21191 "Before first heading?"
21192 (save-excursion
21193 (end-of-line)
21194 (null (re-search-backward org-outline-regexp-bol nil t))))
21196 (defun org-at-heading-p (&optional ignored)
21197 (outline-on-heading-p t))
21198 ;; Compatibility alias with Org versions < 7.8.03
21199 (defalias 'org-on-heading-p 'org-at-heading-p)
21201 (defun org-at-drawer-p nil
21202 "Is cursor at a drawer keyword?"
21203 (save-excursion
21204 (move-beginning-of-line 1)
21205 (looking-at org-drawer-regexp)))
21207 (defun org-at-block-p nil
21208 "Is cursor at a block keyword?"
21209 (save-excursion
21210 (move-beginning-of-line 1)
21211 (looking-at org-block-regexp)))
21213 (defun org-point-at-end-of-empty-headline ()
21214 "If point is at the end of an empty headline, return t, else nil.
21215 If the heading only contains a TODO keyword, it is still still considered
21216 empty."
21217 (and (looking-at "[ \t]*$")
21218 (when org-todo-line-regexp
21219 (save-excursion
21220 (beginning-of-line 1)
21221 (let ((case-fold-search nil))
21222 (looking-at org-todo-line-regexp)
21223 (string= (match-string 3) ""))))))
21225 (defun org-at-heading-or-item-p ()
21226 (or (org-at-heading-p) (org-at-item-p)))
21228 (defun org-at-target-p ()
21229 (or (org-in-regexp org-radio-target-regexp)
21230 (org-in-regexp org-target-regexp)))
21231 ;; Compatibility alias with Org versions < 7.8.03
21232 (defalias 'org-on-target-p 'org-at-target-p)
21234 (defun org-up-heading-all (arg)
21235 "Move to the heading line of which the present line is a subheading.
21236 This function considers both visible and invisible heading lines.
21237 With argument, move up ARG levels."
21238 (if (fboundp 'outline-up-heading-all)
21239 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21240 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21242 (defun org-up-heading-safe ()
21243 "Move to the heading line of which the present line is a subheading.
21244 This version will not throw an error. It will return the level of the
21245 headline found, or nil if no higher level is found.
21247 Also, this function will be a lot faster than `outline-up-heading',
21248 because it relies on stars being the outline starters. This can really
21249 make a significant difference in outlines with very many siblings."
21250 (let (start-level re)
21251 (org-back-to-heading t)
21252 (setq start-level (funcall outline-level))
21253 (if (equal start-level 1)
21255 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21256 (if (re-search-backward re nil t)
21257 (funcall outline-level)))))
21259 (defun org-first-sibling-p ()
21260 "Is this heading the first child of its parents?"
21261 (interactive)
21262 (let ((re org-outline-regexp-bol)
21263 level l)
21264 (unless (org-at-heading-p t)
21265 (error "Not at a heading"))
21266 (setq level (funcall outline-level))
21267 (save-excursion
21268 (if (not (re-search-backward re nil t))
21270 (setq l (funcall outline-level))
21271 (< l level)))))
21273 (defun org-goto-sibling (&optional previous)
21274 "Goto the next sibling, even if it is invisible.
21275 When PREVIOUS is set, go to the previous sibling instead. Returns t
21276 when a sibling was found. When none is found, return nil and don't
21277 move point."
21278 (let ((fun (if previous 're-search-backward 're-search-forward))
21279 (pos (point))
21280 (re org-outline-regexp-bol)
21281 level l)
21282 (when (condition-case nil (org-back-to-heading t) (error nil))
21283 (setq level (funcall outline-level))
21284 (catch 'exit
21285 (or previous (forward-char 1))
21286 (while (funcall fun re nil t)
21287 (setq l (funcall outline-level))
21288 (when (< l level) (goto-char pos) (throw 'exit nil))
21289 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21290 (goto-char pos)
21291 nil))))
21293 (defun org-show-siblings ()
21294 "Show all siblings of the current headline."
21295 (save-excursion
21296 (while (org-goto-sibling) (org-flag-heading nil)))
21297 (save-excursion
21298 (while (org-goto-sibling 'previous)
21299 (org-flag-heading nil))))
21301 (defun org-goto-first-child ()
21302 "Goto the first child, even if it is invisible.
21303 Return t when a child was found. Otherwise don't move point and
21304 return nil."
21305 (let (level (pos (point)) (re org-outline-regexp-bol))
21306 (when (condition-case nil (org-back-to-heading t) (error nil))
21307 (setq level (outline-level))
21308 (forward-char 1)
21309 (if (and (re-search-forward re nil t) (> (outline-level) level))
21310 (progn (goto-char (match-beginning 0)) t)
21311 (goto-char pos) nil))))
21313 (defun org-show-hidden-entry ()
21314 "Show an entry where even the heading is hidden."
21315 (save-excursion
21316 (org-show-entry)))
21318 (defun org-flag-heading (flag &optional entry)
21319 "Flag the current heading. FLAG non-nil means make invisible.
21320 When ENTRY is non-nil, show the entire entry."
21321 (save-excursion
21322 (org-back-to-heading t)
21323 ;; Check if we should show the entire entry
21324 (if entry
21325 (progn
21326 (org-show-entry)
21327 (save-excursion
21328 (and (outline-next-heading)
21329 (org-flag-heading nil))))
21330 (outline-flag-region (max (point-min) (1- (point)))
21331 (save-excursion (outline-end-of-heading) (point))
21332 flag))))
21334 (defun org-get-next-sibling ()
21335 "Move to next heading of the same level, and return point.
21336 If there is no such heading, return nil.
21337 This is like outline-next-sibling, but invisible headings are ok."
21338 (let ((level (funcall outline-level)))
21339 (outline-next-heading)
21340 (while (and (not (eobp)) (> (funcall outline-level) level))
21341 (outline-next-heading))
21342 (if (or (eobp) (< (funcall outline-level) level))
21344 (point))))
21346 (defun org-get-last-sibling ()
21347 "Move to previous heading of the same level, and return point.
21348 If there is no such heading, return nil."
21349 (let ((opoint (point))
21350 (level (funcall outline-level)))
21351 (outline-previous-heading)
21352 (when (and (/= (point) opoint) (outline-on-heading-p t))
21353 (while (and (> (funcall outline-level) level)
21354 (not (bobp)))
21355 (outline-previous-heading))
21356 (if (< (funcall outline-level) level)
21358 (point)))))
21360 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21361 ;; This contains an exact copy of the original function, but it uses
21362 ;; `org-back-to-heading', to make it work also in invisible
21363 ;; trees. And is uses an invisible-OK argument.
21364 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21365 ;; Furthermore, when used inside Org, finding the end of a large subtree
21366 ;; with many children and grandchildren etc, this can be much faster
21367 ;; than the outline version.
21368 (org-back-to-heading invisible-OK)
21369 (let ((first t)
21370 (level (funcall outline-level)))
21371 (if (and (derived-mode-p 'org-mode) (< level 1000))
21372 ;; A true heading (not a plain list item), in Org-mode
21373 ;; This means we can easily find the end by looking
21374 ;; only for the right number of stars. Using a regexp to do
21375 ;; this is so much faster than using a Lisp loop.
21376 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21377 (forward-char 1)
21378 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21379 ;; something else, do it the slow way
21380 (while (and (not (eobp))
21381 (or first (> (funcall outline-level) level)))
21382 (setq first nil)
21383 (outline-next-heading)))
21384 (unless to-heading
21385 (if (memq (preceding-char) '(?\n ?\^M))
21386 (progn
21387 ;; Go to end of line before heading
21388 (forward-char -1)
21389 (if (memq (preceding-char) '(?\n ?\^M))
21390 ;; leave blank line before heading
21391 (forward-char -1))))))
21392 (point))
21394 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21395 "Use Org version in org-mode, for dramatic speed-up."
21396 (if (derived-mode-p 'org-mode)
21397 (progn
21398 (org-end-of-subtree nil t)
21399 (unless (eobp) (backward-char 1)))
21400 ad-do-it))
21402 (defun org-end-of-meta-data-and-drawers ()
21403 "Jump to the first text after meta data and drawers in the current entry.
21404 This will move over empty lines, lines with planning time stamps,
21405 clocking lines, and drawers."
21406 (org-back-to-heading t)
21407 (let ((end (save-excursion (outline-next-heading) (point)))
21408 (re (concat "\\(" org-drawer-regexp "\\)"
21409 "\\|" "[ \t]*" org-keyword-time-regexp)))
21410 (forward-line 1)
21411 (while (re-search-forward re end t)
21412 (if (not (match-end 1))
21413 ;; empty or planning line
21414 (forward-line 1)
21415 ;; a drawer, find the end
21416 (re-search-forward "^[ \t]*:END:" end 'move)
21417 (forward-line 1)))
21418 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21419 (point)))
21421 (defun org-forward-same-level (arg &optional invisible-ok)
21422 "Move forward to the arg'th subheading at same level as this one.
21423 Stop at the first and last subheadings of a superior heading.
21424 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21425 it wil also look at invisible ones."
21426 (interactive "p")
21427 (org-back-to-heading invisible-ok)
21428 (org-at-heading-p)
21429 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21430 (re (format "^\\*\\{1,%d\\} " level))
21432 (forward-char 1)
21433 (while (> arg 0)
21434 (while (and (re-search-forward re nil 'move)
21435 (setq l (- (match-end 0) (match-beginning 0) 1))
21436 (= l level)
21437 (not invisible-ok)
21438 (progn (backward-char 1) (outline-invisible-p)))
21439 (if (< l level) (setq arg 1)))
21440 (setq arg (1- arg)))
21441 (beginning-of-line 1)))
21443 (defun org-backward-same-level (arg &optional invisible-ok)
21444 "Move backward to the arg'th subheading at same level as this one.
21445 Stop at the first and last subheadings of a superior heading."
21446 (interactive "p")
21447 (org-back-to-heading)
21448 (org-at-heading-p)
21449 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21450 (re (format "^\\*\\{1,%d\\} " level))
21452 (while (> arg 0)
21453 (while (and (re-search-backward re nil 'move)
21454 (setq l (- (match-end 0) (match-beginning 0) 1))
21455 (= l level)
21456 (not invisible-ok)
21457 (outline-invisible-p))
21458 (if (< l level) (setq arg 1)))
21459 (setq arg (1- arg)))))
21461 (defun org-show-subtree ()
21462 "Show everything after this heading at deeper levels."
21463 (interactive)
21464 (outline-flag-region
21465 (point)
21466 (save-excursion
21467 (org-end-of-subtree t t))
21468 nil))
21470 (defun org-show-entry ()
21471 "Show the body directly following this heading.
21472 Show the heading too, if it is currently invisible."
21473 (interactive)
21474 (save-excursion
21475 (condition-case nil
21476 (progn
21477 (org-back-to-heading t)
21478 (outline-flag-region
21479 (max (point-min) (1- (point)))
21480 (save-excursion
21481 (if (re-search-forward
21482 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21483 (match-beginning 1)
21484 (point-max)))
21485 nil)
21486 (org-cycle-hide-drawers 'children))
21487 (error nil))))
21489 (defun org-make-options-regexp (kwds &optional extra)
21490 "Make a regular expression for keyword lines."
21491 (concat
21493 "#?[ \t]*\\+\\("
21494 (mapconcat 'regexp-quote kwds "\\|")
21495 (if extra (concat "\\|" extra))
21496 "\\):[ \t]*"
21497 "\\(.*\\)"))
21499 ;; Make isearch reveal the necessary context
21500 (defun org-isearch-end ()
21501 "Reveal context after isearch exits."
21502 (when isearch-success ; only if search was successful
21503 (if (featurep 'xemacs)
21504 ;; Under XEmacs, the hook is run in the correct place,
21505 ;; we directly show the context.
21506 (org-show-context 'isearch)
21507 ;; In Emacs the hook runs *before* restoring the overlays.
21508 ;; So we have to use a one-time post-command-hook to do this.
21509 ;; (Emacs 22 has a special variable, see function `org-mode')
21510 (unless (and (boundp 'isearch-mode-end-hook-quit)
21511 isearch-mode-end-hook-quit)
21512 ;; Only when the isearch was not quitted.
21513 (org-add-hook 'post-command-hook 'org-isearch-post-command
21514 'append 'local)))))
21516 (defun org-isearch-post-command ()
21517 "Remove self from hook, and show context."
21518 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21519 (org-show-context 'isearch))
21522 ;;;; Integration with and fixes for other packages
21524 ;;; Imenu support
21526 (defvar org-imenu-markers nil
21527 "All markers currently used by Imenu.")
21528 (make-variable-buffer-local 'org-imenu-markers)
21530 (defun org-imenu-new-marker (&optional pos)
21531 "Return a new marker for use by Imenu, and remember the marker."
21532 (let ((m (make-marker)))
21533 (move-marker m (or pos (point)))
21534 (push m org-imenu-markers)
21537 (defun org-imenu-get-tree ()
21538 "Produce the index for Imenu."
21539 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21540 (setq org-imenu-markers nil)
21541 (let* ((n org-imenu-depth)
21542 (re (concat "^" (org-get-limited-outline-regexp)))
21543 (subs (make-vector (1+ n) nil))
21544 (last-level 0)
21545 m level head)
21546 (save-excursion
21547 (save-restriction
21548 (widen)
21549 (goto-char (point-max))
21550 (while (re-search-backward re nil t)
21551 (setq level (org-reduced-level (funcall outline-level)))
21552 (when (and (<= level n)
21553 (looking-at org-complex-heading-regexp))
21554 (setq head (org-link-display-format
21555 (org-match-string-no-properties 4))
21556 m (org-imenu-new-marker))
21557 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21558 (if (>= level last-level)
21559 (push (cons head m) (aref subs level))
21560 (push (cons head (aref subs (1+ level))) (aref subs level))
21561 (loop for i from (1+ level) to n do (aset subs i nil)))
21562 (setq last-level level)))))
21563 (aref subs 1)))
21565 (eval-after-load "imenu"
21566 '(progn
21567 (add-hook 'imenu-after-jump-hook
21568 (lambda ()
21569 (if (derived-mode-p 'org-mode)
21570 (org-show-context 'org-goto))))))
21572 (defun org-link-display-format (link)
21573 "Replace a link with either the description, or the link target
21574 if no description is present"
21575 (save-match-data
21576 (if (string-match org-bracket-link-analytic-regexp link)
21577 (replace-match (if (match-end 5)
21578 (match-string 5 link)
21579 (concat (match-string 1 link)
21580 (match-string 3 link)))
21581 nil t link)
21582 link)))
21584 (defun org-toggle-link-display ()
21585 "Toggle the literal or descriptive display of links."
21586 (interactive)
21587 (if org-descriptive-links
21588 (progn (org-remove-from-invisibility-spec '(org-link))
21589 (org-restart-font-lock)
21590 (setq org-descriptive-links nil))
21591 (progn (add-to-invisibility-spec '(org-link))
21592 (org-restart-font-lock)
21593 (setq org-descriptive-links t))))
21595 ;; Speedbar support
21597 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21598 "Overlay marking the agenda restriction line in speedbar.")
21599 (overlay-put org-speedbar-restriction-lock-overlay
21600 'face 'org-agenda-restriction-lock)
21601 (overlay-put org-speedbar-restriction-lock-overlay
21602 'help-echo "Agendas are currently limited to this item.")
21603 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21605 (defun org-speedbar-set-agenda-restriction ()
21606 "Restrict future agenda commands to the location at point in speedbar.
21607 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21608 (interactive)
21609 (require 'org-agenda)
21610 (let (p m tp np dir txt)
21611 (cond
21612 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21613 'org-imenu t))
21614 (setq m (get-text-property p 'org-imenu-marker))
21615 (with-current-buffer (marker-buffer m)
21616 (goto-char m)
21617 (org-agenda-set-restriction-lock 'subtree)))
21618 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21619 'speedbar-function 'speedbar-find-file))
21620 (setq tp (previous-single-property-change
21621 (1+ p) 'speedbar-function)
21622 np (next-single-property-change
21623 tp 'speedbar-function)
21624 dir (speedbar-line-directory)
21625 txt (buffer-substring-no-properties (or tp (point-min))
21626 (or np (point-max))))
21627 (with-current-buffer (find-file-noselect
21628 (let ((default-directory dir))
21629 (expand-file-name txt)))
21630 (unless (derived-mode-p 'org-mode)
21631 (error "Cannot restrict to non-Org-mode file"))
21632 (org-agenda-set-restriction-lock 'file)))
21633 (t (error "Don't know how to restrict Org-mode's agenda")))
21634 (move-overlay org-speedbar-restriction-lock-overlay
21635 (point-at-bol) (point-at-eol))
21636 (setq current-prefix-arg nil)
21637 (org-agenda-maybe-redo)))
21639 (eval-after-load "speedbar"
21640 '(progn
21641 (speedbar-add-supported-extension ".org")
21642 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21643 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21644 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21645 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21646 (add-hook 'speedbar-visiting-tag-hook
21647 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21649 ;;; Fixes and Hacks for problems with other packages
21651 ;; Make flyspell not check words in links, to not mess up our keymap
21652 (defun org-mode-flyspell-verify ()
21653 "Don't let flyspell put overlays at active buttons, or on
21654 {todo,all-time,additional-option-like}-keywords."
21655 (let ((pos (max (1- (point)) (point-min)))
21656 (word (thing-at-point 'word)))
21657 (and (not (get-text-property pos 'keymap))
21658 (not (get-text-property pos 'org-no-flyspell))
21659 (not (member word org-todo-keywords-1))
21660 (not (member word org-all-time-keywords))
21661 (not (member word org-additional-option-like-keywords)))))
21663 (defun org-remove-flyspell-overlays-in (beg end)
21664 "Remove flyspell overlays in region."
21665 (and (org-bound-and-true-p flyspell-mode)
21666 (fboundp 'flyspell-delete-region-overlays)
21667 (flyspell-delete-region-overlays beg end))
21668 (add-text-properties beg end '(org-no-flyspell t)))
21670 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21671 (eval-after-load "bookmark"
21672 '(if (boundp 'bookmark-after-jump-hook)
21673 ;; We can use the hook
21674 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21675 ;; Hook not available, use advice
21676 (defadvice bookmark-jump (after org-make-visible activate)
21677 "Make the position visible."
21678 (org-bookmark-jump-unhide))))
21680 ;; Make sure saveplace shows the location if it was hidden
21681 (eval-after-load "saveplace"
21682 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21683 "Make the position visible."
21684 (org-bookmark-jump-unhide)))
21686 ;; Make sure ecb shows the location if it was hidden
21687 (eval-after-load "ecb"
21688 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21689 "Make hierarchy visible when jumping into location from ECB tree buffer."
21690 (if (derived-mode-p 'org-mode)
21691 (org-show-context))))
21693 (defun org-bookmark-jump-unhide ()
21694 "Unhide the current position, to show the bookmark location."
21695 (and (derived-mode-p 'org-mode)
21696 (or (outline-invisible-p)
21697 (save-excursion (goto-char (max (point-min) (1- (point))))
21698 (outline-invisible-p)))
21699 (org-show-context 'bookmark-jump)))
21701 ;; Make session.el ignore our circular variable
21702 (eval-after-load "session"
21703 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21705 ;;;; Experimental code
21707 (defun org-closed-in-range ()
21708 "Sparse tree of items closed in a certain time range.
21709 Still experimental, may disappear in the future."
21710 (interactive)
21711 ;; Get the time interval from the user.
21712 (let* ((time1 (org-float-time
21713 (org-read-date nil 'to-time nil "Starting date: ")))
21714 (time2 (org-float-time
21715 (org-read-date nil 'to-time nil "End date:")))
21716 ;; callback function
21717 (callback (lambda ()
21718 (let ((time
21719 (org-float-time
21720 (apply 'encode-time
21721 (org-parse-time-string
21722 (match-string 1))))))
21723 ;; check if time in interval
21724 (and (>= time time1) (<= time time2))))))
21725 ;; make tree, check each match with the callback
21726 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21728 ;;;; Finish up
21730 (provide 'org)
21732 (run-hooks 'org-load-hook)
21734 ;;; org.el ends here